From 0b9c6879c90eceb9792ca09a1cfe8e937d2fd206 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH] fix: improve ux on voice memos --- .../features/room/AudioAttachmentPreview.tsx | 194 +++++++++++++++ .../features/room/AudioMessageRecorder.tsx | 222 ++++++++++++------ src/app/features/room/RoomInput.tsx | 184 ++++++++++----- src/app/utils/debug.ts | 3 +- 4 files changed, 472 insertions(+), 131 deletions(-) create mode 100644 src/app/features/room/AudioAttachmentPreview.tsx diff --git a/src/app/features/room/AudioAttachmentPreview.tsx b/src/app/features/room/AudioAttachmentPreview.tsx new file mode 100644 index 00000000..e054eb0b --- /dev/null +++ b/src/app/features/room/AudioAttachmentPreview.tsx @@ -0,0 +1,194 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Box, Chip, Icon, Icons, IconButton, Text, color, config, toRem } from 'folds'; + +type AudioAttachmentPreviewProps = { + audioUrl: string; + waveform: number[]; + duration: number; // seconds + onDelete: () => void; +}; + +function formatTime(s: number): string { + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${m}:${sec.toString().padStart(2, '0')}`; +} + +const BAR_COUNT = 44; + +/** + * Attachment-area chip for a just-recorded voice message. + * + * Shows a play/pause button, a clickable waveform scrubber that fills + * with Primary colour as playback advances, a duration counter, and a + * delete button that matches the UploadBoard cancel chip style. + */ +export function AudioAttachmentPreview({ + audioUrl, + waveform, + duration, + onDelete, +}: AudioAttachmentPreviewProps) { + const [isPlaying, setIsPlaying] = useState(false); + const [currentTime, setCurrentTime] = useState(0); + const audioRef = useRef(null); + const rafRef = useRef(null); + + // Downsample waveform to BAR_COUNT display bars + const bars = Array.from({ length: BAR_COUNT }, (_, i) => { + const src = waveform.length > 0 ? waveform : Array(BAR_COUNT).fill(0.3); + const step = src.length / BAR_COUNT; + return src[Math.floor(i * step)] ?? 0; + }); + + const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; + + // Animate current-time with rAF while playing for a smooth scrubber + const startRaf = useCallback((audio: HTMLAudioElement) => { + const tick = () => { + setCurrentTime(audio.currentTime); + rafRef.current = requestAnimationFrame(tick); + }; + rafRef.current = requestAnimationFrame(tick); + }, []); + + const stopRaf = useCallback(() => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }, []); + + useEffect(() => { + const audio = new Audio(audioUrl); + audioRef.current = audio; + + audio.onended = () => { + setIsPlaying(false); + setCurrentTime(0); + stopRaf(); + }; + + return () => { + audio.pause(); + stopRaf(); + }; + }, [audioUrl, stopRaf]); + + const handlePlayPause = useCallback(() => { + const audio = audioRef.current; + if (!audio) return; + + if (isPlaying) { + audio.pause(); + setIsPlaying(false); + stopRaf(); + } else { + audio.play().catch(() => {}); + setIsPlaying(true); + startRaf(audio); + } + }, [isPlaying, startRaf, stopRaf]); + + const handleScrubClick = useCallback( + (e: React.MouseEvent) => { + const audio = audioRef.current; + if (!audio || !duration) return; + const rect = e.currentTarget.getBoundingClientRect(); + const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); + audio.currentTime = ratio * duration; + setCurrentTime(audio.currentTime); + }, + [duration] + ); + + return ( + + {/* Play / Pause */} + + + + + {/* Waveform scrubber */} + + {bars.map((level, i) => { + const barRatio = i / BAR_COUNT; + const played = barRatio <= progress; + return ( +
+ ); + })} + + + {/* Time display: shows current position while playing, total when paused */} + + {formatTime(isPlaying ? currentTime : duration)} + + + {/* Delete — matches UploadBoardHeader "Remove" chip style */} + } + title="Remove voice message" + aria-label="Remove voice message" + /> + + ); +} diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index f324d444..dd5d3bab 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -1,7 +1,12 @@ -import { VoiceRecorder } from '$plugins/voice-recorder-kit'; -import FocusTrap from 'focus-trap-react'; -import { Box, Icon, Icons, Text, color, config } from 'folds'; -import { useRef } from 'react'; +import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'; +import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; +import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; +import { Box, Text, color, config, toRem } from 'folds'; + +export type AudioMessageRecorderHandle = { + stop: () => void; + cancel: () => void; +}; type AudioMessageRecorderProps = { onRecordingComplete: (audioBlob: Blob) => void; @@ -10,83 +15,148 @@ type AudioMessageRecorderProps = { onAudioLengthUpdate: (length: number) => void; }; -// We use a react voice recorder library to handle the recording of audio messages, as it provides a simple API and handles the complexities of recording audio in the browser. -// The component is wrapped in a focus trap to ensure that keyboard users can easily navigate and interact with the recorder without accidentally losing focus or interacting with other parts of the UI. -// The styling is kept simple and consistent with the rest of the app, using Folds' design tokens for colors, spacing, and typography. -// we use a modified version of https://www.npmjs.com/package/react-voice-recorder-kit for the recording -export function AudioMessageRecorder({ - onRecordingComplete, - onRequestClose, - onWaveformUpdate, - onAudioLengthUpdate, -}: AudioMessageRecorderProps) { - const containerRef = useRef(null); +function formatTime(seconds: number): string { + const m = Math.floor(seconds / 60); + const s = seconds % 60; + return `${m}:${s.toString().padStart(2, '0')}`; +} + +const KEYFRAMES = ` +@keyframes recDotPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.25; } +} +`; +if (typeof document !== 'undefined') { + const styleId = '__audio-recorder-keyframes'; + if (!document.getElementById(styleId)) { + const style = document.createElement('style'); + style.id = styleId; + style.textContent = KEYFRAMES; + document.head.appendChild(style); + } +} + +export const AudioMessageRecorder = forwardRef< + AudioMessageRecorderHandle, + AudioMessageRecorderProps +>(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => { const isDismissedRef = useRef(false); + // Guard against React Strict Mode's double-invoke of the autoStart effect, + // which fires onstop with a ~110-byte blob before the user does anything. + const userRequestedStopRef = useRef(false); + + // Keep stable refs for prop callbacks so useVoiceRecorder's internal + // useCallbacks never need to be recreated (which would reset the timer). + const onRecordingCompleteRef = useRef(onRecordingComplete); + onRecordingCompleteRef.current = onRecordingComplete; + const onRequestCloseRef = useRef(onRequestClose); + onRequestCloseRef.current = onRequestClose; + const onWaveformUpdateRef = useRef(onWaveformUpdate); + onWaveformUpdateRef.current = onWaveformUpdate; + const onAudioLengthUpdateRef = useRef(onAudioLengthUpdate); + onAudioLengthUpdateRef.current = onAudioLengthUpdate; + + // Stable stop handler — empty dep array intentional; live values via refs. + + const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => { + if (!userRequestedStopRef.current) return; + if (isDismissedRef.current) return; + onRecordingCompleteRef.current(payload.audioFile); + onWaveformUpdateRef.current(payload.waveform); + onAudioLengthUpdateRef.current(payload.audioLength); + }, []); + + // Stable delete handler — empty dep array intentional; live values via refs. + + const stableOnDelete = useCallback(() => { + isDismissedRef.current = true; + onRequestCloseRef.current(); + }, []); + + const { levels, seconds, handleStop, handleDelete } = useVoiceRecorder({ + autoStart: true, + onStop: stableOnStop, + onDelete: stableOnDelete, + }); + + const doStop = useCallback(() => { + if (isDismissedRef.current) return; + userRequestedStopRef.current = true; + handleStop(); + }, [handleStop]); + + const doCancel = useCallback(() => { + if (isDismissedRef.current) return; + isDismissedRef.current = true; + handleDelete(); + }, [handleDelete]); + + useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]); + + const BAR_COUNT = 28; + const step = Math.max(1, levels.length / BAR_COUNT); + const bars = Array.from( + { length: BAR_COUNT }, + (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 + ); - // uses default styling, we use at other places return ( - { - isDismissedRef.current = true; - onRequestClose(); - }, - clickOutsideDeactivates: true, - allowOutsideClick: true, - fallbackFocus: () => containerRef.current!, - }} + -
- - Audio Message Recorder - { - if (isDismissedRef.current) return; - // closes the recorder and sends the audio file back to the parent component to be uploaded and sent as a message - onRecordingComplete(audioFile); - onWaveformUpdate(waveform); - onAudioLengthUpdate(audioLength); - }} - buttonBackgroundColor={color.SurfaceVariant.Container} - buttonHoverBackgroundColor={color.SurfaceVariant.ContainerHover} - iconColor={color.Primary.Main} - // icons for the recorder, we use Folds' icon library to keep the styling consistent with the rest of the app - customPauseIcon={} - customPlayIcon={} - customDeleteIcon={} - customStopIcon={} - customRepeatIcon={} - customResumeIcon={} + {/* Pulsing red dot */} +
+ + {/* Live waveform bars */} + + {bars.map((level, i) => ( +
- -
- + ))} +
+ + {/* Timer */} + + {formatTime(seconds)} + + ); -} +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index b280cf5d..a531f173 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -24,6 +24,7 @@ import { ReactEditor } from 'slate-react'; import { Editor, Point, Range, Transforms } from 'slate'; import { Box, + color, config, Dialog, Icon, @@ -158,7 +159,8 @@ import { getVideoMsgContent, } from './msgContent'; import { CommandAutocomplete } from './CommandAutocomplete'; -import { AudioMessageRecorder } from './AudioMessageRecorder'; +import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder'; +import { AudioAttachmentPreview } from './AudioAttachmentPreview'; const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => { if (!replyDraft) return {}; @@ -251,6 +253,18 @@ export const RoomInput = forwardRef( const [showAudioRecorder, setShowAudioRecorder] = useState(false); const [audioMsgWaveform, setAudioMsgWaveform] = useState(undefined); const [audioMsgLength, setAudioMsgLength] = useState(undefined); + // pendingAudioFileRef is a ref (not state) so its value is set synchronously + // before handleFiles → setSelectedFiles (Jotai) can trigger a render. + // Using useState here caused a render window where selectedFiles already contained + // the file but pendingAudioFile state was still null, letting UploadCardRenderer + // render for the audio file and trigger an upload-during-render state dispatch. + const pendingAudioFileRef = useRef(null); + const [pendingAudioUrl, setPendingAudioUrl] = useState(null); + const audioRecorderRef = useRef(null); + // Tracks when the mic button was pressed on mobile so we can distinguish + // a quick tap (toggle — user stops manually) from a long hold (send on release). + const micHoldStartRef = useRef(0); + const HOLD_THRESHOLD_MS = 400; const [autocompleteQuery, setAutocompleteQuery] = useState>(); const [isQuickTextReact, setQuickTextReact] = useState(false); @@ -421,6 +435,19 @@ export const RoomInput = forwardRef( const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { const uploads = Array.isArray(upload) ? upload : [upload]; + // If the pending audio file is being removed (via UploadBoard's Remove button), + // clean up the object URL and reset audio preview state. + uploads.forEach((u) => { + if (u === pendingAudioFileRef.current) { + setPendingAudioUrl((url) => { + if (url) URL.revokeObjectURL(url); + return null; + }); + pendingAudioFileRef.current = null; + setAudioMsgWaveform(undefined); + setAudioMsgLength(undefined); + } + }); setSelectedFiles({ type: 'DELETE', item: selectedFiles.filter((f) => uploads.find((u) => u === f.file)), @@ -827,18 +854,35 @@ export const RoomInput = forwardRef( {Array.from(selectedFiles) .reverse() - .map((fileItem, index) => ( - - ))} + .map((fileItem, index) => { + // pendingAudioFileRef is a ref so it's available synchronously + // even in Jotai-triggered renders — UploadCardRenderer never + // renders for the audio file, preventing the upload-during-render + // setState warning on UploadBoardHeader. + if (fileItem.file === pendingAudioFileRef.current && pendingAudioUrl) { + return ( + + ); + } + return ( + + ); + })} )} @@ -1059,6 +1103,79 @@ export const RoomInput = forwardRef( } after={ <> + {/* ── Recording pill: grows into available space left of mic button ── */} + {showAudioRecorder && ( + setShowAudioRecorder(false)} + onRecordingComplete={(audioBlob) => { + const file = new File([audioBlob], `sable-audio-message-${Date.now()}.ogg`, { + type: audioBlob.type, + }); + // Set ref synchronously BEFORE handleFiles so the Jotai render + // that follows immediately sees it and skips UploadCardRenderer. + pendingAudioFileRef.current = file; + setPendingAudioUrl(URL.createObjectURL(audioBlob)); + handleFiles([file]); + setShowAudioRecorder(false); + }} + onAudioLengthUpdate={(len) => setAudioMsgLength(len)} + onWaveformUpdate={(w) => setAudioMsgWaveform(w)} + /> + )} + + {/* ── Mic button — always present; icon swaps to Stop while recording ── */} + { + if (mobileOrTablet()) return; // mobile handled via pointerdown/up + if (showAudioRecorder) { + audioRecorderRef.current?.stop(); + } else { + setShowAudioRecorder(true); + } + }} + onPointerDown={() => { + if (!mobileOrTablet()) return; + if (showAudioRecorder) return; // already recording — onClick will stop it + micHoldStartRef.current = Date.now(); + setShowAudioRecorder(true); + + // One-shot global listeners: the mic button stays mounted now but + // the ref is already populated by the time pointerup fires. + const cleanup = () => { + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onCancel); + }; + const onUp = () => { + cleanup(); + const held = Date.now() - micHoldStartRef.current; + if (held >= HOLD_THRESHOLD_MS) { + audioRecorderRef.current?.stop(); + } + // Short tap → recorder stays open; tap stop-icon to finish + }; + const onCancel = () => { + cleanup(); + audioRecorderRef.current?.cancel(); + }; + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onCancel); + }} + > + + + + {/* ── Toolbar toggle — always visible ── */} ( > - setShowAudioRecorder(!showAudioRecorder)} - > - - - {showAudioRecorder && ( - { - setShowAudioRecorder(false); - }} - onRecordingComplete={(audioBlob) => { - const file = new File( - [audioBlob], - `sable-audio-message-${Date.now()}.ogg`, - { - type: audioBlob.type, - } - ); - handleFiles([file]); - // Close the recorder after handling the file, to give some feedback that the recording was successful - setShowAudioRecorder(false); - }} - onAudioLengthUpdate={(len) => setAudioMsgLength(len)} - onWaveformUpdate={(w) => setAudioMsgWaveform(w)} - /> - } - /> - )} {(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => ( localStorage.getItem('sable_debug') === '1'; +export const isDebug = (): boolean => + import.meta.env.DEV || localStorage.getItem('sable_debug') === '1'; type LogLevel = 'log' | 'warn' | 'error';