@fanvue/ui 3.16.0 → 3.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/AudioPlayer/AudioPlayer.cjs +16 -89
- package/dist/cjs/components/AudioPlayer/AudioPlayer.cjs.map +1 -1
- package/dist/cjs/components/VoiceNote/VoiceNote.cjs +305 -0
- package/dist/cjs/components/VoiceNote/VoiceNote.cjs.map +1 -0
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/utils/audioWaveform.cjs +76 -0
- package/dist/cjs/utils/audioWaveform.cjs.map +1 -0
- package/dist/cjs/utils/useAudioPlayback.cjs +123 -0
- package/dist/cjs/utils/useAudioPlayback.cjs.map +1 -0
- package/dist/cjs/utils/useFittedBarCount.cjs +42 -0
- package/dist/cjs/utils/useFittedBarCount.cjs.map +1 -0
- package/dist/cjs/utils/useWaveformPeaks.cjs +48 -0
- package/dist/cjs/utils/useWaveformPeaks.cjs.map +1 -0
- package/dist/cjs/utils/useWaveformSeek.cjs +100 -0
- package/dist/cjs/utils/useWaveformSeek.cjs.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.mjs +7 -80
- package/dist/components/AudioPlayer/AudioPlayer.mjs.map +1 -1
- package/dist/components/VoiceNote/VoiceNote.mjs +288 -0
- package/dist/components/VoiceNote/VoiceNote.mjs.map +1 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -1
- package/dist/styles/base.css +11 -2
- package/dist/utils/audioWaveform.mjs +76 -0
- package/dist/utils/audioWaveform.mjs.map +1 -0
- package/dist/utils/useAudioPlayback.mjs +106 -0
- package/dist/utils/useAudioPlayback.mjs.map +1 -0
- package/dist/utils/useFittedBarCount.mjs +25 -0
- package/dist/utils/useFittedBarCount.mjs.map +1 -0
- package/dist/utils/useWaveformPeaks.mjs +31 -0
- package/dist/utils/useWaveformPeaks.mjs.map +1 -0
- package/dist/utils/useWaveformSeek.mjs +83 -0
- package/dist/utils/useWaveformSeek.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AudioPlayer.mjs","sources":["../../../src/components/AudioPlayer/AudioPlayer.tsx"],"sourcesContent":["import * as React from \"react\";\nimport { cn } from \"../../utils/cn\";\nimport { PauseIcon } from \"../Icons/PauseIcon\";\nimport { PlayIcon } from \"../Icons/PlayIcon\";\n\n/** Width of a single waveform bar, in pixels. */\nconst BAR_WIDTH_PX = 4;\n/** Gap between waveform bars, in pixels. */\nconst BAR_GAP_PX = 4;\n/** Shortest a waveform bar can render, in pixels. */\nconst MIN_BAR_HEIGHT_PX = 4;\n/** Tallest a waveform bar can render, in pixels — matches the 40px row height. */\nconst MAX_BAR_HEIGHT_PX = 26;\n/** Bar count used before the container has been measured (e.g. during SSR or in jsdom, where layout is unavailable). */\nconst DEFAULT_BAR_COUNT = 24;\n/** Number of amplitude samples kept internally, resampled to the rendered bar count. */\nconst RAW_PEAK_COUNT = 128;\n/** Seconds moved per Arrow key press while seeking. */\nconst SEEK_STEP_SECONDS = 1;\n/** Seconds moved per Page Up/Down press while seeking. */\nconst SEEK_STEP_LARGE_SECONDS = 5;\n\n/** Height of the audio player row, in pixels. Matches both the Vault card overlay and the \"Generated Audio\" modal row in Figma — both use an identical 32px play button and 40px row. */\nexport type AudioPlayerSize = \"40\";\n\nexport interface AudioPlayerProps\n extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onPlay\" | \"onPause\" | \"onEnded\"> {\n /** URL of the audio file to play. */\n src: string;\n /**\n * Total duration in seconds, used to render the timestamp before the\n * media's own metadata has loaded (and as a fallback if it never does).\n */\n duration?: number;\n /**\n * Whether playback is active (controlled). Note: once `onEnded` fires, the\n * browser has already stopped native playback. To loop or replay under\n * controlled usage, toggle this prop `false` then `true` (rather than\n * leaving it `true`) — the sync effect only calls `play()` again when this\n * value actually changes.\n */\n playing?: boolean;\n /** Initial playback state (uncontrolled). @default false */\n defaultPlaying?: boolean;\n /** Called when playback starts. */\n onPlay?: () => void;\n /** Called when playback is paused. */\n onPause?: () => void;\n /** Called when playback reaches the end of the media. */\n onEnded?: () => void;\n /** Height of the player row, in pixels. @default \"40\" */\n size?: AudioPlayerSize;\n}\n\nfunction formatTime(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds)) return \"--:--\";\n const totalSeconds = Math.max(0, Math.floor(seconds));\n const minutes = Math.floor(totalSeconds / 60);\n const remainingSeconds = totalSeconds % 60;\n return `${minutes}:${String(remainingSeconds).padStart(2, \"0\")}`;\n}\n\n/** Deterministic 32-bit string hash (FNV-1a), used to seed the fallback waveform. */\nfunction hashString(value: string): number {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return hash >>> 0;\n}\n\n/** Seeded PRNG (mulberry32) — deterministic across runs, unlike `Math.random`. */\nfunction createSeededRandom(seed: number): () => number {\n let state = seed;\n return () => {\n state = (state + 0x6d2b79f5) | 0;\n let t = Math.imul(state ^ (state >>> 15), 1 | state);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** Deterministic placeholder amplitudes used when audio can't be decoded (network/CORS/format failure). */\nfunction generateFallbackPeaks(src: string, count: number): number[] {\n const random = createSeededRandom(hashString(src));\n return Array.from({ length: count }, () => 0.2 + random() * 0.8);\n}\n\n/** Downsamples decoded PCM data to `count` peak (max-abs) amplitudes. */\nfunction computePeaksFromChannelData(channelData: Float32Array, count: number): number[] {\n const blockSize = Math.max(1, Math.floor(channelData.length / count));\n const peaks: number[] = [];\n for (let i = 0; i < count; i++) {\n const start = i * blockSize;\n let max = 0;\n for (let j = 0; j < blockSize && start + j < channelData.length; j++) {\n max = Math.max(max, Math.abs(channelData[start + j] ?? 0));\n }\n peaks.push(max);\n }\n return peaks;\n}\n\n/** Resamples a peaks array to the number of bars that currently fit the container. */\nfunction resamplePeaks(peaks: number[], barCount: number): number[] {\n if (peaks.length === 0 || barCount <= 0) return [];\n const step = peaks.length / barCount;\n return Array.from(\n { length: barCount },\n (_, i) => peaks[Math.min(peaks.length - 1, Math.floor(i * step))] ?? 0,\n );\n}\n\n/** Decodes `src` via WebAudio and returns downsampled peak amplitudes. Throws on any failure. */\nasync function decodeAudioPeaks(src: string, signal: AbortSignal): Promise<number[]> {\n const AudioContextCtor =\n window.AudioContext ??\n (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (!AudioContextCtor) throw new Error(\"WebAudio unsupported\");\n\n const response = await fetch(src, { signal });\n const arrayBuffer = await response.arrayBuffer();\n const audioContext = new AudioContextCtor();\n try {\n const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);\n return computePeaksFromChannelData(audioBuffer.getChannelData(0), RAW_PEAK_COUNT);\n } finally {\n if (audioContext.state !== \"closed\") audioContext.close().catch(() => {});\n }\n}\n\n/**\n * A compact playback control for a single audio clip: a play/pause toggle, a\n * static amplitude waveform that doubles as a seek scrubber, and elapsed/total\n * timestamps. Designed to sit as an overlay on media thumbnails (Vault cards)\n * as well as inline rows (the AI Voice Message \"Generated Audio\" row).\n *\n * The waveform is seeded from the decoded audio when possible, falling back\n * to a deterministic (not random) placeholder derived from `src` so the\n * result is stable across renders, SSR, and Chromatic snapshots.\n *\n * @example\n * ```tsx\n * <AudioPlayer src=\"https://example.com/clip.mp3\" duration={5} />\n * ```\n */\nexport const AudioPlayer = React.forwardRef<HTMLDivElement, AudioPlayerProps>(\n (\n {\n className,\n src,\n duration,\n playing: controlledPlaying,\n defaultPlaying = false,\n onPlay,\n onPause,\n onEnded,\n size = \"40\",\n ...props\n },\n ref,\n ) => {\n const audioRef = React.useRef<HTMLAudioElement>(null);\n const trackRef = React.useRef<HTMLDivElement>(null);\n\n const [internalPlaying, setInternalPlaying] = React.useState(defaultPlaying);\n const isControlled = controlledPlaying !== undefined;\n const playing = isControlled ? controlledPlaying : internalPlaying;\n\n const [currentTime, setCurrentTime] = React.useState(0);\n const [mediaDuration, setMediaDuration] = React.useState<number | undefined>(undefined);\n const [barCount, setBarCount] = React.useState(DEFAULT_BAR_COUNT);\n const [peaks, setPeaks] = React.useState<number[]>(() =>\n generateFallbackPeaks(src, RAW_PEAK_COUNT),\n );\n const [isDragging, setIsDragging] = React.useState(false);\n\n const displayDuration = mediaDuration ?? duration;\n const hasStarted = playing || currentTime > 0;\n\n // Latest-value refs so the src-change effect below can react to a src swap\n // without re-running whenever `playing`/`isControlled`/`onPause` change.\n const playingRef = React.useRef(playing);\n playingRef.current = playing;\n const isControlledRef = React.useRef(isControlled);\n isControlledRef.current = isControlled;\n const onPauseRef = React.useRef(onPause);\n onPauseRef.current = onPause;\n\n // Reset transient playback state when the source changes. Skips the\n // initial mount (there's nothing to reset yet) and, if playback was\n // active, stops it — the browser silently drops playback on a source\n // swap, so the UI (and any controlled parent) must be told via onPause.\n const isFirstSrcRenderRef = React.useRef(true);\n React.useEffect(() => {\n if (isFirstSrcRenderRef.current) {\n isFirstSrcRenderRef.current = false;\n return;\n }\n setCurrentTime(0);\n setMediaDuration(undefined);\n setPeaks(generateFallbackPeaks(src, RAW_PEAK_COUNT));\n if (playingRef.current) {\n if (!isControlledRef.current) setInternalPlaying(false);\n onPauseRef.current?.();\n }\n }, [src]);\n\n // Decode the audio to derive real waveform amplitudes, falling back to a\n // deterministic placeholder on any failure (network, CORS, unsupported format).\n React.useEffect(() => {\n let cancelled = false;\n const abortController = new AbortController();\n\n decodeAudioPeaks(src, abortController.signal)\n .then((decodedPeaks) => {\n if (!cancelled) setPeaks(decodedPeaks);\n })\n .catch(() => {\n if (!cancelled) setPeaks(generateFallbackPeaks(src, RAW_PEAK_COUNT));\n });\n\n return () => {\n cancelled = true;\n abortController.abort();\n };\n }, [src]);\n\n // Measure the track to decide how many bars fit; falls back to DEFAULT_BAR_COUNT\n // when layout is unavailable (SSR, jsdom).\n React.useEffect(() => {\n const track = trackRef.current;\n if (!track) return;\n\n const updateFromWidth = (width: number) => {\n if (width <= 0) return;\n setBarCount(Math.max(1, Math.floor((width + BAR_GAP_PX) / (BAR_WIDTH_PX + BAR_GAP_PX))));\n };\n\n updateFromWidth(track.getBoundingClientRect().width);\n\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry) updateFromWidth(entry.contentRect.width);\n });\n observer.observe(track);\n return () => observer.disconnect();\n }, []);\n\n // Sync the controlled/uncontrolled `playing` state to the media element.\n React.useEffect(() => {\n const audio = audioRef.current;\n if (!audio) return;\n if (playing) {\n audio.play().catch(() => {\n if (!isControlled) setInternalPlaying(false);\n onPauseRef.current?.();\n });\n } else {\n audio.pause();\n }\n }, [playing, isControlled]);\n\n const handleToggle = () => {\n const next = !playing;\n if (!isControlled) setInternalPlaying(next);\n if (next) onPlay?.();\n else onPause?.();\n };\n\n const seekTo = React.useCallback(\n (time: number) => {\n if (displayDuration === undefined) return;\n const clamped = Math.min(Math.max(time, 0), displayDuration);\n setCurrentTime(clamped);\n const audio = audioRef.current;\n if (audio) audio.currentTime = clamped;\n },\n [displayDuration],\n );\n\n const seekFromClientX = React.useCallback(\n (clientX: number) => {\n const track = trackRef.current;\n if (!track || displayDuration === undefined) return;\n const rect = track.getBoundingClientRect();\n if (rect.width <= 0) return;\n const fraction = Math.min(Math.max((clientX - rect.left) / rect.width, 0), 1);\n seekTo(fraction * displayDuration);\n },\n [displayDuration, seekTo],\n );\n\n // Track drag outside the element via window listeners rather than pointer\n // capture, which some environments (and jsdom) don't fully implement.\n React.useEffect(() => {\n if (!isDragging) return;\n const handleWindowPointerMove = (event: PointerEvent) => seekFromClientX(event.clientX);\n const handleWindowPointerUp = () => setIsDragging(false);\n window.addEventListener(\"pointermove\", handleWindowPointerMove);\n window.addEventListener(\"pointerup\", handleWindowPointerUp);\n return () => {\n window.removeEventListener(\"pointermove\", handleWindowPointerMove);\n window.removeEventListener(\"pointerup\", handleWindowPointerUp);\n };\n }, [isDragging, seekFromClientX]);\n\n const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n seekFromClientX(event.clientX);\n setIsDragging(true);\n };\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (displayDuration === undefined) return;\n switch (event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n event.preventDefault();\n seekTo(currentTime + SEEK_STEP_SECONDS);\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n event.preventDefault();\n seekTo(currentTime - SEEK_STEP_SECONDS);\n break;\n case \"PageUp\":\n event.preventDefault();\n seekTo(currentTime + SEEK_STEP_LARGE_SECONDS);\n break;\n case \"PageDown\":\n event.preventDefault();\n seekTo(currentTime - SEEK_STEP_LARGE_SECONDS);\n break;\n case \"Home\":\n event.preventDefault();\n seekTo(0);\n break;\n case \"End\":\n event.preventDefault();\n seekTo(displayDuration);\n break;\n default:\n break;\n }\n };\n\n const bars = resamplePeaks(peaks, barCount);\n const progressFraction =\n displayDuration && displayDuration > 0\n ? Math.min(Math.max(currentTime / displayDuration, 0), 1)\n : 0;\n const playedBarCount = hasStarted ? Math.round(progressFraction * bars.length) : bars.length;\n const barData = bars.map((amplitude, index) => {\n const isPlayed = index < playedBarCount;\n return {\n heightPx: MIN_BAR_HEIGHT_PX + amplitude * (MAX_BAR_HEIGHT_PX - MIN_BAR_HEIGHT_PX),\n className: cn(\n \"w-1 shrink-0 rounded-3xs bg-messages-waveform-default\",\n \"motion-safe:transition-opacity motion-safe:duration-150 motion-safe:ease-in-out\",\n isPlayed ? \"opacity-100\" : \"opacity-50\",\n ),\n };\n });\n\n return (\n <div\n ref={ref}\n data-size={size}\n className={cn(\"flex w-full items-center gap-3\", className)}\n {...props}\n >\n <button\n type=\"button\"\n onClick={handleToggle}\n aria-label={playing ? \"Pause\" : \"Play\"}\n className={cn(\n \"flex size-8 shrink-0 items-center justify-center rounded-full\",\n \"bg-buttons-secondary-default text-icons-primary backdrop-blur-[40px]\",\n \"motion-safe:transition-colors motion-safe:duration-150 motion-safe:ease-in-out\",\n \"hover:bg-buttons-secondary-hover\",\n \"focus-visible:shadow-focus-ring focus-visible:outline-none\",\n )}\n >\n {playing ? <PauseIcon size={16} filled /> : <PlayIcon size={16} filled />}\n </button>\n\n <div className=\"flex min-w-0 flex-1 items-center gap-3\">\n <div\n ref={trackRef}\n role=\"slider\"\n tabIndex={0}\n aria-label=\"Seek\"\n aria-orientation=\"horizontal\"\n aria-valuemin={0}\n aria-valuemax={displayDuration}\n aria-valuenow={Math.round(currentTime)}\n aria-valuetext={\n displayDuration !== undefined\n ? `${formatTime(currentTime)} of ${formatTime(displayDuration)}`\n : formatTime(currentTime)\n }\n onPointerDown={handlePointerDown}\n onKeyDown={handleKeyDown}\n className={cn(\n \"flex h-10 min-w-0 flex-1 cursor-pointer touch-none select-none items-center gap-1 overflow-hidden\",\n \"focus-visible:shadow-focus-ring focus-visible:outline-none\",\n )}\n >\n {barData.map((bar, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: bars are a fixed-count, non-reorderable list\n <span key={index} className={bar.className} style={{ height: bar.heightPx }} />\n ))}\n </div>\n\n <span className=\"typography-body-small-14px-semibold flex shrink-0 items-center gap-0.5 whitespace-nowrap\">\n {hasStarted ? (\n <>\n <span className=\"text-content-primary\">{formatTime(currentTime)}</span>\n <span className=\"text-content-secondary\">/{formatTime(displayDuration)}</span>\n </>\n ) : (\n <span className=\"text-content-primary\">{formatTime(displayDuration)}</span>\n )}\n </span>\n </div>\n\n {/* biome-ignore lint/a11y/useMediaCaption: this is a UI sound clip (voice note / short recording), not spoken/narrated content requiring captions. */}\n <audio\n ref={audioRef}\n src={src}\n preload=\"metadata\"\n className=\"hidden\"\n onLoadedMetadata={(event) => {\n const { duration: nativeDuration } = event.currentTarget;\n setMediaDuration(Number.isFinite(nativeDuration) ? nativeDuration : undefined);\n }}\n onTimeUpdate={(event) => {\n if (isDragging) return;\n setCurrentTime(event.currentTarget.currentTime);\n }}\n onEnded={() => {\n setCurrentTime(0);\n if (!isControlled) setInternalPlaying(false);\n onEnded?.();\n }}\n />\n </div>\n );\n },\n);\n\nAudioPlayer.displayName = \"AudioPlayer\";\n"],"names":[],"mappings":";;;;;;AAMA,MAAM,eAAe;AAErB,MAAM,aAAa;AAEnB,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB;AAE1B,MAAM,0BAA0B;AAkChC,SAAS,WAAW,SAAqC;AACvD,MAAI,YAAY,UAAa,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO;AAC/D,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,CAAC;AACpD,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,QAAM,mBAAmB,eAAe;AACxC,SAAO,GAAG,OAAO,IAAI,OAAO,gBAAgB,EAAE,SAAS,GAAG,GAAG,CAAC;AAChE;AAGA,SAAS,WAAW,OAAuB;AACzC,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAQ,MAAM,WAAW,CAAC;AAC1B,WAAO,KAAK,KAAK,MAAM,QAAQ;AAAA,EACjC;AACA,SAAO,SAAS;AAClB;AAGA,SAAS,mBAAmB,MAA4B;AACtD,MAAI,QAAQ;AACZ,SAAO,MAAM;AACX,YAAS,QAAQ,aAAc;AAC/B,QAAI,IAAI,KAAK,KAAK,QAAS,UAAU,IAAK,IAAI,KAAK;AACnD,QAAK,IAAI,KAAK,KAAK,IAAK,MAAM,GAAI,KAAK,CAAC,IAAK;AAC7C,aAAS,IAAK,MAAM,QAAS,KAAK;AAAA,EACpC;AACF;AAGA,SAAS,sBAAsB,KAAa,OAAyB;AACnE,QAAM,SAAS,mBAAmB,WAAW,GAAG,CAAC;AACjD,SAAO,MAAM,KAAK,EAAE,QAAQ,MAAA,GAAS,MAAM,MAAM,OA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;AAAA,cACR,WAAU;AAAA,cACV,kBAAkB,CAAC,UAAU;AAC3B,sBAAM,EAAE,UAAU,eAAA,IAAmB,MAAM;AAC3C,iCAAiB,OAAO,SAAS,cAAc,IAAI,iBAAiB,MAAS;AAAA,cAC/E;AAAA,cACA,cAAc,CAAC,UAAU;AACvB,oBAAI,WAAY;AAChB,+BAAe,MAAM,cAAc,WAAW;AAAA,cAChD;AAAA,cACA,SAAS,MAAM;AACb,+BAAe,CAAC;AAChB,oBAAI,CAAC,aAAc,oBAAmB,KAAK;AAC3C,0BAAA;AAAA,cACF;AAAA,YAAA;AAAA,UAAA;AAAA,QACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAGN;AACF;AAEA,YAAY,cAAc;"}
|
|
1
|
+
{"version":3,"file":"AudioPlayer.mjs","sources":["../../../src/components/AudioPlayer/AudioPlayer.tsx"],"sourcesContent":["import * as React from \"react\";\nimport {\n decodeAudioPeaks,\n formatTime,\n generateFallbackPeaks,\n RAW_PEAK_COUNT,\n resamplePeaks,\n} from \"../../utils/audioWaveform\";\nimport { cn } from \"../../utils/cn\";\nimport { useFittedBarCount } from \"../../utils/useFittedBarCount\";\nimport { PauseIcon } from \"../Icons/PauseIcon\";\nimport { PlayIcon } from \"../Icons/PlayIcon\";\n\n/** Width of a single waveform bar, in pixels. */\nconst BAR_WIDTH_PX = 4;\n/** Gap between waveform bars, in pixels. */\nconst BAR_GAP_PX = 4;\n/** Shortest a waveform bar can render, in pixels. */\nconst MIN_BAR_HEIGHT_PX = 4;\n/** Tallest a waveform bar can render, in pixels — matches the 40px row height. */\nconst MAX_BAR_HEIGHT_PX = 26;\n/** Bar count used before the container has been measured (e.g. during SSR or in jsdom, where layout is unavailable). */\nconst DEFAULT_BAR_COUNT = 24;\n/** Seconds moved per Arrow key press while seeking. */\nconst SEEK_STEP_SECONDS = 1;\n/** Seconds moved per Page Up/Down press while seeking. */\nconst SEEK_STEP_LARGE_SECONDS = 5;\n\n/** Height of the audio player row, in pixels. Matches both the Vault card overlay and the \"Generated Audio\" modal row in Figma — both use an identical 32px play button and 40px row. */\nexport type AudioPlayerSize = \"40\";\n\nexport interface AudioPlayerProps\n extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onPlay\" | \"onPause\" | \"onEnded\"> {\n /** URL of the audio file to play. */\n src: string;\n /**\n * Total duration in seconds, used to render the timestamp before the\n * media's own metadata has loaded (and as a fallback if it never does).\n */\n duration?: number;\n /**\n * Whether playback is active (controlled). Note: once `onEnded` fires, the\n * browser has already stopped native playback. To loop or replay under\n * controlled usage, toggle this prop `false` then `true` (rather than\n * leaving it `true`) — the sync effect only calls `play()` again when this\n * value actually changes.\n */\n playing?: boolean;\n /** Initial playback state (uncontrolled). @default false */\n defaultPlaying?: boolean;\n /** Called when playback starts. */\n onPlay?: () => void;\n /** Called when playback is paused. */\n onPause?: () => void;\n /** Called when playback reaches the end of the media. */\n onEnded?: () => void;\n /** Height of the player row, in pixels. @default \"40\" */\n size?: AudioPlayerSize;\n}\n\n/**\n * A compact playback control for a single audio clip: a play/pause toggle, a\n * static amplitude waveform that doubles as a seek scrubber, and elapsed/total\n * timestamps. Designed to sit as an overlay on media thumbnails (Vault cards)\n * as well as inline rows (the AI Voice Message \"Generated Audio\" row).\n *\n * The waveform is seeded from the decoded audio when possible, falling back\n * to a deterministic (not random) placeholder derived from `src` so the\n * result is stable across renders, SSR, and Chromatic snapshots.\n *\n * @example\n * ```tsx\n * <AudioPlayer src=\"https://example.com/clip.mp3\" duration={5} />\n * ```\n */\nexport const AudioPlayer = React.forwardRef<HTMLDivElement, AudioPlayerProps>(\n (\n {\n className,\n src,\n duration,\n playing: controlledPlaying,\n defaultPlaying = false,\n onPlay,\n onPause,\n onEnded,\n size = \"40\",\n ...props\n },\n ref,\n ) => {\n const audioRef = React.useRef<HTMLAudioElement>(null);\n const trackRef = React.useRef<HTMLDivElement>(null);\n\n const [internalPlaying, setInternalPlaying] = React.useState(defaultPlaying);\n const isControlled = controlledPlaying !== undefined;\n const playing = isControlled ? controlledPlaying : internalPlaying;\n\n const [currentTime, setCurrentTime] = React.useState(0);\n const [mediaDuration, setMediaDuration] = React.useState<number | undefined>(undefined);\n const barCount = useFittedBarCount(trackRef, {\n barWidthPx: BAR_WIDTH_PX,\n gapPx: BAR_GAP_PX,\n fallback: DEFAULT_BAR_COUNT,\n });\n const [peaks, setPeaks] = React.useState<number[]>(() =>\n generateFallbackPeaks(src, RAW_PEAK_COUNT),\n );\n const [isDragging, setIsDragging] = React.useState(false);\n\n const displayDuration = mediaDuration ?? duration;\n const hasStarted = playing || currentTime > 0;\n\n // Latest-value refs so the src-change effect below can react to a src swap\n // without re-running whenever `playing`/`isControlled`/`onPause` change.\n const playingRef = React.useRef(playing);\n playingRef.current = playing;\n const isControlledRef = React.useRef(isControlled);\n isControlledRef.current = isControlled;\n const onPauseRef = React.useRef(onPause);\n onPauseRef.current = onPause;\n\n // Reset transient playback state when the source changes. Skips the\n // initial mount (there's nothing to reset yet) and, if playback was\n // active, stops it — the browser silently drops playback on a source\n // swap, so the UI (and any controlled parent) must be told via onPause.\n const isFirstSrcRenderRef = React.useRef(true);\n React.useEffect(() => {\n if (isFirstSrcRenderRef.current) {\n isFirstSrcRenderRef.current = false;\n return;\n }\n setCurrentTime(0);\n setMediaDuration(undefined);\n setPeaks(generateFallbackPeaks(src, RAW_PEAK_COUNT));\n if (playingRef.current) {\n if (!isControlledRef.current) setInternalPlaying(false);\n onPauseRef.current?.();\n }\n }, [src]);\n\n // Decode the audio to derive real waveform amplitudes, falling back to a\n // deterministic placeholder on any failure (network, CORS, unsupported format).\n React.useEffect(() => {\n let cancelled = false;\n const abortController = new AbortController();\n\n decodeAudioPeaks(src, abortController.signal)\n .then((decodedPeaks) => {\n if (!cancelled) setPeaks(decodedPeaks);\n })\n .catch(() => {\n if (!cancelled) setPeaks(generateFallbackPeaks(src, RAW_PEAK_COUNT));\n });\n\n return () => {\n cancelled = true;\n abortController.abort();\n };\n }, [src]);\n\n // Sync the controlled/uncontrolled `playing` state to the media element.\n React.useEffect(() => {\n const audio = audioRef.current;\n if (!audio) return;\n if (playing) {\n audio.play().catch(() => {\n if (!isControlled) setInternalPlaying(false);\n onPauseRef.current?.();\n });\n } else {\n audio.pause();\n }\n }, [playing, isControlled]);\n\n const handleToggle = () => {\n const next = !playing;\n if (!isControlled) setInternalPlaying(next);\n if (next) onPlay?.();\n else onPause?.();\n };\n\n const seekTo = React.useCallback(\n (time: number) => {\n if (displayDuration === undefined) return;\n const clamped = Math.min(Math.max(time, 0), displayDuration);\n setCurrentTime(clamped);\n const audio = audioRef.current;\n if (audio) audio.currentTime = clamped;\n },\n [displayDuration],\n );\n\n const seekFromClientX = React.useCallback(\n (clientX: number) => {\n const track = trackRef.current;\n if (!track || displayDuration === undefined) return;\n const rect = track.getBoundingClientRect();\n if (rect.width <= 0) return;\n const fraction = Math.min(Math.max((clientX - rect.left) / rect.width, 0), 1);\n seekTo(fraction * displayDuration);\n },\n [displayDuration, seekTo],\n );\n\n // Track drag outside the element via window listeners rather than pointer\n // capture, which some environments (and jsdom) don't fully implement.\n React.useEffect(() => {\n if (!isDragging) return;\n const handleWindowPointerMove = (event: PointerEvent) => seekFromClientX(event.clientX);\n const handleWindowPointerUp = () => setIsDragging(false);\n window.addEventListener(\"pointermove\", handleWindowPointerMove);\n window.addEventListener(\"pointerup\", handleWindowPointerUp);\n return () => {\n window.removeEventListener(\"pointermove\", handleWindowPointerMove);\n window.removeEventListener(\"pointerup\", handleWindowPointerUp);\n };\n }, [isDragging, seekFromClientX]);\n\n const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n seekFromClientX(event.clientX);\n setIsDragging(true);\n };\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (displayDuration === undefined) return;\n switch (event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n event.preventDefault();\n seekTo(currentTime + SEEK_STEP_SECONDS);\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n event.preventDefault();\n seekTo(currentTime - SEEK_STEP_SECONDS);\n break;\n case \"PageUp\":\n event.preventDefault();\n seekTo(currentTime + SEEK_STEP_LARGE_SECONDS);\n break;\n case \"PageDown\":\n event.preventDefault();\n seekTo(currentTime - SEEK_STEP_LARGE_SECONDS);\n break;\n case \"Home\":\n event.preventDefault();\n seekTo(0);\n break;\n case \"End\":\n event.preventDefault();\n seekTo(displayDuration);\n break;\n default:\n break;\n }\n };\n\n const bars = resamplePeaks(peaks, barCount);\n const progressFraction =\n displayDuration && displayDuration > 0\n ? Math.min(Math.max(currentTime / displayDuration, 0), 1)\n : 0;\n const playedBarCount = hasStarted ? Math.round(progressFraction * bars.length) : bars.length;\n const barData = bars.map((amplitude, index) => {\n const isPlayed = index < playedBarCount;\n return {\n heightPx: MIN_BAR_HEIGHT_PX + amplitude * (MAX_BAR_HEIGHT_PX - MIN_BAR_HEIGHT_PX),\n className: cn(\n \"w-1 shrink-0 rounded-3xs bg-messages-waveform-default\",\n \"motion-safe:transition-opacity motion-safe:duration-150 motion-safe:ease-in-out\",\n isPlayed ? \"opacity-100\" : \"opacity-50\",\n ),\n };\n });\n\n return (\n <div\n ref={ref}\n data-size={size}\n className={cn(\"flex w-full items-center gap-3\", className)}\n {...props}\n >\n <button\n type=\"button\"\n onClick={handleToggle}\n aria-label={playing ? \"Pause\" : \"Play\"}\n className={cn(\n \"flex size-8 shrink-0 items-center justify-center rounded-full\",\n \"bg-buttons-secondary-default text-icons-primary backdrop-blur-[40px]\",\n \"motion-safe:transition-colors motion-safe:duration-150 motion-safe:ease-in-out\",\n \"hover:bg-buttons-secondary-hover\",\n \"focus-visible:shadow-focus-ring focus-visible:outline-none\",\n )}\n >\n {playing ? <PauseIcon size={16} filled /> : <PlayIcon size={16} filled />}\n </button>\n\n <div className=\"flex min-w-0 flex-1 items-center gap-3\">\n <div\n ref={trackRef}\n role=\"slider\"\n tabIndex={0}\n aria-label=\"Seek\"\n aria-orientation=\"horizontal\"\n aria-valuemin={0}\n aria-valuemax={displayDuration}\n aria-valuenow={Math.round(currentTime)}\n aria-valuetext={\n displayDuration !== undefined\n ? `${formatTime(currentTime)} of ${formatTime(displayDuration)}`\n : formatTime(currentTime)\n }\n onPointerDown={handlePointerDown}\n onKeyDown={handleKeyDown}\n className={cn(\n \"flex h-10 min-w-0 flex-1 cursor-pointer touch-none select-none items-center gap-1 overflow-hidden\",\n \"focus-visible:shadow-focus-ring focus-visible:outline-none\",\n )}\n >\n {barData.map((bar, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: bars are a fixed-count, non-reorderable list\n <span key={index} className={bar.className} style={{ height: bar.heightPx }} />\n ))}\n </div>\n\n <span className=\"typography-body-small-14px-semibold flex shrink-0 items-center gap-0.5 whitespace-nowrap\">\n {hasStarted ? (\n <>\n <span className=\"text-content-primary\">{formatTime(currentTime)}</span>\n <span className=\"text-content-secondary\">/{formatTime(displayDuration)}</span>\n </>\n ) : (\n <span className=\"text-content-primary\">{formatTime(displayDuration)}</span>\n )}\n </span>\n </div>\n\n {/* biome-ignore lint/a11y/useMediaCaption: this is a UI sound clip (voice note / short recording), not spoken/narrated content requiring captions. */}\n <audio\n ref={audioRef}\n src={src}\n preload=\"metadata\"\n className=\"hidden\"\n onLoadedMetadata={(event) => {\n const { duration: nativeDuration } = event.currentTarget;\n setMediaDuration(Number.isFinite(nativeDuration) ? nativeDuration : undefined);\n }}\n onTimeUpdate={(event) => {\n if (isDragging) return;\n setCurrentTime(event.currentTarget.currentTime);\n }}\n onEnded={() => {\n setCurrentTime(0);\n if (!isControlled) setInternalPlaying(false);\n onEnded?.();\n }}\n />\n </div>\n );\n },\n);\n\nAudioPlayer.displayName = \"AudioPlayer\";\n"],"names":[],"mappings":";;;;;;;;AAcA,MAAM,eAAe;AAErB,MAAM,aAAa;AAEnB,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB;AAE1B,MAAM,oBAAoB;AAE1B,MAAM,0BAA0B;AAiDzB,MAAM,cAAc,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N;AACF;AAEA,YAAY,cAAc;"}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { resamplePeaks, formatTime } from "../../utils/audioWaveform.mjs";
|
|
5
|
+
import { cn } from "../../utils/cn.mjs";
|
|
6
|
+
import { useAudioPlayback } from "../../utils/useAudioPlayback.mjs";
|
|
7
|
+
import { useFittedBarCount } from "../../utils/useFittedBarCount.mjs";
|
|
8
|
+
import { useWaveformPeaks } from "../../utils/useWaveformPeaks.mjs";
|
|
9
|
+
import { useWaveformSeek } from "../../utils/useWaveformSeek.mjs";
|
|
10
|
+
import { IconButton } from "../IconButton/IconButton.mjs";
|
|
11
|
+
import { CloseIcon } from "../Icons/CloseIcon.mjs";
|
|
12
|
+
import { PauseIcon } from "../Icons/PauseIcon.mjs";
|
|
13
|
+
import { PlayIcon } from "../Icons/PlayIcon.mjs";
|
|
14
|
+
const DEFAULT_WAVEFORM = [
|
|
15
|
+
0.15,
|
|
16
|
+
0.46,
|
|
17
|
+
0.85,
|
|
18
|
+
0.23,
|
|
19
|
+
1,
|
|
20
|
+
0.85,
|
|
21
|
+
0.62,
|
|
22
|
+
0.62,
|
|
23
|
+
0.62,
|
|
24
|
+
0.85,
|
|
25
|
+
0.85,
|
|
26
|
+
0.62,
|
|
27
|
+
0.62,
|
|
28
|
+
1,
|
|
29
|
+
1,
|
|
30
|
+
0.62,
|
|
31
|
+
0.62,
|
|
32
|
+
0.62,
|
|
33
|
+
0.23,
|
|
34
|
+
0.23,
|
|
35
|
+
0.15,
|
|
36
|
+
0.46,
|
|
37
|
+
0.85,
|
|
38
|
+
0.23,
|
|
39
|
+
1,
|
|
40
|
+
0.46,
|
|
41
|
+
0.85,
|
|
42
|
+
0.62,
|
|
43
|
+
0.23,
|
|
44
|
+
0.23,
|
|
45
|
+
0.62,
|
|
46
|
+
0.62,
|
|
47
|
+
0.85,
|
|
48
|
+
0.85,
|
|
49
|
+
0.62,
|
|
50
|
+
0.62,
|
|
51
|
+
0.85,
|
|
52
|
+
1,
|
|
53
|
+
0.85,
|
|
54
|
+
1,
|
|
55
|
+
0.62,
|
|
56
|
+
0.62,
|
|
57
|
+
0.62,
|
|
58
|
+
0.23,
|
|
59
|
+
0.23,
|
|
60
|
+
0.62,
|
|
61
|
+
0.23,
|
|
62
|
+
0.23,
|
|
63
|
+
0.23,
|
|
64
|
+
0.62,
|
|
65
|
+
0.85,
|
|
66
|
+
0.62,
|
|
67
|
+
0.85,
|
|
68
|
+
1,
|
|
69
|
+
0.85,
|
|
70
|
+
0.85,
|
|
71
|
+
1,
|
|
72
|
+
0.85,
|
|
73
|
+
0.23,
|
|
74
|
+
0.23,
|
|
75
|
+
0.23,
|
|
76
|
+
0.46,
|
|
77
|
+
0.62,
|
|
78
|
+
0.23,
|
|
79
|
+
0.23
|
|
80
|
+
];
|
|
81
|
+
const MIN_BAR_HEIGHT = 4;
|
|
82
|
+
const MAX_BAR_HEIGHT = {
|
|
83
|
+
default: 26,
|
|
84
|
+
small: 16
|
|
85
|
+
};
|
|
86
|
+
const CONTROL_SIZE = {
|
|
87
|
+
default: "48",
|
|
88
|
+
small: "32"
|
|
89
|
+
};
|
|
90
|
+
const BAR_WIDTH_PX = 4;
|
|
91
|
+
const BAR_GAP_PX = 4;
|
|
92
|
+
const DEFAULT_BAR_COUNT = 40;
|
|
93
|
+
function activeBarClass(negative) {
|
|
94
|
+
return negative ? "bg-messages-waveform-listening-negative-active" : "bg-messages-waveform-listening-active";
|
|
95
|
+
}
|
|
96
|
+
function inactiveBarClass(negative) {
|
|
97
|
+
return negative ? "bg-messages-waveform-listening-negative-inactive" : "bg-messages-waveform-listening-inactive";
|
|
98
|
+
}
|
|
99
|
+
function restingBarClass(negative) {
|
|
100
|
+
return negative ? "bg-messages-waveform-listening-negative-default" : "bg-messages-waveform-default";
|
|
101
|
+
}
|
|
102
|
+
function WaveformBars({ bars, variant, size, negative, progress }) {
|
|
103
|
+
const hasProgress = progress !== void 0;
|
|
104
|
+
const activeCount = hasProgress ? Math.round(progress * bars.length) : 0;
|
|
105
|
+
const maxBarHeight = MAX_BAR_HEIGHT[size];
|
|
106
|
+
return /* @__PURE__ */ jsx(Fragment, { children: bars.map((amplitude, index) => {
|
|
107
|
+
const height = variant === "flat" ? MIN_BAR_HEIGHT : Math.max(MIN_BAR_HEIGHT, Math.round(amplitude * maxBarHeight));
|
|
108
|
+
const colorClass = !hasProgress ? restingBarClass(negative) : index < activeCount ? activeBarClass(negative) : inactiveBarClass(negative);
|
|
109
|
+
return /* @__PURE__ */ jsx(
|
|
110
|
+
"span",
|
|
111
|
+
{
|
|
112
|
+
className: cn("w-1 shrink-0 rounded-[2px]", colorClass),
|
|
113
|
+
style: { height }
|
|
114
|
+
},
|
|
115
|
+
index
|
|
116
|
+
);
|
|
117
|
+
}) });
|
|
118
|
+
}
|
|
119
|
+
function WaveformMeta({ time, fileName, textColor }) {
|
|
120
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
121
|
+
time && /* @__PURE__ */ jsx("span", { className: cn("typography-body-small-14px-regular shrink-0", textColor), children: time }),
|
|
122
|
+
fileName && /* @__PURE__ */ jsx(
|
|
123
|
+
"span",
|
|
124
|
+
{
|
|
125
|
+
className: cn(
|
|
126
|
+
"typography-body-small-14px-regular min-w-0 max-w-[50%] truncate",
|
|
127
|
+
textColor
|
|
128
|
+
),
|
|
129
|
+
children: fileName
|
|
130
|
+
}
|
|
131
|
+
)
|
|
132
|
+
] });
|
|
133
|
+
}
|
|
134
|
+
const VoiceNote = React.forwardRef(
|
|
135
|
+
({
|
|
136
|
+
className,
|
|
137
|
+
src,
|
|
138
|
+
duration,
|
|
139
|
+
waveform = DEFAULT_WAVEFORM,
|
|
140
|
+
variant = "default",
|
|
141
|
+
size = "default",
|
|
142
|
+
negative = false,
|
|
143
|
+
progress,
|
|
144
|
+
playing,
|
|
145
|
+
defaultPlaying = false,
|
|
146
|
+
onPlayPause,
|
|
147
|
+
onEnded,
|
|
148
|
+
time,
|
|
149
|
+
fileName,
|
|
150
|
+
showControls = true,
|
|
151
|
+
showTimestamp = true,
|
|
152
|
+
showRemove = false,
|
|
153
|
+
onRemove,
|
|
154
|
+
playButtonLabel,
|
|
155
|
+
removeButtonLabel = "Remove",
|
|
156
|
+
"aria-label": ariaLabel = "Voice note",
|
|
157
|
+
...props
|
|
158
|
+
}, ref) => {
|
|
159
|
+
const isPlayer = src !== void 0;
|
|
160
|
+
const playback = useAudioPlayback({
|
|
161
|
+
src,
|
|
162
|
+
duration,
|
|
163
|
+
playing,
|
|
164
|
+
defaultPlaying,
|
|
165
|
+
onEnded,
|
|
166
|
+
onPlay: React.useCallback(() => onPlayPause?.(true), [onPlayPause]),
|
|
167
|
+
onPause: React.useCallback(() => onPlayPause?.(false), [onPlayPause])
|
|
168
|
+
});
|
|
169
|
+
const decodedPeaks = useWaveformPeaks(src);
|
|
170
|
+
const [internalPlaying, setInternalPlaying] = React.useState(defaultPlaying);
|
|
171
|
+
const isControlled = playing !== void 0;
|
|
172
|
+
const trackRef = React.useRef(null);
|
|
173
|
+
const fittedBarCount = useFittedBarCount(trackRef, {
|
|
174
|
+
barWidthPx: BAR_WIDTH_PX,
|
|
175
|
+
gapPx: BAR_GAP_PX,
|
|
176
|
+
fallback: DEFAULT_BAR_COUNT
|
|
177
|
+
});
|
|
178
|
+
const seekProps = useWaveformSeek({
|
|
179
|
+
trackRef,
|
|
180
|
+
displayDuration: playback.displayDuration,
|
|
181
|
+
currentTime: playback.currentTime,
|
|
182
|
+
seekTo: playback.seekTo,
|
|
183
|
+
setSeeking: playback.setSeeking
|
|
184
|
+
});
|
|
185
|
+
const isPlaying = isPlayer ? playback.isPlaying : playing ?? internalPlaying;
|
|
186
|
+
const handlePlayPause = () => {
|
|
187
|
+
if (isPlayer) {
|
|
188
|
+
playback.toggle();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const next = !isPlaying;
|
|
192
|
+
if (!isControlled) setInternalPlaying(next);
|
|
193
|
+
onPlayPause?.(next);
|
|
194
|
+
};
|
|
195
|
+
const bars = resamplePeaks(isPlayer ? decodedPeaks : waveform, fittedBarCount);
|
|
196
|
+
const progressValue = isPlayer ? playback.progress : progress;
|
|
197
|
+
const textColor = negative ? "text-content-primary-inverted" : "text-content-primary";
|
|
198
|
+
const playerTime = playback.hasStarted ? playback.currentTime : playback.displayDuration;
|
|
199
|
+
const displayTime = isPlayer ? formatTime(playerTime) : time;
|
|
200
|
+
const controlLabel = playButtonLabel ?? (isPlaying ? "Pause" : "Play");
|
|
201
|
+
const trackAria = isPlayer ? seekProps : { "aria-hidden": true };
|
|
202
|
+
return (
|
|
203
|
+
// biome-ignore lint/a11y/useSemanticElements: <fieldset> would break the public HTMLDivElement ref/props API
|
|
204
|
+
/* @__PURE__ */ jsxs(
|
|
205
|
+
"div",
|
|
206
|
+
{
|
|
207
|
+
ref,
|
|
208
|
+
role: "group",
|
|
209
|
+
"aria-label": ariaLabel,
|
|
210
|
+
className: cn("flex items-center gap-3", size === "small" ? "h-8" : "h-12", className),
|
|
211
|
+
...props,
|
|
212
|
+
children: [
|
|
213
|
+
showControls && /* @__PURE__ */ jsx(
|
|
214
|
+
IconButton,
|
|
215
|
+
{
|
|
216
|
+
variant: "secondary",
|
|
217
|
+
size: CONTROL_SIZE[size],
|
|
218
|
+
negative,
|
|
219
|
+
icon: isPlaying ? /* @__PURE__ */ jsx(PauseIcon, {}) : /* @__PURE__ */ jsx(PlayIcon, {}),
|
|
220
|
+
"aria-label": controlLabel,
|
|
221
|
+
onClick: handlePlayPause
|
|
222
|
+
}
|
|
223
|
+
),
|
|
224
|
+
/* @__PURE__ */ jsx(
|
|
225
|
+
"div",
|
|
226
|
+
{
|
|
227
|
+
ref: trackRef,
|
|
228
|
+
"data-testid": "voice-note-waveform",
|
|
229
|
+
className: cn(
|
|
230
|
+
"flex h-full min-w-0 flex-1 items-center gap-1 overflow-hidden",
|
|
231
|
+
isPlayer && "cursor-pointer touch-none select-none focus-visible:shadow-focus-ring focus-visible:outline-none"
|
|
232
|
+
),
|
|
233
|
+
...trackAria,
|
|
234
|
+
children: /* @__PURE__ */ jsx(
|
|
235
|
+
WaveformBars,
|
|
236
|
+
{
|
|
237
|
+
bars,
|
|
238
|
+
variant,
|
|
239
|
+
size,
|
|
240
|
+
negative,
|
|
241
|
+
progress: progressValue
|
|
242
|
+
}
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
),
|
|
246
|
+
/* @__PURE__ */ jsx(
|
|
247
|
+
WaveformMeta,
|
|
248
|
+
{
|
|
249
|
+
time: showTimestamp ? displayTime : void 0,
|
|
250
|
+
fileName,
|
|
251
|
+
textColor
|
|
252
|
+
}
|
|
253
|
+
),
|
|
254
|
+
showRemove && /* @__PURE__ */ jsx(
|
|
255
|
+
IconButton,
|
|
256
|
+
{
|
|
257
|
+
variant: "tertiary",
|
|
258
|
+
size: CONTROL_SIZE[size],
|
|
259
|
+
negative,
|
|
260
|
+
icon: /* @__PURE__ */ jsx(CloseIcon, {}),
|
|
261
|
+
"aria-label": removeButtonLabel,
|
|
262
|
+
onClick: onRemove
|
|
263
|
+
}
|
|
264
|
+
),
|
|
265
|
+
isPlayer && // biome-ignore lint/a11y/useMediaCaption: a UI voice note / short recording, not narrated content needing captions
|
|
266
|
+
/* @__PURE__ */ jsx(
|
|
267
|
+
"audio",
|
|
268
|
+
{
|
|
269
|
+
ref: playback.audioRef,
|
|
270
|
+
src,
|
|
271
|
+
preload: "metadata",
|
|
272
|
+
className: "hidden",
|
|
273
|
+
onLoadedMetadata: playback.audioHandlers.onLoadedMetadata,
|
|
274
|
+
onTimeUpdate: playback.audioHandlers.onTimeUpdate,
|
|
275
|
+
onEnded: playback.audioHandlers.onEnded
|
|
276
|
+
}
|
|
277
|
+
)
|
|
278
|
+
]
|
|
279
|
+
}
|
|
280
|
+
)
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
);
|
|
284
|
+
VoiceNote.displayName = "VoiceNote";
|
|
285
|
+
export {
|
|
286
|
+
VoiceNote
|
|
287
|
+
};
|
|
288
|
+
//# sourceMappingURL=VoiceNote.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VoiceNote.mjs","sources":["../../../src/components/VoiceNote/VoiceNote.tsx"],"sourcesContent":["import * as React from \"react\";\nimport { formatTime, resamplePeaks } from \"@/utils/audioWaveform\";\nimport { cn } from \"@/utils/cn\";\nimport { useAudioPlayback } from \"@/utils/useAudioPlayback\";\nimport { useFittedBarCount } from \"@/utils/useFittedBarCount\";\nimport { useWaveformPeaks } from \"@/utils/useWaveformPeaks\";\nimport { useWaveformSeek } from \"@/utils/useWaveformSeek\";\nimport { IconButton, type IconButtonSize } from \"../IconButton/IconButton\";\nimport { CloseIcon } from \"../Icons/CloseIcon\";\nimport { PauseIcon } from \"../Icons/PauseIcon\";\nimport { PlayIcon } from \"../Icons/PlayIcon\";\n\n/** Visual style of the waveform. */\nexport type VoiceNoteVariant = \"default\" | \"flat\";\n\n/** Size preset for the voice note. */\nexport type VoiceNoteSize = \"default\" | \"small\";\n\n/**\n * Default waveform amplitudes (0–1), taken from the Figma reference so the\n * resting state renders 1:1 when no `waveform` data (or `src`) is supplied.\n */\nconst DEFAULT_WAVEFORM = [\n 0.15, 0.46, 0.85, 0.23, 1, 0.85, 0.62, 0.62, 0.62, 0.85, 0.85, 0.62, 0.62, 1, 1, 0.62, 0.62, 0.62,\n 0.23, 0.23, 0.15, 0.46, 0.85, 0.23, 1, 0.46, 0.85, 0.62, 0.23, 0.23, 0.62, 0.62, 0.85, 0.85, 0.62,\n 0.62, 0.85, 1, 0.85, 1, 0.62, 0.62, 0.62, 0.23, 0.23, 0.62, 0.23, 0.23, 0.23, 0.62, 0.85, 0.62,\n 0.85, 1, 0.85, 0.85, 1, 0.85, 0.23, 0.23, 0.23, 0.46, 0.62, 0.23, 0.23,\n];\n\nconst MIN_BAR_HEIGHT = 4;\nconst MAX_BAR_HEIGHT: Record<VoiceNoteSize, number> = {\n default: 26,\n small: 16,\n};\n\nconst CONTROL_SIZE: Record<VoiceNoteSize, IconButtonSize> = {\n default: \"48\",\n small: \"32\",\n};\n\n/** Rendered width of a single waveform bar, in pixels (`w-1`). */\nconst BAR_WIDTH_PX = 4;\n/** Gap between waveform bars, in pixels (`gap-1`). */\nconst BAR_GAP_PX = 4;\n/** Bar count before the track is measured (SSR, jsdom, or zero-width layout). */\nconst DEFAULT_BAR_COUNT = 40;\n\nfunction activeBarClass(negative: boolean): string {\n return negative\n ? \"bg-messages-waveform-listening-negative-active\"\n : \"bg-messages-waveform-listening-active\";\n}\n\nfunction inactiveBarClass(negative: boolean): string {\n return negative\n ? \"bg-messages-waveform-listening-negative-inactive\"\n : \"bg-messages-waveform-listening-inactive\";\n}\n\nfunction restingBarClass(negative: boolean): string {\n return negative\n ? \"bg-messages-waveform-listening-negative-default\"\n : \"bg-messages-waveform-default\";\n}\n\ninterface WaveformBarsProps {\n bars: number[];\n variant: VoiceNoteVariant;\n size: VoiceNoteSize;\n negative: boolean;\n progress: number | undefined;\n}\n\nfunction WaveformBars({ bars, variant, size, negative, progress }: WaveformBarsProps) {\n const hasProgress = progress !== undefined;\n const activeCount = hasProgress ? Math.round(progress * bars.length) : 0;\n const maxBarHeight = MAX_BAR_HEIGHT[size];\n\n return (\n <>\n {bars.map((amplitude, index) => {\n const height =\n variant === \"flat\"\n ? MIN_BAR_HEIGHT\n : Math.max(MIN_BAR_HEIGHT, Math.round(amplitude * maxBarHeight));\n const colorClass = !hasProgress\n ? restingBarClass(negative)\n : index < activeCount\n ? activeBarClass(negative)\n : inactiveBarClass(negative);\n\n return (\n <span\n // biome-ignore lint/suspicious/noArrayIndexKey: bars are a fixed positional sequence\n key={index}\n className={cn(\"w-1 shrink-0 rounded-[2px]\", colorClass)}\n style={{ height }}\n />\n );\n })}\n </>\n );\n}\n\ninterface WaveformMetaProps {\n time: string | undefined;\n fileName: string | undefined;\n textColor: string;\n}\n\nfunction WaveformMeta({ time, fileName, textColor }: WaveformMetaProps) {\n return (\n <>\n {time && (\n <span className={cn(\"typography-body-small-14px-regular shrink-0\", textColor)}>{time}</span>\n )}\n {fileName && (\n <span\n className={cn(\n \"typography-body-small-14px-regular min-w-0 max-w-[50%] truncate\",\n textColor,\n )}\n >\n {fileName}\n </span>\n )}\n </>\n );\n}\n\nexport interface VoiceNoteProps\n extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onPlay\" | \"onPause\"> {\n /**\n * URL of the audio to play. When set, the component manages a real `<audio>`\n * element: it decodes the waveform, plays/pauses, tracks live progress and is\n * seekable — `waveform`/`progress` are derived automatically. Leave unset for\n * a presentational, fully-controlled voice note.\n */\n src?: string;\n /** Fallback total duration (seconds), used until the media's metadata loads. */\n duration?: number;\n /** Amplitude values (0–1), one per bar. Ignored when `src` is set. Falls back to a built-in pattern. */\n waveform?: number[];\n /** Visual style; `flat` renders a simplified dotted preview. @default \"default\" */\n variant?: VoiceNoteVariant;\n /** Size preset. @default \"default\" */\n size?: VoiceNoteSize;\n /** Dark-surface treatment for use on message bubbles. @default false */\n negative?: boolean;\n /**\n * Playback progress (0–1) for the presentational mode. When set, the waveform\n * splits into played/unplayed bars (the \"Listening\" state). Ignored when `src`\n * is set (progress comes from the media element).\n */\n progress?: number;\n /** Whether audio is playing (controlled) — toggles the play/pause icon. */\n playing?: boolean;\n /** Initial playing state (uncontrolled). @default false */\n defaultPlaying?: boolean;\n /** Called with the next playing state when the play/pause control is pressed. */\n onPlayPause?: (playing: boolean) => void;\n /** Called when audio playback reaches the end (only in `src` mode). */\n onEnded?: () => void;\n /** Timestamp or duration label, e.g. \"0:05\". Ignored when `src` is set (derived from the media). */\n time?: string;\n /** File name shown when the audio is an uploaded file rather than a voice note. */\n fileName?: string;\n /** Show the play/pause control. @default true */\n showControls?: boolean;\n /** Show the timestamp label. @default true */\n showTimestamp?: boolean;\n /** Show a remove button (calls {@link VoiceNoteProps.onRemove}). @default false */\n showRemove?: boolean;\n /** Called when the remove button is pressed. */\n onRemove?: () => void;\n /** Accessible name for the play/pause control. Defaults to \"Play\"/\"Pause\". */\n playButtonLabel?: string;\n /** Accessible name for the remove button. @default \"Remove\" */\n removeButtonLabel?: string;\n /** Accessible name for the whole player. @default \"Voice note\" */\n \"aria-label\"?: string;\n}\n\n/**\n * A voice-note audio player: a play/pause control, an amplitude waveform, and a\n * timestamp — for voice messages and audio attachments in a conversation.\n *\n * Two modes: pass `src` for a self-contained player that decodes the waveform,\n * plays real audio, tracks live progress and is seekable; or omit `src` and\n * drive it with `playing`/`progress` + `onPlayPause` for a presentational,\n * fully-controlled voice note. `flat` renders a compact dotted preview and\n * `negative` adapts it to dark message bubbles.\n *\n * @example\n * ```tsx\n * <VoiceNote src=\"https://example.com/note.mp3\" duration={5} />\n * <VoiceNote time=\"0:05\" progress={0.4} playing onPlayPause={toggle} />\n * ```\n */\nexport const VoiceNote = React.forwardRef<HTMLDivElement, VoiceNoteProps>(\n (\n {\n className,\n src,\n duration,\n waveform = DEFAULT_WAVEFORM,\n variant = \"default\",\n size = \"default\",\n negative = false,\n progress,\n playing,\n defaultPlaying = false,\n onPlayPause,\n onEnded,\n time,\n fileName,\n showControls = true,\n showTimestamp = true,\n showRemove = false,\n onRemove,\n playButtonLabel,\n removeButtonLabel = \"Remove\",\n \"aria-label\": ariaLabel = \"Voice note\",\n ...props\n },\n ref,\n ) => {\n const isPlayer = src !== undefined;\n\n const playback = useAudioPlayback({\n src,\n duration,\n playing,\n defaultPlaying,\n onEnded,\n onPlay: React.useCallback(() => onPlayPause?.(true), [onPlayPause]),\n onPause: React.useCallback(() => onPlayPause?.(false), [onPlayPause]),\n });\n const decodedPeaks = useWaveformPeaks(src);\n\n const [internalPlaying, setInternalPlaying] = React.useState(defaultPlaying);\n const isControlled = playing !== undefined;\n\n const trackRef = React.useRef<HTMLDivElement>(null);\n const fittedBarCount = useFittedBarCount(trackRef, {\n barWidthPx: BAR_WIDTH_PX,\n gapPx: BAR_GAP_PX,\n fallback: DEFAULT_BAR_COUNT,\n });\n const seekProps = useWaveformSeek({\n trackRef,\n displayDuration: playback.displayDuration,\n currentTime: playback.currentTime,\n seekTo: playback.seekTo,\n setSeeking: playback.setSeeking,\n });\n\n const isPlaying = isPlayer ? playback.isPlaying : (playing ?? internalPlaying);\n\n const handlePlayPause = () => {\n if (isPlayer) {\n playback.toggle();\n return;\n }\n const next = !isPlaying;\n if (!isControlled) setInternalPlaying(next);\n onPlayPause?.(next);\n };\n\n const bars = resamplePeaks(isPlayer ? decodedPeaks : waveform, fittedBarCount);\n const progressValue = isPlayer ? playback.progress : progress;\n const textColor = negative ? \"text-content-primary-inverted\" : \"text-content-primary\";\n\n const playerTime = playback.hasStarted ? playback.currentTime : playback.displayDuration;\n const displayTime = isPlayer ? formatTime(playerTime) : time;\n const controlLabel = playButtonLabel ?? (isPlaying ? \"Pause\" : \"Play\");\n const trackAria = isPlayer ? seekProps : ({ \"aria-hidden\": true } as const);\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: <fieldset> would break the public HTMLDivElement ref/props API\n <div\n ref={ref}\n role=\"group\"\n aria-label={ariaLabel}\n className={cn(\"flex items-center gap-3\", size === \"small\" ? \"h-8\" : \"h-12\", className)}\n {...props}\n >\n {showControls && (\n <IconButton\n variant=\"secondary\"\n size={CONTROL_SIZE[size]}\n negative={negative}\n icon={isPlaying ? <PauseIcon /> : <PlayIcon />}\n aria-label={controlLabel}\n onClick={handlePlayPause}\n />\n )}\n\n <div\n ref={trackRef}\n data-testid=\"voice-note-waveform\"\n className={cn(\n \"flex h-full min-w-0 flex-1 items-center gap-1 overflow-hidden\",\n isPlayer &&\n \"cursor-pointer touch-none select-none focus-visible:shadow-focus-ring focus-visible:outline-none\",\n )}\n {...trackAria}\n >\n <WaveformBars\n bars={bars}\n variant={variant}\n size={size}\n negative={negative}\n progress={progressValue}\n />\n </div>\n\n <WaveformMeta\n time={showTimestamp ? displayTime : undefined}\n fileName={fileName}\n textColor={textColor}\n />\n\n {showRemove && (\n <IconButton\n variant=\"tertiary\"\n size={CONTROL_SIZE[size]}\n negative={negative}\n icon={<CloseIcon />}\n aria-label={removeButtonLabel}\n onClick={onRemove}\n />\n )}\n\n {isPlayer && (\n // biome-ignore lint/a11y/useMediaCaption: a UI voice note / short recording, not narrated content needing captions\n <audio\n ref={playback.audioRef}\n src={src}\n preload=\"metadata\"\n className=\"hidden\"\n onLoadedMetadata={playback.audioHandlers.onLoadedMetadata}\n onTimeUpdate={playback.audioHandlers.onTimeUpdate}\n onEnded={playback.audioHandlers.onEnded}\n />\n )}\n </div>\n );\n },\n);\n\nVoiceNote.displayName = \"VoiceNote\";\n"],"names":[],"mappings":";;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AAAA,EACvB;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAG;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAC7F;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAC7F;AAAA,EAAM;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAC1F;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAAG;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,E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AA,gBACC,MAAM,gBAAgB,cAAc;AAAA,gBACpC;AAAA,gBACA;AAAA,cAAA;AAAA,YAAA;AAAA,YAGD,cACC;AAAA,cAAC;AAAA,cAAA;AAAA,gBACC,SAAQ;AAAA,gBACR,MAAM,aAAa,IAAI;AAAA,gBACvB;AAAA,gBACA,0BAAO,WAAA,EAAU;AAAA,gBACjB,cAAY;AAAA,gBACZ,SAAS;AAAA,cAAA;AAAA,YAAA;AAAA,YAIZ;AAAA,YAEC;AAAA,cAAC;AAAA,cAAA;AAAA,gBACC,KAAK,SAAS;AAAA,gBACd;AAAA,gBACA,SAAQ;AAAA,gBACR,WAAU;AAAA,gBACV,kBAAkB,SAAS,cAAc;AAAA,gBACzC,cAAc,SAAS,cAAc;AAAA,gBACrC,SAAS,SAAS,cAAc;AAAA,cAAA;AAAA,YAAA;AAAA,UAClC;AAAA,QAAA;AAAA,MAAA;AAAA;AAAA,EAIR;AACF;AAEA,UAAU,cAAc;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -6053,6 +6053,82 @@ export declare const VipBadgeIcon: React_2.ForwardRefExoticComponent<React_2.SVG
|
|
|
6053
6053
|
className?: string;
|
|
6054
6054
|
} & React_2.RefAttributes<SVGSVGElement>>;
|
|
6055
6055
|
|
|
6056
|
+
/**
|
|
6057
|
+
* A voice-note audio player: a play/pause control, an amplitude waveform, and a
|
|
6058
|
+
* timestamp — for voice messages and audio attachments in a conversation.
|
|
6059
|
+
*
|
|
6060
|
+
* Two modes: pass `src` for a self-contained player that decodes the waveform,
|
|
6061
|
+
* plays real audio, tracks live progress and is seekable; or omit `src` and
|
|
6062
|
+
* drive it with `playing`/`progress` + `onPlayPause` for a presentational,
|
|
6063
|
+
* fully-controlled voice note. `flat` renders a compact dotted preview and
|
|
6064
|
+
* `negative` adapts it to dark message bubbles.
|
|
6065
|
+
*
|
|
6066
|
+
* @example
|
|
6067
|
+
* ```tsx
|
|
6068
|
+
* <VoiceNote src="https://example.com/note.mp3" duration={5} />
|
|
6069
|
+
* <VoiceNote time="0:05" progress={0.4} playing onPlayPause={toggle} />
|
|
6070
|
+
* ```
|
|
6071
|
+
*/
|
|
6072
|
+
export declare const VoiceNote: React_2.ForwardRefExoticComponent<VoiceNoteProps & React_2.RefAttributes<HTMLDivElement>>;
|
|
6073
|
+
|
|
6074
|
+
export declare interface VoiceNoteProps extends Omit<React_2.HTMLAttributes<HTMLDivElement>, "onPlay" | "onPause"> {
|
|
6075
|
+
/**
|
|
6076
|
+
* URL of the audio to play. When set, the component manages a real `<audio>`
|
|
6077
|
+
* element: it decodes the waveform, plays/pauses, tracks live progress and is
|
|
6078
|
+
* seekable — `waveform`/`progress` are derived automatically. Leave unset for
|
|
6079
|
+
* a presentational, fully-controlled voice note.
|
|
6080
|
+
*/
|
|
6081
|
+
src?: string;
|
|
6082
|
+
/** Fallback total duration (seconds), used until the media's metadata loads. */
|
|
6083
|
+
duration?: number;
|
|
6084
|
+
/** Amplitude values (0–1), one per bar. Ignored when `src` is set. Falls back to a built-in pattern. */
|
|
6085
|
+
waveform?: number[];
|
|
6086
|
+
/** Visual style; `flat` renders a simplified dotted preview. @default "default" */
|
|
6087
|
+
variant?: VoiceNoteVariant;
|
|
6088
|
+
/** Size preset. @default "default" */
|
|
6089
|
+
size?: VoiceNoteSize;
|
|
6090
|
+
/** Dark-surface treatment for use on message bubbles. @default false */
|
|
6091
|
+
negative?: boolean;
|
|
6092
|
+
/**
|
|
6093
|
+
* Playback progress (0–1) for the presentational mode. When set, the waveform
|
|
6094
|
+
* splits into played/unplayed bars (the "Listening" state). Ignored when `src`
|
|
6095
|
+
* is set (progress comes from the media element).
|
|
6096
|
+
*/
|
|
6097
|
+
progress?: number;
|
|
6098
|
+
/** Whether audio is playing (controlled) — toggles the play/pause icon. */
|
|
6099
|
+
playing?: boolean;
|
|
6100
|
+
/** Initial playing state (uncontrolled). @default false */
|
|
6101
|
+
defaultPlaying?: boolean;
|
|
6102
|
+
/** Called with the next playing state when the play/pause control is pressed. */
|
|
6103
|
+
onPlayPause?: (playing: boolean) => void;
|
|
6104
|
+
/** Called when audio playback reaches the end (only in `src` mode). */
|
|
6105
|
+
onEnded?: () => void;
|
|
6106
|
+
/** Timestamp or duration label, e.g. "0:05". Ignored when `src` is set (derived from the media). */
|
|
6107
|
+
time?: string;
|
|
6108
|
+
/** File name shown when the audio is an uploaded file rather than a voice note. */
|
|
6109
|
+
fileName?: string;
|
|
6110
|
+
/** Show the play/pause control. @default true */
|
|
6111
|
+
showControls?: boolean;
|
|
6112
|
+
/** Show the timestamp label. @default true */
|
|
6113
|
+
showTimestamp?: boolean;
|
|
6114
|
+
/** Show a remove button (calls {@link VoiceNoteProps.onRemove}). @default false */
|
|
6115
|
+
showRemove?: boolean;
|
|
6116
|
+
/** Called when the remove button is pressed. */
|
|
6117
|
+
onRemove?: () => void;
|
|
6118
|
+
/** Accessible name for the play/pause control. Defaults to "Play"/"Pause". */
|
|
6119
|
+
playButtonLabel?: string;
|
|
6120
|
+
/** Accessible name for the remove button. @default "Remove" */
|
|
6121
|
+
removeButtonLabel?: string;
|
|
6122
|
+
/** Accessible name for the whole player. @default "Voice note" */
|
|
6123
|
+
"aria-label"?: string;
|
|
6124
|
+
}
|
|
6125
|
+
|
|
6126
|
+
/** Size preset for the voice note. */
|
|
6127
|
+
export declare type VoiceNoteSize = "default" | "small";
|
|
6128
|
+
|
|
6129
|
+
/** Visual style of the waveform. */
|
|
6130
|
+
export declare type VoiceNoteVariant = "default" | "flat";
|
|
6131
|
+
|
|
6056
6132
|
/**
|
|
6057
6133
|
* Wallet icon. Renders at sizes 16, 24, or 32 px with outlined and filled variants.
|
|
6058
6134
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -248,6 +248,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./comp
|
|
|
248
248
|
import { UserDisplayName } from "./components/UserDisplayName/UserDisplayName.mjs";
|
|
249
249
|
import { UserHandle } from "./components/UserHandle/UserHandle.mjs";
|
|
250
250
|
import { UserItem } from "./components/UserItem/UserItem.mjs";
|
|
251
|
+
import { VoiceNote } from "./components/VoiceNote/VoiceNote.mjs";
|
|
251
252
|
import { cn } from "./utils/cn.mjs";
|
|
252
253
|
import { getInitials } from "./utils/getInitials.mjs";
|
|
253
254
|
import { useSuppressClickAfterDrag } from "./utils/useSuppressClickAfterDrag.mjs";
|
|
@@ -564,6 +565,7 @@ export {
|
|
|
564
565
|
VerifiedIcon,
|
|
565
566
|
VideoIcon,
|
|
566
567
|
VipBadgeIcon,
|
|
568
|
+
VoiceNote,
|
|
567
569
|
WalletIcon,
|
|
568
570
|
WarningIcon,
|
|
569
571
|
WarningTriangleIcon,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/styles/base.css
CHANGED
|
@@ -13,6 +13,15 @@
|
|
|
13
13
|
scrollbar-gutter: stable;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
/*
|
|
17
|
+
* Neutralise the browser's autofill highlight with the inset box-shadow
|
|
18
|
+
* hack. The shadow colour must match the input container background
|
|
19
|
+
* (TextField/TextArea render a transparent <input> inside a
|
|
20
|
+
* bg-inputs-inputs-primary wrapper) — a translucent tint here paints a
|
|
21
|
+
* visibly lighter band inside the field in dark mode. Note this rule
|
|
22
|
+
* cannot be overridden by unlayered !important declarations downstream:
|
|
23
|
+
* for !important the cascade reverses, so @layer base wins.
|
|
24
|
+
*/
|
|
16
25
|
input:-webkit-autofill,
|
|
17
26
|
input:-webkit-autofill:hover,
|
|
18
27
|
input:-webkit-autofill:focus,
|
|
@@ -26,8 +35,8 @@
|
|
|
26
35
|
textarea:autofill:hover,
|
|
27
36
|
textarea:autofill:focus {
|
|
28
37
|
-webkit-text-fill-color: var(--color-content-primary);
|
|
29
|
-
-webkit-box-shadow: inset 0 0 0 1000px var(--color-
|
|
30
|
-
box-shadow: inset 0 0 0 1000px var(--color-
|
|
38
|
+
-webkit-box-shadow: inset 0 0 0 1000px var(--color-inputs-inputs-primary) !important;
|
|
39
|
+
box-shadow: inset 0 0 0 1000px var(--color-inputs-inputs-primary) !important;
|
|
31
40
|
background-clip: padding-box !important;
|
|
32
41
|
transition: background-color 9999s ease-in-out 0s;
|
|
33
42
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
const RAW_PEAK_COUNT = 128;
|
|
3
|
+
function formatTime(seconds) {
|
|
4
|
+
if (seconds === void 0 || !Number.isFinite(seconds)) return "--:--";
|
|
5
|
+
const totalSeconds = Math.max(0, Math.floor(seconds));
|
|
6
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
7
|
+
const remainingSeconds = totalSeconds % 60;
|
|
8
|
+
return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
|
|
9
|
+
}
|
|
10
|
+
function hashString(value) {
|
|
11
|
+
let hash = 2166136261;
|
|
12
|
+
for (let i = 0; i < value.length; i++) {
|
|
13
|
+
hash ^= value.charCodeAt(i);
|
|
14
|
+
hash = Math.imul(hash, 16777619);
|
|
15
|
+
}
|
|
16
|
+
return hash >>> 0;
|
|
17
|
+
}
|
|
18
|
+
function createSeededRandom(seed) {
|
|
19
|
+
let state = seed;
|
|
20
|
+
return () => {
|
|
21
|
+
state = state + 1831565813 | 0;
|
|
22
|
+
let t = Math.imul(state ^ state >>> 15, 1 | state);
|
|
23
|
+
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
|
|
24
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function generateFallbackPeaks(src, count) {
|
|
28
|
+
const random = createSeededRandom(hashString(src));
|
|
29
|
+
return Array.from({ length: count }, () => 0.2 + random() * 0.8);
|
|
30
|
+
}
|
|
31
|
+
function computePeaksFromChannelData(channelData, count) {
|
|
32
|
+
const blockSize = Math.max(1, Math.floor(channelData.length / count));
|
|
33
|
+
const peaks = [];
|
|
34
|
+
for (let i = 0; i < count; i++) {
|
|
35
|
+
const start = i * blockSize;
|
|
36
|
+
let max = 0;
|
|
37
|
+
for (let j = 0; j < blockSize && start + j < channelData.length; j++) {
|
|
38
|
+
max = Math.max(max, Math.abs(channelData[start + j] ?? 0));
|
|
39
|
+
}
|
|
40
|
+
peaks.push(max);
|
|
41
|
+
}
|
|
42
|
+
return peaks;
|
|
43
|
+
}
|
|
44
|
+
function resamplePeaks(peaks, barCount) {
|
|
45
|
+
if (peaks.length === 0 || barCount <= 0) return [];
|
|
46
|
+
const step = peaks.length / barCount;
|
|
47
|
+
return Array.from(
|
|
48
|
+
{ length: barCount },
|
|
49
|
+
(_, i) => peaks[Math.min(peaks.length - 1, Math.floor(i * step))] ?? 0
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
async function decodeAudioPeaks(src, signal) {
|
|
53
|
+
const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;
|
|
54
|
+
if (!AudioContextCtor) throw new Error("WebAudio unsupported");
|
|
55
|
+
const response = await fetch(src, { signal });
|
|
56
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
57
|
+
const audioContext = new AudioContextCtor();
|
|
58
|
+
try {
|
|
59
|
+
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
|
|
60
|
+
return computePeaksFromChannelData(audioBuffer.getChannelData(0), RAW_PEAK_COUNT);
|
|
61
|
+
} finally {
|
|
62
|
+
if (audioContext.state !== "closed") audioContext.close().catch(() => {
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export {
|
|
67
|
+
RAW_PEAK_COUNT,
|
|
68
|
+
computePeaksFromChannelData,
|
|
69
|
+
createSeededRandom,
|
|
70
|
+
decodeAudioPeaks,
|
|
71
|
+
formatTime,
|
|
72
|
+
generateFallbackPeaks,
|
|
73
|
+
hashString,
|
|
74
|
+
resamplePeaks
|
|
75
|
+
};
|
|
76
|
+
//# sourceMappingURL=audioWaveform.mjs.map
|