fix: improve ux on voice memos

This commit is contained in:
hazre committed 2026-03-16 15:15:56 +01:00
1 parent b90555a27c
commit 0b9c6879c9
4 files changed
+472 -131

No files matched your search

@@ -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<HTMLAudioElement | null>(null);
const rafRef = useRef<number | null>(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<HTMLDivElement>) => {
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 (
<Box
alignItems="Center"
gap="200"
style={{
backgroundColor: color.SurfaceVariant.Container,
border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
borderRadius: config.radii.R300,
padding: `${config.space.S100} ${config.space.S200}`,
// Matches the max-width of UploadBoard so it looks native in that context
maxWidth: toRem(400),
width: '100%',
boxSizing: 'border-box',
}}
>
{/* Play / Pause */}
<IconButton
variant="SurfaceVariant"
size="300"
radii="300"
onClick={handlePlayPause}
title={isPlaying ? 'Pause' : 'Play voice message'}
aria-label={isPlaying ? 'Pause' : 'Play voice message'}
>
<Icon src={isPlaying ? Icons.Pause : Icons.Play} size="200" />
</IconButton>
{/* Waveform scrubber */}
<Box
grow="Yes"
alignItems="Center"
gap="25"
onClick={handleScrubClick}
style={{
height: 28,
cursor: 'pointer',
userSelect: 'none',
overflow: 'hidden',
}}
title="Seek"
>
{bars.map((level, i) => {
const barRatio = i / BAR_COUNT;
const played = barRatio <= progress;
return (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
style={{
width: 2,
height: Math.max(3, Math.round(level * 24)),
borderRadius: 1,
backgroundColor: played ? color.Primary.Main : color.SurfaceVariant.OnContainer,
opacity: played ? 1 : 0.45,
flexShrink: 0,
transition: 'background-color 40ms, opacity 40ms',
pointerEvents: 'none',
}}
/>
);
})}
</Box>
{/* Time display: shows current position while playing, total when paused */}
<Text
size="T200"
style={{
fontVariantNumeric: 'tabular-nums',
color: color.Surface.OnContainer,
minWidth: toRem(30),
textAlign: 'right',
flexShrink: 0,
}}
>
{formatTime(isPlaying ? currentTime : duration)}
</Text>
{/* Delete — matches UploadBoardHeader "Remove" chip style */}
<Chip
as="button"
onClick={onDelete}
variant="SurfaceVariant"
radii="Pill"
after={<Icon src={Icons.Cross} size="50" />}
title="Remove voice message"
aria-label="Remove voice message"
/>
</Box>
);
}
+146 -76
View File
@@ -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<HTMLDivElement>(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 (
<FocusTrap
focusTrapOptions={{
returnFocusOnDeactivate: false,
initialFocus: false,
onDeactivate: () => {
isDismissedRef.current = true;
onRequestClose();
},
clickOutsideDeactivates: true,
allowOutsideClick: true,
fallbackFocus: () => containerRef.current!,
}}
<Box
grow="Yes"
alignItems="Center"
gap="200"
style={{ minWidth: 0, overflow: 'hidden', padding: `0 ${config.space.S200}` }}
>
<div ref={containerRef} tabIndex={-1} style={{ outline: 'none' }}>
<Box
direction="Column"
gap="200"
alignItems="Center"
style={{
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`,
borderRadius: config.radii.R400,
boxShadow: config.shadow.E200,
padding: config.space.S400,
minWidth: 300,
}}
>
<Text size="H4">Audio Message Recorder</Text>
<VoiceRecorder
autoStart
onStop={({
audioFile,
waveform,
audioLength,
}: {
audioFile: Blob;
waveform: number[];
audioLength: number;
}) => {
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={<Icon src={Icons.Pause} size="200" color={color.Primary.Main} />}
customPlayIcon={<Icon src={Icons.Play} size="200" color={color.Primary.Main} />}
customDeleteIcon={<Icon src={Icons.Delete} size="200" color={color.Primary.Main} />}
customStopIcon={<Icon src={Icons.Send} size="200" color={color.Primary.Main} />}
customRepeatIcon={<Icon src={Icons.Reload} size="200" color={color.Primary.Main} />}
customResumeIcon={<Icon src={Icons.Mic} size="200" color={color.Primary.Main} />}
{/* Pulsing red dot */}
<div
aria-hidden
style={{
width: 7,
height: 7,
borderRadius: '50%',
backgroundColor: color.Critical.Main,
flexShrink: 0,
animation: 'recDotPulse 1.4s ease-in-out infinite',
}}
/>
{/* Live waveform bars */}
<Box
grow="Yes"
alignItems="Center"
gap="25"
style={{ height: 22, overflow: 'hidden', minWidth: 0 }}
>
{bars.map((level, i) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
style={{
backgroundColor: color.Surface.ContainerActive,
width: 2,
height: Math.max(3, Math.round(level * 20)),
borderRadius: 1,
backgroundColor: color.Primary.Main,
transition: 'height 70ms ease-out',
flexShrink: 0,
}}
/>
</Box>
</div>
</FocusTrap>
))}
</Box>
{/* Timer */}
<Text
size="T200"
style={{
fontVariantNumeric: 'tabular-nums',
color: color.Critical.Main,
minWidth: toRem(28),
flexShrink: 0,
fontWeight: 600,
}}
>
{formatTime(seconds)}
</Text>
</Box>
);
}
});
+130 -54
View File
@@ -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<HTMLDivElement, RoomInputProps>(
const [showAudioRecorder, setShowAudioRecorder] = useState(false);
const [audioMsgWaveform, setAudioMsgWaveform] = useState<number[] | undefined>(undefined);
const [audioMsgLength, setAudioMsgLength] = useState<number | undefined>(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<File | null>(null);
const [pendingAudioUrl, setPendingAudioUrl] = useState<string | null>(null);
const audioRecorderRef = useRef<AudioMessageRecorderHandle>(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<number>(0);
const HOLD_THRESHOLD_MS = 400;
const [autocompleteQuery, setAutocompleteQuery] =
useState<AutocompleteQuery<AutocompletePrefix>>();
const [isQuickTextReact, setQuickTextReact] = useState(false);
@@ -421,6 +435,19 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
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<HTMLDivElement, RoomInputProps>(
<UploadBoardContent>
{Array.from(selectedFiles)
.reverse()
.map((fileItem, index) => (
<UploadCardRenderer
// eslint-disable-next-line react/no-array-index-key
key={index}
isEncrypted={!!fileItem.encInfo}
fileItem={fileItem}
setMetadata={handleFileMetadata}
onRemove={handleRemoveUpload}
setDesc={setDesc}
roomId={roomId}
/>
))}
.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 (
<AudioAttachmentPreview
// eslint-disable-next-line react/no-array-index-key
key={index}
audioUrl={pendingAudioUrl}
waveform={audioMsgWaveform ?? []}
duration={audioMsgLength ?? 0}
/>
);
}
return (
<UploadCardRenderer
// eslint-disable-next-line react/no-array-index-key
key={index}
isEncrypted={!!fileItem.encInfo}
fileItem={fileItem}
setMetadata={handleFileMetadata}
onRemove={handleRemoveUpload}
setDesc={setDesc}
roomId={roomId}
/>
);
})}
</UploadBoardContent>
</Scroll>
)}
@@ -1059,6 +1103,79 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
after={
<>
{/* ── Recording pill: grows into available space left of mic button ── */}
{showAudioRecorder && (
<AudioMessageRecorder
ref={audioRecorderRef}
onRequestClose={() => 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 ── */}
<IconButton
ref={micBtnRef}
variant={showAudioRecorder ? 'Critical' : 'SurfaceVariant'}
size="300"
radii="300"
title={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-pressed={showAudioRecorder}
onClick={() => {
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);
}}
>
<Icon
src={Icons.Mic}
{...(showAudioRecorder ? { style: { color: color.Critical.Main } } : {})}
/>
</IconButton>
{/* ── Toolbar toggle — always visible ── */}
<IconButton
variant="SurfaceVariant"
size="300"
@@ -1070,47 +1187,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
>
<Icon src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<IconButton
ref={micBtnRef}
variant="SurfaceVariant"
size="300"
radii="300"
title="record audio message"
aria-pressed={showAudioRecorder}
onClick={() => setShowAudioRecorder(!showAudioRecorder)}
>
<Icon src={Icons.Mic} />
</IconButton>
{showAudioRecorder && (
<PopOut
anchor={micBtnRef.current?.getBoundingClientRect() ?? undefined}
offset={8}
position="Top"
align="End"
alignOffset={-44}
content={
<AudioMessageRecorder
onRequestClose={() => {
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)}
/>
}
/>
)}
<UseStateProvider initial={undefined}>
{(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => (
<PopOut
+2 -1
View File
@@ -8,7 +8,8 @@
* localStorage.removeItem('sable_debug'); location.reload();
*/
const isDebug = (): boolean => localStorage.getItem('sable_debug') === '1';
export const isDebug = (): boolean =>
import.meta.env.DEV || localStorage.getItem('sable_debug') === '1';
type LogLevel = 'log' | 'warn' | 'error';