feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes
This commit is contained in:
parent
01ef3293cf
commit
66b6b45ba9
399 changed files with 17828 additions and 11330 deletions
100
packages/ui/__tests__/ds-contract.test.tsx
Normal file
100
packages/ui/__tests__/ds-contract.test.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
AudioVisualizerBar,
|
||||
DoubleBezelCard,
|
||||
GradientWave,
|
||||
InstrumentPanel,
|
||||
Led,
|
||||
MetalCard,
|
||||
PhosphorText,
|
||||
PhysicalButton,
|
||||
ScreenPanel,
|
||||
SegmentControl,
|
||||
StatRing,
|
||||
TactileBadge,
|
||||
TiltCard
|
||||
} from '../src/components/ds'
|
||||
|
||||
describe('디자인 시스템 접근성·역할 계약 (TDD v2.0 Phase 2)', () => {
|
||||
it('PhysicalButton_활성및비활성렌더시_button요소와disabled계약을유지한다', () => {
|
||||
const activeHtml = renderToStaticMarkup(
|
||||
<PhysicalButton tone="accent" aria-label="녹음 시작">
|
||||
시작
|
||||
</PhysicalButton>
|
||||
)
|
||||
expect(activeHtml).toContain('<button')
|
||||
expect(activeHtml).toContain('aria-label="녹음 시작"')
|
||||
expect(activeHtml).toContain('시작')
|
||||
|
||||
const disabledHtml = renderToStaticMarkup(
|
||||
<PhysicalButton disabled trailingIcon={<span data-icon="mic" />}>
|
||||
대기
|
||||
</PhysicalButton>
|
||||
)
|
||||
expect(disabledHtml).toContain('disabled=""')
|
||||
expect(disabledHtml).toContain('aria-hidden="true"')
|
||||
})
|
||||
|
||||
it('SegmentControl_옵션목록렌더시_tablist와선택상태ariaSelected계약을보장한다', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SegmentControl
|
||||
ariaLabel="전사 보기 전환"
|
||||
value="transcript"
|
||||
onChange={() => {}}
|
||||
options={[
|
||||
{ value: 'transcript', label: '전사문', badge: 12 },
|
||||
{ value: 'summary', label: '요약' }
|
||||
]}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('role="tablist"')
|
||||
expect(html).toContain('aria-label="전사 보기 전환"')
|
||||
expect(html).toContain('role="tab"')
|
||||
expect(html).toContain('aria-selected="true"')
|
||||
expect(html).toContain('aria-selected="false"')
|
||||
})
|
||||
|
||||
it('TactileBadge_클릭핸들러유무에따라_대화형button역할만조건부로부여한다', () => {
|
||||
const staticHtml = renderToStaticMarkup(<TactileBadge ledColor="green">연결됨</TactileBadge>)
|
||||
expect(staticHtml).not.toContain('role="button"')
|
||||
expect(staticHtml).toContain('aria-hidden="true"')
|
||||
|
||||
const interactiveHtml = renderToStaticMarkup(
|
||||
<TactileBadge tone="accent" onClick={() => {}}>
|
||||
필터 해제
|
||||
</TactileBadge>
|
||||
)
|
||||
expect(interactiveHtml).toContain('role="button"')
|
||||
expect(interactiveHtml).toContain('tabindex="0"')
|
||||
})
|
||||
|
||||
it('장식지표및패널컴포넌트_렌더시_장식요소ariaHidden과시맨틱태그계약을유지한다', () => {
|
||||
const indicatorsHtml = renderToStaticMarkup(
|
||||
<div>
|
||||
<Led color="amber" pulse />
|
||||
<StatRing color="accent">42</StatRing>
|
||||
<AudioVisualizerBar audioLevel={0.4} aria-label="입력 파형" />
|
||||
<GradientWave />
|
||||
</div>
|
||||
)
|
||||
expect(indicatorsHtml).toContain('aria-hidden="true"')
|
||||
expect(indicatorsHtml).toContain('<canvas')
|
||||
|
||||
const containersHtml = renderToStaticMarkup(
|
||||
<div>
|
||||
<PhosphorText variant="heading" component="h2">
|
||||
섹션 제목
|
||||
</PhosphorText>
|
||||
<InstrumentPanel>계기판</InstrumentPanel>
|
||||
<MetalCard>메탈 카드</MetalCard>
|
||||
<TiltCard>틸트 카드</TiltCard>
|
||||
<ScreenPanel>스크린 패널</ScreenPanel>
|
||||
<DoubleBezelCard>이중 베젤</DoubleBezelCard>
|
||||
</div>
|
||||
)
|
||||
expect(containersHtml).toContain('<h2')
|
||||
expect(containersHtml).toContain('섹션 제목')
|
||||
expect(containersHtml).toContain('이중 베젤')
|
||||
})
|
||||
})
|
||||
256
packages/ui/__tests__/wave-visualizer.test.tsx
Normal file
256
packages/ui/__tests__/wave-visualizer.test.tsx
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const uiHarness = vi.hoisted(() => {
|
||||
interface RefSlot {
|
||||
kind: 'ref'
|
||||
ref: { current: unknown }
|
||||
}
|
||||
interface EffectSlot {
|
||||
kind: 'effect'
|
||||
deps: readonly unknown[] | undefined
|
||||
create: () => void | (() => void)
|
||||
cleanup: (() => void) | undefined
|
||||
}
|
||||
type Slot = RefSlot | EffectSlot
|
||||
|
||||
const slots: Slot[] = []
|
||||
const pendingEffects: number[] = []
|
||||
let cursor = 0
|
||||
|
||||
function depsChanged(
|
||||
prev: readonly unknown[] | undefined,
|
||||
next: readonly unknown[] | undefined,
|
||||
): boolean {
|
||||
if (prev === undefined || next === undefined) return true
|
||||
if (prev.length !== next.length) return true
|
||||
for (let i = 0; i < next.length; i += 1) {
|
||||
if (!Object.is(prev[i], next[i])) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
for (const slot of slots) {
|
||||
if (slot.kind === 'effect' && slot.cleanup) {
|
||||
slot.cleanup()
|
||||
}
|
||||
}
|
||||
slots.length = 0
|
||||
pendingEffects.length = 0
|
||||
cursor = 0
|
||||
}
|
||||
|
||||
function renderComponent(fn: () => unknown): void {
|
||||
cursor = 0
|
||||
fn()
|
||||
const indices = pendingEffects.splice(0)
|
||||
for (const idx of indices) {
|
||||
const slot = slots[idx]
|
||||
if (!slot || slot.kind !== 'effect') continue
|
||||
if (slot.cleanup) {
|
||||
slot.cleanup()
|
||||
slot.cleanup = undefined
|
||||
}
|
||||
const cleanup = slot.create()
|
||||
slot.cleanup = typeof cleanup === 'function' ? cleanup : undefined
|
||||
}
|
||||
}
|
||||
|
||||
function getRef<T>(index = 0): { current: T } {
|
||||
const slot = slots[index]
|
||||
if (!slot || slot.kind !== 'ref') {
|
||||
throw new Error(`Expected ref slot at index ${index}`)
|
||||
}
|
||||
return slot.ref as { current: T }
|
||||
}
|
||||
|
||||
let seededCanvas: unknown = null
|
||||
|
||||
function setCanvasSeed(canvas: unknown): void {
|
||||
seededCanvas = canvas
|
||||
}
|
||||
|
||||
const reactMock = {
|
||||
useRef<T>(initial: T): { current: T } {
|
||||
const idx = cursor++
|
||||
const existing = slots[idx]
|
||||
if (existing && existing.kind === 'ref') {
|
||||
return existing.ref as { current: T }
|
||||
}
|
||||
const value = initial === null && seededCanvas !== null ? (seededCanvas as T) : initial
|
||||
const slot: RefSlot = { kind: 'ref', ref: { current: value } }
|
||||
slots[idx] = slot
|
||||
return slot.ref as { current: T }
|
||||
},
|
||||
useEffect(create: () => void | (() => void), deps?: readonly unknown[]): void {
|
||||
const idx = cursor++
|
||||
const existing = slots[idx]
|
||||
if (!existing || existing.kind !== 'effect') {
|
||||
slots[idx] = { kind: 'effect', deps, create, cleanup: undefined }
|
||||
pendingEffects.push(idx)
|
||||
return
|
||||
}
|
||||
if (depsChanged(existing.deps, deps)) {
|
||||
existing.deps = deps
|
||||
existing.create = create
|
||||
pendingEffects.push(idx)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
return { reset, renderComponent, getRef, setCanvasSeed, reactMock }
|
||||
})
|
||||
|
||||
vi.mock('react', () => ({
|
||||
...uiHarness.reactMock,
|
||||
default: uiHarness.reactMock,
|
||||
}))
|
||||
|
||||
vi.mock('react/jsx-runtime', () => ({
|
||||
Fragment: 'Fragment',
|
||||
jsx: (type: unknown, props: unknown) => ({ type, props }),
|
||||
jsxs: (type: unknown, props: unknown) => ({ type, props }),
|
||||
}))
|
||||
|
||||
vi.mock('react/jsx-dev-runtime', () => ({
|
||||
Fragment: 'Fragment',
|
||||
jsxDEV: (type: unknown, props: unknown) => ({ type, props }),
|
||||
}))
|
||||
|
||||
import { AudioVisualizerBar } from '../src/components/ds/AudioVisualizerBar'
|
||||
import { GradientWave } from '../src/components/ds/GradientWave'
|
||||
import { clampAudioLevel, stepSmoothedAudioLevel } from '../src/components/ds/wave-math'
|
||||
|
||||
interface CanvasProbe {
|
||||
gradientCreates: number
|
||||
roundRectArgs: number[][]
|
||||
stepFrames: (count: number) => void
|
||||
restore: () => void
|
||||
}
|
||||
|
||||
function installCanvasGlobals(width = 240, height = 48): CanvasProbe {
|
||||
const roundRectArgs: number[][] = []
|
||||
let gradientCreates = 0
|
||||
let rafCounter = 0
|
||||
const rafQueue = new Map<number, FrameRequestCallback>()
|
||||
|
||||
const fakeCtx = {
|
||||
setTransform: vi.fn(),
|
||||
clearRect: vi.fn(),
|
||||
beginPath: vi.fn(),
|
||||
fill: vi.fn(),
|
||||
roundRect: (...args: number[]) => {
|
||||
roundRectArgs.push(args)
|
||||
},
|
||||
createLinearGradient: () => {
|
||||
gradientCreates += 1
|
||||
return { addColorStop: vi.fn() }
|
||||
},
|
||||
fillStyle: '',
|
||||
shadowBlur: 0,
|
||||
shadowColor: '',
|
||||
}
|
||||
|
||||
const fakeCanvas = {
|
||||
clientWidth: width,
|
||||
clientHeight: height,
|
||||
width: 0,
|
||||
height: 0,
|
||||
getContext: () => fakeCtx,
|
||||
}
|
||||
|
||||
class MockResizeObserver {
|
||||
observe(): void {}
|
||||
disconnect(): void {}
|
||||
}
|
||||
|
||||
vi.stubGlobal('ResizeObserver', MockResizeObserver)
|
||||
vi.stubGlobal('window', { devicePixelRatio: 1 })
|
||||
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
|
||||
rafCounter += 1
|
||||
rafQueue.set(rafCounter, cb)
|
||||
return rafCounter
|
||||
})
|
||||
vi.stubGlobal('cancelAnimationFrame', (id: number) => {
|
||||
rafQueue.delete(id)
|
||||
})
|
||||
|
||||
// 최초 렌더 후 canvasRef 에 가짜 캔버스를 주입하기 위해 hook 슬롯에 접근할 수 있도록 헬퍼 반환
|
||||
;(installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas = fakeCanvas
|
||||
|
||||
return {
|
||||
get gradientCreates() {
|
||||
return gradientCreates
|
||||
},
|
||||
roundRectArgs,
|
||||
stepFrames(count: number) {
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const next = rafQueue.entries().next()
|
||||
if (next.done) break
|
||||
const [id, cb] = next.value
|
||||
rafQueue.delete(id)
|
||||
cb(i * 16)
|
||||
}
|
||||
},
|
||||
restore() {
|
||||
vi.unstubAllGlobals()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('AudioVisualizerBar & GradientWave 캔버스 안전성과 성능 계약', () => {
|
||||
afterEach(() => {
|
||||
uiHarness.setCanvasSeed(null)
|
||||
uiHarness.reset()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('AudioVisualizerBar_연속프레임렌더시_그라디언트를매프레임재생성하지않고NaN레벨에서도유한한높이를그린다', () => {
|
||||
const probe = installCanvasGlobals(240, 48)
|
||||
const fakeCanvas = (installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas
|
||||
|
||||
uiHarness.setCanvasSeed(fakeCanvas)
|
||||
uiHarness.renderComponent(() => AudioVisualizerBar({ audioLevel: Number.NaN, bars: 12 }))
|
||||
probe.stepFrames(10)
|
||||
|
||||
expect(probe.gradientCreates).toBe(1)
|
||||
expect(probe.roundRectArgs.length).toBe(120)
|
||||
const hasNonFinite = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n)))
|
||||
expect(hasNonFinite).toBe(false)
|
||||
|
||||
// NaN 이후 유효 레벨이 들어와도 smoothedRef가 회복되어 정상 동작해야 한다
|
||||
uiHarness.renderComponent(() => AudioVisualizerBar({ audioLevel: 0.8, bars: 12 }))
|
||||
probe.roundRectArgs.length = 0
|
||||
probe.stepFrames(2)
|
||||
const recoveredHasNaN = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n)))
|
||||
expect(recoveredHasNaN).toBe(false)
|
||||
})
|
||||
|
||||
it('GradientWave_NaN및음수오디오레벨에서도_안전하고유한한좌표만그린다', () => {
|
||||
const probe = installCanvasGlobals(180, 40)
|
||||
const fakeCanvas = (installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas
|
||||
|
||||
uiHarness.setCanvasSeed(fakeCanvas)
|
||||
uiHarness.renderComponent(() => GradientWave({ audioLevel: Number.NaN }))
|
||||
probe.stepFrames(5)
|
||||
|
||||
const hasNaN = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n)))
|
||||
expect(hasNaN).toBe(false)
|
||||
expect(probe.roundRectArgs.length).toBeGreaterThan(0)
|
||||
|
||||
// barWidth + barGap <= 0 이면 무한 루프나 음수 계산 없이 프레임을 건너뛴다
|
||||
uiHarness.reset()
|
||||
probe.roundRectArgs.length = 0
|
||||
uiHarness.setCanvasSeed(fakeCanvas)
|
||||
uiHarness.renderComponent(() => GradientWave({ audioLevel: 0.5, barWidth: 0, barGap: 0 }))
|
||||
probe.stepFrames(2)
|
||||
expect(probe.roundRectArgs).toEqual([])
|
||||
})
|
||||
|
||||
it('waveMath_음수및NaN입력_클램프와스무딩상태회복을보장한다', () => {
|
||||
expect(clampAudioLevel(-0.5)).toBe(0)
|
||||
expect(clampAudioLevel(Number.NaN)).toBe(0)
|
||||
expect(clampAudioLevel(1.8)).toBe(1)
|
||||
expect(stepSmoothedAudioLevel(Number.NaN, 0.5, 0.5, 0.1)).toBe(0.25)
|
||||
})
|
||||
})
|
||||
|
|
@ -4,6 +4,9 @@
|
|||
"private": true,
|
||||
"description": "D3RO Voice 공유 UI — 디자인 시스템 컴포넌트 + 테마 토큰 + CSS 변수 맵",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "vitest run --config vitest.config.ts"
|
||||
},
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@
|
|||
import React, { useRef, useEffect } from 'react'
|
||||
import { Box, type BoxProps } from '@mui/material'
|
||||
import { d3roRadius } from '../../theme'
|
||||
import { RAW } from '../../theme-raw'
|
||||
|
||||
/** SSR/무-문서 환경 폴백 — 테마 원시값에서 가져온다(하드코딩 hex 금지). */
|
||||
const WAVE_FALLBACK = RAW.dark.gradient
|
||||
import {
|
||||
buildWaveLinearGradient,
|
||||
readWaveGradientColors,
|
||||
stepSmoothedAudioLevel,
|
||||
} from './wave-math'
|
||||
|
||||
export interface AudioVisualizerBarProps extends Omit<BoxProps, 'children'> {
|
||||
/** Real-time normalized audio RMS level (0.0 to 1.0) */
|
||||
|
|
@ -26,19 +27,6 @@ export interface AudioVisualizerBarProps extends Omit<BoxProps, 'children'> {
|
|||
active?: boolean
|
||||
}
|
||||
|
||||
function readVisualizerColors(): [string, string, string, string] {
|
||||
const fallback = [WAVE_FALLBACK.wave1, WAVE_FALLBACK.wave2, WAVE_FALLBACK.wave3, WAVE_FALLBACK.wave4]
|
||||
if (typeof document === 'undefined') return [fallback[0], fallback[1], fallback[2], fallback[3]]
|
||||
const style = getComputedStyle(document.documentElement)
|
||||
const read = (name: string, fb: string): string => style.getPropertyValue(name).trim() || fb
|
||||
return [
|
||||
read('--d3-gradient-wave1', fallback[0]),
|
||||
read('--d3-gradient-wave2', fallback[1]),
|
||||
read('--d3-gradient-wave3', fallback[2]),
|
||||
read('--d3-gradient-wave4', fallback[3]),
|
||||
]
|
||||
}
|
||||
|
||||
export function AudioVisualizerBar({
|
||||
audioLevel = 0,
|
||||
bars = 32,
|
||||
|
|
@ -66,9 +54,14 @@ export function AudioVisualizerBar({
|
|||
let raf = 0
|
||||
let width = 0
|
||||
let heightPx = height
|
||||
let colors = readVisualizerColors()
|
||||
let colors = readWaveGradientColors()
|
||||
let gradient: CanvasGradient | null = null
|
||||
let frame = 0
|
||||
|
||||
const rebuildGradient = (): void => {
|
||||
gradient = width > 0 ? buildWaveLinearGradient(ctx, width, colors) : null
|
||||
}
|
||||
|
||||
const resize = (): void => {
|
||||
const dpr = window.devicePixelRatio || 1
|
||||
width = canvas.clientWidth
|
||||
|
|
@ -76,6 +69,7 @@ export function AudioVisualizerBar({
|
|||
canvas.width = Math.max(1, Math.round(width * dpr))
|
||||
canvas.height = Math.max(1, Math.round(heightPx * dpr))
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
rebuildGradient()
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(resize)
|
||||
|
|
@ -85,36 +79,37 @@ export function AudioVisualizerBar({
|
|||
const render = (): void => {
|
||||
frame += 1
|
||||
if (frame % 60 === 0) {
|
||||
colors = readVisualizerColors()
|
||||
const next = readWaveGradientColors()
|
||||
if (next.join() !== colors.join()) {
|
||||
colors = next
|
||||
rebuildGradient()
|
||||
}
|
||||
}
|
||||
|
||||
// Smooth audio RMS response
|
||||
const target = Math.min(1, levelRef.current)
|
||||
const k = target > smoothedRef.current ? 0.35 : 0.08
|
||||
smoothedRef.current += (target - smoothedRef.current) * k
|
||||
// Smooth audio RMS response (NaN/범위 밖 입력 시 상태 오염 방지)
|
||||
smoothedRef.current = stepSmoothedAudioLevel(
|
||||
smoothedRef.current,
|
||||
levelRef.current,
|
||||
0.35,
|
||||
0.08,
|
||||
)
|
||||
|
||||
ctx.clearRect(0, 0, width, heightPx)
|
||||
|
||||
if (width <= 0 || heightPx <= 0) {
|
||||
const totalStep = barWidth + gap
|
||||
const safeBars = Number.isFinite(bars) ? Math.max(0, Math.floor(bars)) : 0
|
||||
const actualBars = totalStep > 0 ? Math.min(safeBars, Math.floor(width / totalStep)) : 0
|
||||
if (!gradient || width <= 0 || heightPx <= 0 || totalStep <= 0 || barWidth <= 0 || actualBars <= 0) {
|
||||
raf = requestAnimationFrame(render)
|
||||
return
|
||||
}
|
||||
|
||||
const totalStep = barWidth + gap
|
||||
const actualBars = Math.min(bars, Math.floor(width / totalStep))
|
||||
const totalWidth = actualBars * totalStep - gap
|
||||
const startX = (width - totalWidth) / 2
|
||||
const centerY = heightPx / 2
|
||||
const t = performance.now() / 1000
|
||||
|
||||
// Create harmonious gradient for bars
|
||||
const grad = ctx.createLinearGradient(0, 0, width, 0)
|
||||
grad.addColorStop(0, colors[0])
|
||||
grad.addColorStop(0.35, colors[1])
|
||||
grad.addColorStop(0.7, colors[2])
|
||||
grad.addColorStop(1, colors[3])
|
||||
|
||||
ctx.fillStyle = grad
|
||||
ctx.fillStyle = gradient
|
||||
|
||||
for (let i = 0; i < actualBars; i++) {
|
||||
const x = startX + i * totalStep
|
||||
|
|
|
|||
|
|
@ -7,10 +7,11 @@
|
|||
|
||||
import { useRef, useEffect } from 'react'
|
||||
import { Box } from '@mui/material'
|
||||
import { RAW } from '../../theme-raw'
|
||||
|
||||
/** SSR/무-문서 환경 폴백 — 테마 원시값에서 가져온다(하드코딩 hex 금지). */
|
||||
const WAVE_FALLBACK = RAW.dark.gradient
|
||||
import {
|
||||
buildWaveLinearGradient,
|
||||
readWaveGradientColors,
|
||||
stepSmoothedAudioLevel,
|
||||
} from './wave-math'
|
||||
|
||||
interface GradientWaveProps {
|
||||
/** 실시간 오디오 레벨 0~1 (없으면 유휴 애니메이션만) */
|
||||
|
|
@ -29,21 +30,6 @@ interface GradientWaveProps {
|
|||
height?: number | string
|
||||
}
|
||||
|
||||
/** :root에 주입된 웨이브 그라디언트 스톱을 읽는다 */
|
||||
function readWaveColors(): [string, string, string, string] {
|
||||
const fallback = [WAVE_FALLBACK.wave1, WAVE_FALLBACK.wave2, WAVE_FALLBACK.wave3, WAVE_FALLBACK.wave4]
|
||||
if (typeof document === 'undefined') return [fallback[0], fallback[1], fallback[2], fallback[3]]
|
||||
const style = getComputedStyle(document.documentElement)
|
||||
const read = (name: string, fb: string): string =>
|
||||
style.getPropertyValue(name).trim() || fb
|
||||
return [
|
||||
read('--d3-gradient-wave1', fallback[0]),
|
||||
read('--d3-gradient-wave2', fallback[1]),
|
||||
read('--d3-gradient-wave3', fallback[2]),
|
||||
read('--d3-gradient-wave4', fallback[3]),
|
||||
]
|
||||
}
|
||||
|
||||
/** 결정적 의사난수 (바 인덱스별 고정 시드) */
|
||||
function seeded(i: number): number {
|
||||
const x = Math.sin(i * 127.1 + 311.7) * 43758.5453
|
||||
|
|
@ -76,17 +62,16 @@ export function GradientWave({
|
|||
let raf = 0
|
||||
let width = 0
|
||||
let heightPx = 0
|
||||
let colors = readWaveColors()
|
||||
let colors = readWaveGradientColors()
|
||||
let gradient: CanvasGradient | null = null
|
||||
let frame = 0
|
||||
const start = performance.now()
|
||||
const safeIdleAmplitude = Number.isFinite(idleAmplitude) ? Math.max(0, Math.min(1, idleAmplitude)) : 0
|
||||
const safeSpeed = Number.isFinite(speed) ? Math.max(0, speed) : 1
|
||||
const safeGlow = Number.isFinite(glow) ? Math.max(0, glow) : 0
|
||||
|
||||
const rebuildGradient = (): void => {
|
||||
gradient = ctx.createLinearGradient(0, 0, width, 0)
|
||||
gradient.addColorStop(0, colors[0])
|
||||
gradient.addColorStop(0.38, colors[1])
|
||||
gradient.addColorStop(0.7, colors[2])
|
||||
gradient.addColorStop(1, colors[3])
|
||||
gradient = width > 0 ? buildWaveLinearGradient(ctx, width, colors) : null
|
||||
}
|
||||
|
||||
const resize = (): void => {
|
||||
|
|
@ -107,33 +92,36 @@ export function GradientWave({
|
|||
frame += 1
|
||||
// 테마 전환 대응: 1초마다 색 재판독
|
||||
if (frame % 60 === 0) {
|
||||
const next = readWaveColors()
|
||||
const next = readWaveGradientColors()
|
||||
if (next.join() !== colors.join()) {
|
||||
colors = next
|
||||
rebuildGradient()
|
||||
}
|
||||
}
|
||||
|
||||
// 레벨 스무딩 (상승 빠르게, 하강 느리게)
|
||||
const target = Math.min(1, levelRef.current)
|
||||
const k = target > smoothedRef.current ? 0.4 : 0.08
|
||||
smoothedRef.current += (target - smoothedRef.current) * k
|
||||
// 레벨 스무딩 (상승 빠르게, 하강 느리게; NaN/범위 밖 방어)
|
||||
smoothedRef.current = stepSmoothedAudioLevel(
|
||||
smoothedRef.current,
|
||||
levelRef.current,
|
||||
0.4,
|
||||
0.08,
|
||||
)
|
||||
|
||||
ctx.clearRect(0, 0, width, heightPx)
|
||||
if (!gradient || width <= 0) {
|
||||
const step = barWidth + barGap
|
||||
if (!gradient || width <= 0 || heightPx <= 0 || step <= 0 || barWidth <= 0) {
|
||||
raf = requestAnimationFrame(render)
|
||||
return
|
||||
}
|
||||
|
||||
const t = ((performance.now() - start) / 1000) * speed
|
||||
const step = barWidth + barGap
|
||||
const t = ((performance.now() - start) / 1000) * safeSpeed
|
||||
const count = Math.max(1, Math.floor(width / step))
|
||||
const centerY = heightPx / 2
|
||||
const maxHalf = heightPx / 2 - 1
|
||||
const maxHalf = Math.max(1.5, heightPx / 2 - 1)
|
||||
|
||||
ctx.fillStyle = gradient
|
||||
if (glow > 0) {
|
||||
ctx.shadowBlur = glow
|
||||
if (safeGlow > 0) {
|
||||
ctx.shadowBlur = safeGlow
|
||||
ctx.shadowColor = colors[1]
|
||||
}
|
||||
|
||||
|
|
@ -144,7 +132,7 @@ export function GradientWave({
|
|||
const idle =
|
||||
(Math.sin(t * 1.4 + i * 0.35) * 0.5 + 0.5) * 0.55 +
|
||||
(Math.sin(t * 0.7 + i * 0.11 + s * 6.28) * 0.5 + 0.5) * 0.45
|
||||
const envelope = idleAmplitude * (0.25 + idle * 0.75) + smoothedRef.current * (0.4 + s * 0.6)
|
||||
const envelope = safeIdleAmplitude * (0.25 + idle * 0.75) + smoothedRef.current * (0.4 + s * 0.6)
|
||||
const half = Math.max(1.5, Math.min(1, envelope) * maxHalf)
|
||||
const radius = Math.min(barWidth / 2, half)
|
||||
ctx.beginPath()
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
import React from 'react'
|
||||
import { Box, Typography } from '@mui/material'
|
||||
import { d3roPalette, d3roRadius, d3roShadow, typoSx } from '../../theme'
|
||||
import { d3roFocusRing, d3roPalette, d3roRadius, d3roShadow, typoSx } from '../../theme'
|
||||
|
||||
export interface SegmentOption<T extends string = string> {
|
||||
value: T
|
||||
|
|
@ -20,6 +20,7 @@ export interface SegmentControlProps<T extends string = string> {
|
|||
items?: SegmentOption<T>[]
|
||||
value: T
|
||||
onChange: (value: T) => void
|
||||
ariaLabel?: string
|
||||
size?: 'small' | 'medium'
|
||||
sx?: object
|
||||
}
|
||||
|
|
@ -29,6 +30,7 @@ export function SegmentControl<T extends string = string>({
|
|||
items,
|
||||
value,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
size = 'medium',
|
||||
sx,
|
||||
}: SegmentControlProps<T>): React.ReactElement {
|
||||
|
|
@ -37,6 +39,8 @@ export function SegmentControl<T extends string = string>({
|
|||
|
||||
return (
|
||||
<Box
|
||||
role="tablist"
|
||||
aria-label={ariaLabel}
|
||||
sx={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
|
|
@ -53,7 +57,16 @@ export function SegmentControl<T extends string = string>({
|
|||
return (
|
||||
<Box
|
||||
key={opt.value}
|
||||
role="tab"
|
||||
aria-selected={isSelected}
|
||||
tabIndex={isSelected ? 0 : -1}
|
||||
onClick={() => onChange(opt.value)}
|
||||
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
onChange(opt.value)
|
||||
}
|
||||
}}
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
|
|
@ -72,6 +85,7 @@ export function SegmentControl<T extends string = string>({
|
|||
color: d3roPalette.text.primary,
|
||||
bgcolor: isSelected ? d3roPalette.glass.raised : d3roPalette.glass.surface,
|
||||
},
|
||||
'&:focus-visible': d3roFocusRing,
|
||||
'&:active': {
|
||||
transform: 'scale(0.97)',
|
||||
},
|
||||
|
|
|
|||
53
packages/ui/src/components/ds/wave-math.ts
Normal file
53
packages/ui/src/components/ds/wave-math.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { RAW } from '../../theme-raw'
|
||||
|
||||
/** SSR/무-문서 환경 폴백 — 테마 원시값에서 가져온다(하드코딩 hex 금지). */
|
||||
const WAVE_FALLBACK = RAW.dark.gradient
|
||||
|
||||
export type WaveGradientColors = readonly [string, string, string, string]
|
||||
|
||||
export function readWaveGradientColors(): WaveGradientColors {
|
||||
const fallback: WaveGradientColors = [
|
||||
WAVE_FALLBACK.wave1,
|
||||
WAVE_FALLBACK.wave2,
|
||||
WAVE_FALLBACK.wave3,
|
||||
WAVE_FALLBACK.wave4,
|
||||
]
|
||||
if (typeof document === 'undefined') return fallback
|
||||
const style = getComputedStyle(document.documentElement)
|
||||
const read = (name: string, fb: string): string => style.getPropertyValue(name).trim() || fb
|
||||
return [
|
||||
read('--d3-gradient-wave1', fallback[0]),
|
||||
read('--d3-gradient-wave2', fallback[1]),
|
||||
read('--d3-gradient-wave3', fallback[2]),
|
||||
read('--d3-gradient-wave4', fallback[3]),
|
||||
]
|
||||
}
|
||||
|
||||
export function clampAudioLevel(level: number): number {
|
||||
return Number.isFinite(level) ? Math.max(0, Math.min(1, level)) : 0
|
||||
}
|
||||
|
||||
export function stepSmoothedAudioLevel(
|
||||
currentSmoothed: number,
|
||||
rawLevel: number,
|
||||
attack = 0.35,
|
||||
release = 0.08,
|
||||
): number {
|
||||
const safeCurrent = Number.isFinite(currentSmoothed) ? Math.max(0, Math.min(1, currentSmoothed)) : 0
|
||||
const target = clampAudioLevel(rawLevel)
|
||||
const k = target > safeCurrent ? attack : release
|
||||
return safeCurrent + (target - safeCurrent) * k
|
||||
}
|
||||
|
||||
export function buildWaveLinearGradient(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
width: number,
|
||||
colors: WaveGradientColors,
|
||||
): CanvasGradient {
|
||||
const grad = ctx.createLinearGradient(0, 0, width, 0)
|
||||
grad.addColorStop(0, colors[0])
|
||||
grad.addColorStop(0.38, colors[1])
|
||||
grad.addColorStop(0.7, colors[2])
|
||||
grad.addColorStop(1, colors[3])
|
||||
return grad
|
||||
}
|
||||
18
packages/ui/vitest.config.ts
Normal file
18
packages/ui/vitest.config.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { resolve } from 'path'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
esbuild: {
|
||||
jsx: 'automatic'
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['__tests__/**/*.test.{ts,tsx}']
|
||||
},
|
||||
resolve: {
|
||||
alias: [
|
||||
{ find: /^@d3ro\/core(\/.*)?$/, replacement: `${resolve(__dirname, '../core/src')}$1` }
|
||||
]
|
||||
}
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue