From 0b9c6879c90eceb9792ca09a1cfe8e937d2fd206 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 01/31] 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 000000000..e054eb0b8 --- /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 f324d444c..dd5d3bab0 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 b280cf5d5..a531f1735 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'; From bf6d7ce4a6b3232900267a662363f70984d2ee59 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 02/31] fix: a lot more polish on voice messages --- package.json | 1 + pnpm-lock.yaml | 15 + .../components/upload-card/UploadCard.css.ts | 64 +- .../upload-card/UploadCardRenderer.tsx | 177 ++++- .../features/room/AudioAttachmentPreview.tsx | 194 ------ .../features/room/AudioMessageRecorder.css.ts | 121 ++++ .../features/room/AudioMessageRecorder.tsx | 242 ++++--- src/app/features/room/RoomInput.tsx | 130 ++-- src/app/features/room/msgContent.ts | 14 +- src/app/plugins/voice-recorder-kit/README.md | 492 -------------- .../voice-recorder-kit/VoiceRecorder.tsx | 620 ------------------ src/app/plugins/voice-recorder-kit/icons.tsx | 76 --- src/app/plugins/voice-recorder-kit/index.ts | 2 - src/app/plugins/voice-recorder-kit/types.ts | 41 -- .../voice-recorder-kit/useVoiceRecorder.ts | 25 +- src/app/state/room/roomInputDrafts.ts | 2 + 16 files changed, 613 insertions(+), 1603 deletions(-) delete mode 100644 src/app/features/room/AudioAttachmentPreview.tsx create mode 100644 src/app/features/room/AudioMessageRecorder.css.ts delete mode 100644 src/app/plugins/voice-recorder-kit/README.md delete mode 100644 src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx delete mode 100644 src/app/plugins/voice-recorder-kit/icons.tsx diff --git a/package.json b/package.json index 371e7a975..14cd7c172 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.1.0", "@fontsource-variable/nunito": "5.2.7", "@fontsource/space-mono": "5.2.9", + "@phosphor-icons/react": "^2.1.10", "@tanstack/react-query": "^5.90.21", "@tanstack/react-query-devtools": "^5.91.3", "@tanstack/react-virtual": "^3.13.19", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e0d64afd3..a1c45c6d3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,6 +31,9 @@ importers: '@fontsource/space-mono': specifier: 5.2.9 version: 5.2.9 + '@phosphor-icons/react': + specifier: ^2.1.10 + version: 2.1.10(react-dom@18.3.1(react@18.3.1))(react@18.3.1) '@tanstack/react-query': specifier: ^5.90.21 version: 5.90.21(react@18.3.1) @@ -1549,6 +1552,13 @@ packages: cpu: [x64] os: [win32] + '@phosphor-icons/react@2.1.10': + resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==} + engines: {node: '>=10'} + peerDependencies: + react: '>= 16.8' + react-dom: '>= 16.8' + '@pkgr/core@0.2.9': resolution: {integrity: sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==} engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} @@ -6360,6 +6370,11 @@ snapshots: '@oxc-resolver/binding-win32-x64-msvc@11.19.1': optional: true + '@phosphor-icons/react@2.1.10(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + '@pkgr/core@0.2.9': {} '@poppinss/colors@4.1.6': diff --git a/src/app/components/upload-card/UploadCard.css.ts b/src/app/components/upload-card/UploadCard.css.ts index ad3caf10e..d02cbe3f5 100644 --- a/src/app/components/upload-card/UploadCard.css.ts +++ b/src/app/components/upload-card/UploadCard.css.ts @@ -1,6 +1,6 @@ import { style } from '@vanilla-extract/css'; import { RecipeVariants, recipe } from '@vanilla-extract/recipes'; -import { RadiiVariant, color, config } from 'folds'; +import { DefaultReset, RadiiVariant, color, config, toRem } from 'folds'; export const UploadCard = recipe({ base: { @@ -34,3 +34,65 @@ export const UploadCardError = style({ padding: `0 ${config.space.S100}`, color: color.Critical.Main, }); + +export const AudioPreviewContainer = style([ + DefaultReset, + { + backgroundColor: color.SurfaceVariant.Container, + border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`, + borderRadius: config.radii.R400, + padding: config.space.S300, + width: '100%', + maxWidth: toRem(400), + boxSizing: 'border-box', + }, +]); + +export const AudioWaveformContainer = style([ + DefaultReset, + { + minHeight: 44, + cursor: 'pointer', + userSelect: 'none', + overflow: 'hidden', + }, +]); + +export const AudioWaveformBar = style([ + DefaultReset, + { + width: 2, + height: 3, + borderRadius: 1, + flexShrink: 0, + transition: 'background-color 40ms, opacity 40ms', + pointerEvents: 'none', + }, +]); + +export const AudioWaveformBarPlayed = style([ + DefaultReset, + { + backgroundColor: color.Secondary.Main, + opacity: 1, + }, +]); + +export const AudioWaveformBarUnplayed = style([ + DefaultReset, + { + backgroundColor: color.SurfaceVariant.OnContainer, + opacity: 0.5, + }, +]); + +export const AudioTimeDisplay = style([ + DefaultReset, + { + fontVariantNumeric: 'tabular-nums', + color: color.SurfaceVariant.OnContainer, + minWidth: toRem(30), + textAlign: 'right', + flexShrink: 0, + }, +]); diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 55dbba3c7..aa060835c 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -1,4 +1,4 @@ -import { ReactNode, useEffect, useMemo, useState } from 'react'; +import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Chip, @@ -14,6 +14,7 @@ import { toRem, } from 'folds'; import { HTMLReactParserOptions } from 'html-react-parser'; +import { Play, Pause } from '@phosphor-icons/react'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser'; @@ -27,6 +28,7 @@ import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/ import { useObjectURL } from '$hooks/useObjectURL'; import { useMediaConfig } from '$hooks/useMediaConfig'; import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard'; +import * as css from './UploadCard.css'; import { DescriptionEditor } from './UploadDescriptionEditor'; type PreviewImageProps = { @@ -71,6 +73,178 @@ function PreviewVideo({ fileItem }: PreviewVideoProps) { ); } +const BAR_COUNT = 44; + +function formatAudioTime(s: number): string { + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${m}:${sec.toString().padStart(2, '0')}`; +} + +type PreviewAudioProps = { + fileItem: TUploadItem; +}; +function PreviewAudio({ fileItem }: PreviewAudioProps) { + const { originalFile, metadata } = fileItem; + const audioUrl = useObjectURL(originalFile); + const { waveform, audioDuration } = metadata; + const duration = audioDuration ?? 0; + + const [isPlaying, setIsPlaying] = useState(false); + const [currentTime, setCurrentTime] = useState(0); + const audioRef = useRef(null); + const rafRef = useRef(null); + + const bars = useMemo(() => { + if (!waveform || waveform.length === 0) { + return Array(BAR_COUNT).fill(0.3); + } + const step = waveform.length / BAR_COUNT; + return Array.from({ length: BAR_COUNT }, (_, i) => waveform[Math.floor(i * step)] ?? 0); + }, [waveform]); + + const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; + + useEffect(() => { + if (!audioUrl) { + return undefined; + } + const audio = new Audio(audioUrl); + audioRef.current = audio; + + audio.onended = () => { + setIsPlaying(false); + setCurrentTime(0); + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }; + + return () => { + audio.pause(); + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + } + }; + }, [audioUrl]); + + const startRaf = (audio: HTMLAudioElement) => { + const tick = () => { + setCurrentTime(audio.currentTime); + rafRef.current = requestAnimationFrame(tick); + }; + rafRef.current = requestAnimationFrame(tick); + }; + + const stopRaf = () => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }; + + const handlePlayPause = () => { + const audio = audioRef.current; + if (!audio) return; + + if (isPlaying) { + audio.pause(); + setIsPlaying(false); + stopRaf(); + } else { + audio.play().catch(() => {}); + setIsPlaying(true); + startRaf(audio); + } + }; + + const handleScrubClick = (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); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + const audio = audioRef.current; + if (!audio || !duration) return; + + const SEEK_STEP = 5; + let newTime = currentTime; + + if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { + e.preventDefault(); + newTime = Math.max(0, currentTime - SEEK_STEP); + } else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { + e.preventDefault(); + newTime = Math.min(duration, currentTime + SEEK_STEP); + } else if (e.key === 'Home') { + e.preventDefault(); + newTime = 0; + } else if (e.key === 'End') { + e.preventDefault(); + newTime = duration; + } else { + return; + } + + audio.currentTime = newTime; + setCurrentTime(newTime); + }; + + return ( + + + {isPlaying ? : } + + + + {bars.map((level, i) => { + const barRatio = i / BAR_COUNT; + const played = barRatio <= progress; + return ( +
+ ); + })} + + + + {formatAudioTime(isPlaying ? currentTime : duration)} + + + ); +} + type MediaPreviewProps = { fileItem: TUploadItem; onSpoiler: (marked: boolean) => void; @@ -247,6 +421,7 @@ export function UploadCardRenderer({ )} + {fileItem.metadata.waveform && } {upload.status === UploadStatus.Idle && !fileSizeExceeded && ( )} diff --git a/src/app/features/room/AudioAttachmentPreview.tsx b/src/app/features/room/AudioAttachmentPreview.tsx deleted file mode 100644 index e054eb0b8..000000000 --- a/src/app/features/room/AudioAttachmentPreview.tsx +++ /dev/null @@ -1,194 +0,0 @@ -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.css.ts b/src/app/features/room/AudioMessageRecorder.css.ts new file mode 100644 index 000000000..44c7bcd02 --- /dev/null +++ b/src/app/features/room/AudioMessageRecorder.css.ts @@ -0,0 +1,121 @@ +import { keyframes, style } from '@vanilla-extract/css'; +import { DefaultReset, color, config, toRem } from 'folds'; + +const RecDotPulse = keyframes({ + '0%, 100%': { opacity: 1 }, + '50%': { opacity: 0.25 }, +}); + +const SlideOutLeft = keyframes({ + '0%': { transform: 'translateX(0)', opacity: 1 }, + '100%': { transform: 'translateX(-100%)', opacity: 0 }, +}); + +const Shake = keyframes({ + '0%, 100%': { transform: 'translateX(0)' }, + '20%': { transform: 'translateX(-4px)' }, + '40%': { transform: 'translateX(4px)' }, + '60%': { transform: 'translateX(-4px)' }, + '80%': { transform: 'translateX(4px)' }, +}); + +export const Container = style([ + DefaultReset, + { + minWidth: 0, + overflow: 'hidden', + padding: `0 ${config.space.S200}`, + touchAction: 'pan-y', + userSelect: 'none', + }, +]); + +export const ContainerCanceling = style({ + animation: `${SlideOutLeft} 200ms ease-out forwards`, +}); + +export const ContainerShake = style({ + animation: `${Shake} 300ms ease-out`, +}); + +export const RecDot = style([ + DefaultReset, + { + width: 7, + height: 7, + borderRadius: '50%', + backgroundColor: color.Critical.Main, + flexShrink: 0, + animation: `${RecDotPulse} 1.4s ease-in-out infinite`, + }, +]); + +export const WaveformContainer = style([ + DefaultReset, + { + height: 22, + overflow: 'hidden', + minWidth: 0, + }, +]); + +export const WaveformBar = style([ + DefaultReset, + { + width: 2, + height: 3, + borderRadius: 1, + backgroundColor: color.Primary.Main, + transition: 'height 70ms ease-out', + flexShrink: 0, + }, +]); + +export const Timer = style([ + DefaultReset, + { + fontVariantNumeric: 'tabular-nums', + color: color.Critical.Main, + minWidth: config.space.S300, + flexShrink: 0, + fontWeight: 600, + }, +]); + +export const CancelHint = style([ + DefaultReset, + { + position: 'absolute', + left: 0, + top: 0, + bottom: 0, + display: 'flex', + alignItems: 'center', + paddingLeft: config.space.S200, + color: color.Critical.Main, + fontSize: toRem(12), + fontWeight: 600, + opacity: 0, + transition: 'opacity 100ms ease-out', + pointerEvents: 'none', + }, +]); + +export const CancelHintVisible = style({ + opacity: 1, +}); + +export const SrOnly = style([ + DefaultReset, + { + position: 'absolute', + width: 1, + height: 1, + padding: 0, + margin: -1, + overflow: 'hidden', + clip: 'rect(0, 0, 0, 0)', + whiteSpace: 'nowrap', + borderWidth: 0, + }, +]); diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index dd5d3bab0..7ac2e18c4 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -1,7 +1,23 @@ -import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'; +import { + forwardRef, + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, +} 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'; +import { mobileOrTablet } from '$utils/user-agent'; +import { Box, Text, IconButton, Icon, Icons } from 'folds'; +import * as css from './AudioMessageRecorder.css'; + +export type AudioRecordingCompletePayload = { + audioBlob: Blob; + waveform: number[]; + audioLength: number; +}; export type AudioMessageRecorderHandle = { stop: () => void; @@ -9,7 +25,7 @@ export type AudioMessageRecorderHandle = { }; type AudioMessageRecorderProps = { - onRecordingComplete: (audioBlob: Blob) => void; + onRecordingComplete: (payload: AudioRecordingCompletePayload) => void; onRequestClose: () => void; onWaveformUpdate: (waveform: number[]) => void; onAudioLengthUpdate: (length: number) => void; @@ -21,33 +37,20 @@ function formatTime(seconds: number): string { 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); + const [isCanceling, setIsCanceling] = useState(false); + const [isShaking, setIsShaking] = useState(false); + const [swipeX, setSwipeX] = useState(0); + const [showCancelHint, setShowCancelHint] = useState(false); + const [announcedTime, setAnnouncedTime] = useState(0); + const touchStartXRef = useRef(0); + const isSwipingRef = 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); @@ -57,24 +60,24 @@ export const AudioMessageRecorder = forwardRef< 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); + onRecordingCompleteRef.current({ + audioBlob: payload.audioFile, + waveform: payload.waveform, + audioLength: payload.audioLength, + }); 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({ + const { levels, seconds, error, handleStop, handleDelete } = useVoiceRecorder({ autoStart: true, onStop: stableOnStop, onDelete: stableOnDelete, @@ -88,75 +91,140 @@ export const AudioMessageRecorder = forwardRef< const doCancel = useCallback(() => { if (isDismissedRef.current) return; - isDismissedRef.current = true; - handleDelete(); + setIsCanceling(true); + setTimeout(() => { + isDismissedRef.current = true; + handleDelete(); + }, 180); }, [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 + useEffect(() => { + if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) { + setAnnouncedTime(seconds); + } + }, [seconds, announcedTime]); + + const CANCEL_THRESHOLD = 80; + + const handlePointerDown = useCallback((e: React.PointerEvent) => { + if (!mobileOrTablet()) return; + touchStartXRef.current = e.clientX; + isSwipingRef.current = true; + (e.target as HTMLElement).setPointerCapture(e.pointerId); + }, []); + + const handlePointerMove = useCallback((e: React.PointerEvent) => { + if (!isSwipingRef.current || !mobileOrTablet()) return; + const deltaX = e.clientX - touchStartXRef.current; + if (deltaX < 0) { + setSwipeX(Math.max(deltaX, -CANCEL_THRESHOLD - 20)); + setShowCancelHint(deltaX < -30); + } else { + setSwipeX(0); + setShowCancelHint(false); + } + }, []); + + const handlePointerUp = useCallback( + (e: React.PointerEvent) => { + if (!isSwipingRef.current || !mobileOrTablet()) return; + isSwipingRef.current = false; + (e.target as HTMLElement).releasePointerCapture(e.pointerId); + + const deltaX = e.clientX - touchStartXRef.current; + if (deltaX < -CANCEL_THRESHOLD) { + doCancel(); + } else if (deltaX < -30) { + setIsShaking(true); + setTimeout(() => setIsShaking(false), 300); + } + setSwipeX(0); + setShowCancelHint(false); + }, + [doCancel] ); - return ( - - {/* Pulsing red dot */} -
+ const BAR_COUNT = 28; + const bars = useMemo(() => { + const step = Math.max(1, levels.length / BAR_COUNT); + return Array.from( + { length: BAR_COUNT }, + (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 + ); + }, [levels]); - {/* Live waveform bars */} + const containerClassName = [ + css.Container, + isCanceling ? css.ContainerCanceling : null, + isShaking ? css.ContainerShake : null, + ] + .filter(Boolean) + .join(' '); + + return ( + <> + {error && ( + + {error} + + )} - {bars.map((level, i) => ( -
- ))} - +
- {/* Timer */} - - {formatTime(seconds)} - - + + {bars.map((level, i) => ( +
+ ))} + + + + {formatTime(seconds)} + + {announcedTime > 0 && announcedTime === seconds && ( + + Recording duration: {formatTime(announcedTime)} + + )} + + + + + + {showCancelHint && ( +
+ Release to cancel +
+ )} + + ); }); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index a531f1735..6b30f685e 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -150,6 +150,7 @@ import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice'; +import { Microphone, Stop } from '@phosphor-icons/react'; import { SchedulePickerDialog } from './schedule-send'; import * as css from './schedule-send/SchedulePickerDialog.css'; import { @@ -160,7 +161,6 @@ import { } from './msgContent'; import { CommandAutocomplete } from './CommandAutocomplete'; import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder'; -import { AudioAttachmentPreview } from './AudioAttachmentPreview'; const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => { if (!replyDraft) return {}; @@ -251,18 +251,7 @@ export const RoomInput = forwardRef( const [toolbar, setToolbar] = useSetting(settingsAtom, 'editorToolbar'); 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] = @@ -274,7 +263,7 @@ export const RoomInput = forwardRef( const [inputKey, setInputKey] = useState(0); const handleFiles = useCallback( - async (files: File[]) => { + async (files: File[], audioMeta?: { waveform: number[]; audioDuration: number }) => { setUploadBoard(true); const safeFiles = files.map(safeFile); const fileItems: TUploadItem[] = []; @@ -288,6 +277,8 @@ export const RoomInput = forwardRef( ...ef, metadata: { markedAsSpoiler: false, + waveform: audioMeta?.waveform, + audioDuration: audioMeta?.audioDuration, }, }) ); @@ -299,6 +290,8 @@ export const RoomInput = forwardRef( encInfo: undefined, metadata: { markedAsSpoiler: false, + waveform: audioMeta?.waveform, + audioDuration: audioMeta?.audioDuration, }, }) ); @@ -435,19 +428,6 @@ 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)), @@ -480,7 +460,7 @@ export const RoomInput = forwardRef( return getVideoMsgContent(mx, fileItem, upload.mxc); } if (fileItem.file.type.startsWith('audio')) { - return getAudioMsgContent(fileItem, upload.mxc, audioMsgWaveform, audioMsgLength); + return getAudioMsgContent(fileItem, upload.mxc); } return getFileMsgContent(fileItem, upload.mxc); }); @@ -744,6 +724,10 @@ export const RoomInput = forwardRef( } if (isKeyHotkey('escape', evt)) { evt.preventDefault(); + if (showAudioRecorder) { + audioRecorderRef.current?.cancel(); + return; + } if (autocompleteQuery) { setAutocompleteQuery(undefined); return; @@ -751,7 +735,15 @@ export const RoomInput = forwardRef( setReplyDraft(undefined); } }, - [submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing] + [ + submit, + roomId, + setReplyDraft, + enterForNewline, + autocompleteQuery, + isComposing, + showAudioRecorder, + ] ); const handleKeyUp: KeyboardEventHandler = useCallback( @@ -854,35 +846,18 @@ export const RoomInput = forwardRef( {Array.from(selectedFiles) .reverse() - .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 ( - - ); - })} + .map((fileItem, index) => ( + + ))} )} @@ -1108,19 +1083,22 @@ export const RoomInput = forwardRef( setShowAudioRecorder(false)} - onRecordingComplete={(audioBlob) => { - const file = new File([audioBlob], `sable-audio-message-${Date.now()}.ogg`, { - type: audioBlob.type, + onRecordingComplete={(payload) => { + const file = new File( + [payload.audioBlob], + `sable-audio-message-${Date.now()}.ogg`, + { + type: payload.audioBlob.type, + } + ); + handleFiles([file], { + waveform: payload.waveform, + audioDuration: payload.audioLength, }); - // 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)} + onAudioLengthUpdate={() => {}} + onWaveformUpdate={() => {}} /> )} @@ -1149,10 +1127,7 @@ export const RoomInput = forwardRef( // 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); - }; + let cleanup: () => void; const onUp = () => { cleanup(); const held = Date.now() - micHoldStartRef.current; @@ -1165,14 +1140,19 @@ export const RoomInput = forwardRef( cleanup(); audioRecorderRef.current?.cancel(); }; + cleanup = () => { + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onCancel); + }; window.addEventListener('pointerup', onUp); window.addEventListener('pointercancel', onCancel); }} > - + {showAudioRecorder ? ( + + ) : ( + + )} {/* ── Toolbar toggle — always visible ── */} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 5536f7d05..7da6d955a 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -148,13 +148,9 @@ export type AudioMsgContent = IContent & { audioLength?: number; }; -export const getAudioMsgContent = ( - item: TUploadItem, - mxc: string, - waveform?: number[], - audioLength?: number -): AudioMsgContent => { - const { file, encInfo } = item; +export const getAudioMsgContent = (item: TUploadItem, mxc: string): AudioMsgContent => { + const { file, encInfo, metadata } = item; + const { waveform, audioDuration, markedAsSpoiler } = metadata; const content: IContent = { msgtype: MsgType.Audio, filename: file.name, @@ -166,8 +162,8 @@ export const getAudioMsgContent = ( size: file.size, }, 'org.matrix.msc1767.audio': { - waveform: waveform?.map((v) => Math.round(v * 1024)), // scale waveform values to fit in 10 bits (0-1024) for more efficient storage, as per MSC1767 spec - duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000, // if marked as spoiler, set duration to 0 to hide it in clients that support msc1767 + waveform: waveform?.map((v) => Math.round(v * 1024)), + duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration * 1000, }, }; if (encInfo) { diff --git a/src/app/plugins/voice-recorder-kit/README.md b/src/app/plugins/voice-recorder-kit/README.md deleted file mode 100644 index 49b9edd3b..000000000 --- a/src/app/plugins/voice-recorder-kit/README.md +++ /dev/null @@ -1,492 +0,0 @@ -# react-voice-recorder-kit - -A lightweight React library for voice recording with audio waveform visualization and no UI framework dependencies - -* No UI framework dependencies (Pure React + Inline CSS) -* Animated audio waveform visualization (40 bars) -* Ready-to-use component -* Fully customizable hook -* TypeScript support -* Compatible with Next.js, Vite, CRA, and more - ---- - -## Screenshots - -### Initial State (Ready to Record) -

- Initial State -

- -### Recording in Progress -![Recording](assets/Screenshot%202025-12-05%20173347.png) - -### Paused State -![Paused](assets/Screenshot%202025-12-05%20173407.png) - -### Recorded Audio Ready to Play (Custom Styled) -![Completed Recording Custom](assets/Screenshot%202025-12-05%20173519.png) - ---- - -## Installation - -```bash -npm install react-voice-recorder-kit -# or -pnpm add react-voice-recorder-kit -# or -yarn add react-voice-recorder-kit -``` - -Requires **React 18+** - ---- - -## Quick Start (Using Component) - -```tsx -'use client' - -import { useState } from 'react' -import { VoiceRecorder } from 'react-voice-recorder-kit' - -export default function Page() { - const [file, setFile] = useState(null) - const [url, setUrl] = useState(null) - const [waveform, setWaveform] = useState([]) - const [audioLength, setAudioLength] = useState(0) - - return ( -
-

React Voice Recorder Kit

- - { - setFile(audioFile) - setUrl(audioUrl) - setWaveform(waveform) - setAudioLength(audioLength) - }} - onDelete={() => { - setFile(null) - setUrl(null) - setWaveform([]) - setAudioLength(0) - }} - /> - - {url && ( -
-
- )} -
- ) -} -``` - ---- - -## Usage in Next.js (App Router) - -```tsx -'use client' - -import { VoiceRecorder } from 'react-voice-recorder-kit' - -export default function VoicePage() { - return ( -
- -
- ) -} -``` - ---- - -## Component API - -### Main Props - -| Prop | Type | Default | Description | -| --------- | --------------------------------- | --------- | ---------------------------------------------- | -| autoStart | boolean | true | Auto-start recording on mount | -| onStop | (payload: { audioFile: Blob; audioUrl: string; waveform: number[]; audioLength: number }) => void | undefined | Callback after recording stops (all values batched) | -| onDelete | () => void | undefined | Callback after recording is deleted | -| width | string \| number | '100%' | Component width | -| height | string \| number | undefined | Component height | -| style | CSSProperties | undefined | Additional styles for container | - -### Styling Props - -| Prop | Type | Default | Description | -| --------------------------- | --------------------------------------- | ------------------------------------------------------------ | ------------------------------------ | -| backgroundColor | string | '#ffffff' | Background color | -| borderColor | string | '#e5e7eb' | Border color | -| borderRadius | string \| number | 4 | Border radius | -| padding | string \| number | '6px 10px' | Internal padding | -| gap | string \| number | 8 | Gap between elements | -| recordingIndicatorColor | string | '#ef4444' | Recording indicator color | -| idleIndicatorColor | string | '#9ca3af' | Idle indicator color | -| timeTextColor | string | undefined | Time text color | -| timeFontSize | string \| number | 12 | Time font size | -| timeFontWeight | string \| number | 500 | Time font weight | -| timeFontFamily | string | 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' | Time font family | -| visualizerBarColor | string \| (level: number, index: number) => string | '#4b5563' | Waveform bar color | -| visualizerBarWidth | number | 3 | Waveform bar width | -| visualizerBarGap | number | 4 | Gap between bars | -| visualizerBarHeight | number | 40 | Waveform bar height | -| visualizerHeight | number | 40 | Total waveform height | -| buttonSize | number | 28 | Button size | -| buttonBackgroundColor | string | '#ffffff' | Button background color | -| buttonBorderColor | string | '#e5e7eb' | Button border color | -| buttonBorderRadius | string \| number | 999 | Button border radius | -| buttonHoverBackgroundColor | string | undefined | Button hover background color | -| buttonGap | number | 4 | Gap between buttons | -| errorTextColor | string | '#dc2626' | Error text color | -| errorFontSize | string \| number | 10 | Error font size | -| errorFontFamily | string | 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' | Error font family | -| iconSize | number | 18 | Icon size | -| iconColor | string | undefined | Icon color | - -### Custom Icon Props - -| Prop | Type | Default | Description | -| --------------- | --------- | --------- | ------------------------ | -| customPlayIcon | ReactNode | undefined | Custom play icon | -| customPauseIcon | ReactNode | undefined | Custom pause icon | -| customStopIcon | ReactNode | undefined | Custom stop icon | -| customResumeIcon| ReactNode | undefined | Custom resume icon | -| customDeleteIcon| ReactNode | undefined | Custom delete icon | -| customRepeatIcon| ReactNode | undefined | Custom repeat icon | - ---- - -## Component Usage Examples - -### Example 1: Simple Usage - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function SimpleRecorder() { - return -} -``` - -### Example 2: Custom Styling - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function CustomStyledRecorder() { - return ( - - ) -} -``` - -### Example 3: Using with Callbacks - -```tsx -import { useState } from 'react' -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function RecorderWithCallbacks() { - const [audioFile, setAudioFile] = useState(null) - - return ( - { - if (audioFile instanceof File) { - console.log('Recording stopped:', audioFile.name) - } - console.log('Audio length (s):', audioLength) - console.log('Waveform points:', waveform.length) - setAudioFile(audioFile) - }} - onDelete={() => { - console.log('Recording deleted') - setAudioFile(null) - }} - /> - ) -} -``` - -### Example 4: Dynamic Color Waveform - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function DynamicColorRecorder() { - return ( - { - const hue = (level * 120).toString() - return `hsl(${hue}, 70%, 50%)` - }} - /> - ) -} -``` - ---- - -## Using the Hook (useVoiceRecorder) - -For full control over the UI, you can use the hook directly. - -### Import - -```ts -import { useVoiceRecorder } from 'react-voice-recorder-kit' -``` - -### Options - -```ts -type UseVoiceRecorderOptions = { - autoStart?: boolean - onStop?: (payload: { audioFile: Blob; audioUrl: string; waveform: number[]; audioLength: number }) => void - onDelete?: () => void -} -``` - -### Return Values - -```ts -type UseVoiceRecorderReturn = { - state: RecorderState - isRecording: boolean - isStopped: boolean - isTemporaryStopped: boolean - isPlaying: boolean - isPaused: boolean - seconds: number - levels: number[] - error: string | null - audioUrl: string | null - audioFile: File | null - waveform: number[] | null - start: () => void - handlePause: () => void - handleStopTemporary: () => void - handleStop: () => void - handleResume: () => void - handlePreviewPlay: () => void - handlePlay: () => void - handleRestart: () => void - handleDelete: () => void - handleRecordAgain: () => void -} -``` - -| Property | Type | Description | -| ----------------- | -------------- | ---------------------------------------------- | -| state | RecorderState | Current state: 'idle' \| 'recording' \| 'paused' \| 'reviewing' \| 'playing' | -| isRecording | boolean | Is currently recording | -| isStopped | boolean | Is recording stopped | -| isTemporaryStopped| boolean | Is recording temporarily stopped | -| isPlaying | boolean | Is currently playing | -| isPaused | boolean | Is recording paused | -| seconds | number | Time in seconds | -| levels | number[] | Array of 40 audio levels (0 to 1) | -| error | string \| null | Error message if any | -| audioUrl | string \| null | URL of recorded audio file | -| audioFile | File \| null | Recorded audio file | -| waveform | number[] \| null | Downsampled waveform points for the recording | -| start | () => void | Start recording | -| handlePause | () => void | Pause recording | -| handleStopTemporary| () => void | Temporary stop and review | -| handleStop | () => void | Stop and save recording | -| handleResume | () => void | Resume recording after pause | -| handlePreviewPlay | () => void | Play preview (in paused state) | -| handlePlay | () => void | Play recorded file | -| handleRestart | () => void | Restart recording | -| handleDelete | () => void | Delete recording and return to initial state | -| handleRecordAgain | () => void | Record again (same as handleRestart) | - ---- - -## Complete Hook Usage Example - -```tsx -'use client' - -import { useVoiceRecorder } from 'react-voice-recorder-kit' - -export default function CustomRecorder() { - const { - state, - isRecording, - isPaused, - isStopped, - isPlaying, - seconds, - levels, - audioUrl, - audioFile, - error, - start, - handlePause, - handleResume, - handleStop, - handlePlay, - handleDelete, - handleRestart - } = useVoiceRecorder({ autoStart: false }) - - const formatTime = (secs: number) => { - const minutes = Math.floor(secs / 60) - const sec = secs % 60 - return `${minutes}:${sec.toString().padStart(2, '0')}` - } - - return ( -
-

Custom Voice Recorder

- -
- Status: {state} | Time: {formatTime(seconds)} -
- -
- {!isRecording && !isStopped && ( - - )} - - {isRecording && !isPaused && ( - <> - - - - - )} - - {isPaused && ( - <> - - - - - )} - - {isStopped && audioUrl && ( - <> - - - - - )} -
- - {error && ( -
- {error} -
- )} - -
- {levels.map((level, index) => { - const height = 5 + level * 35 - return ( -
- ) - })} -
- - {audioUrl && ( -
-
- )} -
- ) -} -``` - ---- - -## Recording States (RecorderState) - -The component and hook have 5 different states: - -- **idle**: Initial state, ready to start -- **recording**: Currently recording -- **paused**: Recording paused (can be resumed) -- **reviewing**: Recording completed and under review -- **playing**: Playing recorded file - ---- - -## Features - -* Voice recording using MediaRecorder API -* Animated audio waveform visualization during recording and playback -* Support for pause and resume -* Support for playing recorded files -* Time display in MM:SS format -* Error handling and error message display -* Ready-to-use UI with control buttons -* Fully customizable styling and sizing -* No external dependencies -* Support for custom icons -* Dynamic color waveforms - ---- - -## Important Notes - -1. Requires microphone access in the browser -2. Recorded files are saved in WebM format -3. In paused state, you can play a preview of the recording -4. You can dynamically set bar colors using `visualizerBarColor` -5. All created URLs are automatically cleaned up - ---- - -## License - -MIT - -(orignal by Mohammadreza Fallahfaal: https://github.com/mohamad-fallah/react-voice-recorder-kit) diff --git a/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx b/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx deleted file mode 100644 index a51f634a9..000000000 --- a/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx +++ /dev/null @@ -1,620 +0,0 @@ -import type { CSSProperties } from 'react'; -import { useMemo, useRef, useEffect, useState } from 'react'; -import { useVoiceRecorder } from './useVoiceRecorder'; -import type { VoiceRecorderProps } from './types'; -import { PlayIcon, PauseIcon, StopIcon, RepeatIcon, DeleteIcon, ResumeIcon } from './icons'; - -function VoiceRecorder(props: VoiceRecorderProps) { - const { - width, - height, - style, - backgroundColor = '#ffffff', - borderColor = '#e5e7eb', - borderRadius = 4, - padding = '6px 10px', - gap = 8, - recordingIndicatorColor = '#ef4444', - idleIndicatorColor = '#9ca3af', - timeTextColor, - timeFontSize = 12, - timeFontWeight = 500, - timeFontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', - visualizerBarColor = '#4b5563', - visualizerBarWidth = 3, - visualizerBarGap = 4, - visualizerBarHeight = 40, - visualizerHeight = 40, - buttonSize = 28, - buttonBackgroundColor = '#ffffff', - buttonBorderColor = '#e5e7eb', - buttonBorderRadius = 999, - buttonHoverBackgroundColor, - buttonGap = 4, - errorTextColor = '#dc2626', - errorFontSize = 10, - errorFontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', - customPlayIcon, - customPauseIcon, - customStopIcon, - customResumeIcon, - customDeleteIcon, - customRepeatIcon, - iconSize = 18, - iconColor, - ...recorderOptions - } = props; - - const { - state, - isRecording, - isStopped, - isPlaying, - seconds, - levels, - error, - handlePause, - handleStopTemporary, - handleStop, - handleResume, - handlePreviewPlay, - handlePlay, - handleRestart, - handleDelete, - } = useVoiceRecorder(recorderOptions); - - const containerRef = useRef(null); - const [visualizerWidth, setVisualizerWidth] = useState(0); - const visualizerRef = useRef(null); - - useEffect(() => { - const updateWidth = () => { - if (visualizerRef.current) { - const availableWidth = visualizerRef.current.offsetWidth; - setVisualizerWidth(Math.max(0, availableWidth)); - } - }; - - updateWidth(); - const resizeObserver = new ResizeObserver(updateWidth); - if (visualizerRef.current) { - resizeObserver.observe(visualizerRef.current); - } - - return () => { - resizeObserver.disconnect(); - }; - }, [width, isStopped, error]); - - const formattedTime = useMemo(() => { - const minutes = Math.floor(seconds / 60); - const secs = seconds % 60; - return `${minutes}:${secs.toString().padStart(2, '0')}`; - }, [seconds]); - - const barWidth = visualizerBarWidth; - const barGap = visualizerBarGap; - - const maxBars = useMemo(() => { - if (visualizerWidth <= 0) { - return Math.max(levels.length, 40); - } - const calculatedBars = Math.floor(visualizerWidth / (barWidth + barGap)); - return Math.max(calculatedBars, 1); - }, [visualizerWidth, levels.length, barWidth, barGap]); - - const displayedLevels = useMemo(() => { - if (maxBars <= 0 || levels.length === 0) { - return Array.from({ length: Math.max(maxBars, 40) }, () => 0.15); - } - - if (maxBars <= levels.length) { - const step = levels.length / maxBars; - return Array.from({ length: maxBars }, (_, i) => { - const start = Math.floor(i * step); - const end = Math.floor((i + 1) * step); - const slice = levels.slice(start, end); - return slice.length > 0 ? Math.max(...slice) : 0.15; - }); - } - - const step = (levels.length - 1) / (maxBars - 1); - return Array.from({ length: maxBars }, (_, i) => { - const position = i * step; - const lowerIndex = Math.floor(position); - const upperIndex = Math.min(Math.ceil(position), levels.length - 1); - const fraction = position - lowerIndex; - - if (lowerIndex === upperIndex) { - return levels[lowerIndex] || 0.15; - } - - return ( - (levels[lowerIndex] || 0.15) * (1 - fraction) + (levels[upperIndex] || 0.15) * fraction - ); - }); - }, [levels, maxBars]); - - const containerStyle: CSSProperties = useMemo( - () => ({ - display: 'flex', - alignItems: 'center', - gap: typeof gap === 'number' ? `${gap}px` : gap, - backgroundColor, - borderRadius: typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius, - border: `1px solid ${borderColor}`, - padding: typeof padding === 'number' ? `${padding}px` : padding, - width: width ?? '100%', - height, - boxSizing: 'border-box', - ...style, - }), - [width, height, style, backgroundColor, borderColor, borderRadius, padding, gap] - ); - - return ( -
- - - {formattedTime} - -
- {displayedLevels.map((level) => ( - - ))} -
- - {state === 'recording' && ( -
- - - -
- )} - - {state === 'paused' && ( -
- - - - -
- )} - - {state === 'reviewing' && ( -
- - - -
- )} - - {state === 'playing' && ( -
- -
- )} - - {error && ( - - {error} - - )} -
- ); -} - -export default VoiceRecorder; diff --git a/src/app/plugins/voice-recorder-kit/icons.tsx b/src/app/plugins/voice-recorder-kit/icons.tsx deleted file mode 100644 index 29248a00a..000000000 --- a/src/app/plugins/voice-recorder-kit/icons.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import type { FC } from 'react'; - -export const PlayIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - ); -}; - -export const ResumeIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; - -export const PauseIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - ); -}; - -export const StopIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; - -export const DeleteIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - - - - ); -}; - -export const RepeatIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; diff --git a/src/app/plugins/voice-recorder-kit/index.ts b/src/app/plugins/voice-recorder-kit/index.ts index 00564f2bf..00e2e4d7e 100644 --- a/src/app/plugins/voice-recorder-kit/index.ts +++ b/src/app/plugins/voice-recorder-kit/index.ts @@ -1,9 +1,7 @@ export { useVoiceRecorder } from './useVoiceRecorder'; -export { default as VoiceRecorder } from './VoiceRecorder'; export type { UseVoiceRecorderOptions, UseVoiceRecorderReturn, RecorderState, - VoiceRecorderProps, VoiceRecorderStopPayload, } from './types'; diff --git a/src/app/plugins/voice-recorder-kit/types.ts b/src/app/plugins/voice-recorder-kit/types.ts index 42cccd271..95d428775 100644 --- a/src/app/plugins/voice-recorder-kit/types.ts +++ b/src/app/plugins/voice-recorder-kit/types.ts @@ -1,5 +1,3 @@ -import type { CSSProperties, ReactNode } from 'react'; - export type RecorderState = 'idle' | 'recording' | 'paused' | 'reviewing' | 'playing'; export type VoiceRecorderStopPayload = { @@ -39,42 +37,3 @@ export type UseVoiceRecorderReturn = { handleDelete: () => void; handleRecordAgain: () => void; }; - -export type VoiceRecorderProps = UseVoiceRecorderOptions & { - width?: string | number; - height?: string | number; - style?: CSSProperties; - backgroundColor?: string; - borderColor?: string; - borderRadius?: string | number; - padding?: string | number; - gap?: string | number; - recordingIndicatorColor?: string; - idleIndicatorColor?: string; - timeTextColor?: string; - timeFontSize?: string | number; - timeFontWeight?: string | number; - timeFontFamily?: string; - visualizerBarColor?: string | ((level: number, index: number) => string); - visualizerBarWidth?: number; - visualizerBarGap?: number; - visualizerBarHeight?: number; - visualizerHeight?: number; - buttonSize?: number; - buttonBackgroundColor?: string; - buttonBorderColor?: string; - buttonBorderRadius?: string | number; - buttonHoverBackgroundColor?: string; - buttonGap?: number; - errorTextColor?: string; - errorFontSize?: string | number; - errorFontFamily?: string; - customPlayIcon?: ReactNode; - customPauseIcon?: ReactNode; - customStopIcon?: ReactNode; - customResumeIcon?: ReactNode; - customDeleteIcon?: ReactNode; - customRepeatIcon?: ReactNode; - iconSize?: number; - iconColor?: string; -}; diff --git a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts index 454762463..1b3ea8a15 100644 --- a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts +++ b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts @@ -9,6 +9,15 @@ import type { const BAR_COUNT = 40; const WAVEFORM_POINT_COUNT = 100; +let sharedAudioContext: AudioContext | null = null; + +function getSharedAudioContext(): AudioContext { + if (!sharedAudioContext || sharedAudioContext.state === 'closed') { + sharedAudioContext = new AudioContext(); + } + return sharedAudioContext; +} + // downsample an array of samples to a target count by averaging blocks of samples together function downsampleWaveform(samples: number[], targetCount: number): number[] { if (samples.length === 0) return Array.from({ length: targetCount }, () => 0); @@ -86,7 +95,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic } frameCountRef.current = 0; if (audioContextRef.current) { - audioContextRef.current.close().catch(() => {}); + if (audioContextRef.current.state !== 'closed') { + audioContextRef.current.suspend().catch(() => {}); + } audioContextRef.current = null; } analyserRef.current = null; @@ -188,7 +199,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic const setupAudioGraph = useCallback( (stream: MediaStream) => { - const audioContext = new AudioContext(); + const audioContext = getSharedAudioContext(); audioContextRef.current = audioContext; const source = audioContext.createMediaStreamSource(stream); const analyser = audioContext.createAnalyser(); @@ -199,7 +210,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic analyserRef.current = analyser; dataArrayRef.current = dataArray; source.connect(analyser); - audioContext.resume().catch(() => {}); + if (audioContext.state === 'suspended') { + audioContext.resume().catch(() => {}); + } animateLevels(); }, [animateLevels] @@ -207,7 +220,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic const setupPlaybackGraph = useCallback( (audio: HTMLAudioElement) => { - const audioContext = new AudioContext(); + const audioContext = getSharedAudioContext(); audioContextRef.current = audioContext; const source = audioContext.createMediaElementSource(audio); const analyser = audioContext.createAnalyser(); @@ -219,7 +232,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic dataArrayRef.current = dataArray; source.connect(analyser); analyser.connect(audioContext.destination); - audioContext.resume().catch(() => {}); + if (audioContext.state === 'suspended') { + audioContext.resume().catch(() => {}); + } animateLevels(); }, [animateLevels] diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index 51c3cfaf5..4b167f220 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -9,6 +9,8 @@ import { createListAtom } from '$state/list'; export type TUploadMetadata = { markedAsSpoiler: boolean; + waveform?: number[]; + audioDuration?: number; }; export type TUploadItem = { From 7e76985ebd806d8336747e89c023a68a8e904192 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 03/31] fix: more polish on voice messages --- .../features/room/AudioMessageRecorder.css.ts | 5 ++- .../features/room/AudioMessageRecorder.tsx | 14 +------- src/app/features/room/RoomInput.tsx | 32 +++++++++++-------- 3 files changed, 21 insertions(+), 30 deletions(-) diff --git a/src/app/features/room/AudioMessageRecorder.css.ts b/src/app/features/room/AudioMessageRecorder.css.ts index 44c7bcd02..47b165841 100644 --- a/src/app/features/room/AudioMessageRecorder.css.ts +++ b/src/app/features/room/AudioMessageRecorder.css.ts @@ -22,9 +22,9 @@ const Shake = keyframes({ export const Container = style([ DefaultReset, { + flexGrow: 1, minWidth: 0, overflow: 'hidden', - padding: `0 ${config.space.S200}`, touchAction: 'pan-y', userSelect: 'none', }, @@ -86,12 +86,11 @@ export const CancelHint = style([ DefaultReset, { position: 'absolute', - left: 0, + left: config.space.S200, top: 0, bottom: 0, display: 'flex', alignItems: 'center', - paddingLeft: config.space.S200, color: color.Critical.Main, fontSize: toRem(12), fontWeight: 600, diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index 7ac2e18c4..95c130f1a 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -10,7 +10,7 @@ import { import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; import { mobileOrTablet } from '$utils/user-agent'; -import { Box, Text, IconButton, Icon, Icons } from 'folds'; +import { Box, Text } from 'folds'; import * as css from './AudioMessageRecorder.css'; export type AudioRecordingCompletePayload = { @@ -203,18 +203,6 @@ export const AudioMessageRecorder = forwardRef< )} - - - - {showCancelHint && (
( editableName="RoomInput" editor={editor} key={inputKey} - placeholder="Send a message..." + placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} onPaste={handlePaste} @@ -1065,20 +1065,21 @@ export const RoomInput = forwardRef( } before={ - pickFile('*')} - variant="SurfaceVariant" - size="300" - radii="300" - title="Upload File" - aria-label="Upload and attach a File" - > - - + !(showAudioRecorder && mobileOrTablet()) && ( + pickFile('*')} + variant="SurfaceVariant" + size="300" + radii="300" + title="Upload File" + aria-label="Upload and attach a File" + > + + + ) } after={ <> - {/* ── Recording pill: grows into available space left of mic button ── */} {showAudioRecorder && ( ( aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'} aria-pressed={showAudioRecorder} onClick={() => { - if (mobileOrTablet()) return; // mobile handled via pointerdown/up + if (mobileOrTablet() && showAudioRecorder) { + audioRecorderRef.current?.stop(); + return; + } + if (mobileOrTablet()) return; if (showAudioRecorder) { audioRecorderRef.current?.stop(); } else { @@ -1155,7 +1160,6 @@ export const RoomInput = forwardRef( )} - {/* ── Toolbar toggle — always visible ── */} Date: Tue, 17 Mar 2026 11:44:02 -0500 Subject: [PATCH 04/31] fix enter & empty messages --- .changeset/fix-empty-message.md | 5 +++ .changeset/fix-enter-autocomplete.md | 5 +++ src/app/components/message/RenderBody.tsx | 3 +- src/app/features/room/RoomInput.tsx | 51 +++++++++++++---------- 4 files changed, 42 insertions(+), 22 deletions(-) create mode 100644 .changeset/fix-empty-message.md create mode 100644 .changeset/fix-enter-autocomplete.md diff --git a/.changeset/fix-empty-message.md b/.changeset/fix-empty-message.md new file mode 100644 index 000000000..2febfa102 --- /dev/null +++ b/.changeset/fix-empty-message.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix messages with body empty but formatted body filled rendering as empty. diff --git a/.changeset/fix-enter-autocomplete.md b/.changeset/fix-enter-autocomplete.md new file mode 100644 index 000000000..c44d196b3 --- /dev/null +++ b/.changeset/fix-enter-autocomplete.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix emoticon autocomplete not respecting character threshold setting. diff --git a/src/app/components/message/RenderBody.tsx b/src/app/components/message/RenderBody.tsx index bfd3bdc5f..03714750f 100644 --- a/src/app/components/message/RenderBody.tsx +++ b/src/app/components/message/RenderBody.tsx @@ -20,11 +20,12 @@ export function RenderBody({ htmlReactParserOptions, linkifyOpts, }: Readonly) { - if (body === '') return ; if (customBody) { if (customBody === '') return ; return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions); } + if (body === '') return ; + return ( {highlightRegex diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 60ee8d20b..16b4a04ef 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -805,38 +805,47 @@ export const RoomInput = forwardRef( const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { - if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) { - evt.preventDefault(); - document - .querySelector('[data-autocomplete-menu]') - ?.dispatchEvent(new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } })); - return; - } - if (autocompleteQuery && isKeyHotkey('arrowup', evt)) { - evt.preventDefault(); - document - .querySelector('[data-autocomplete-menu]') - ?.dispatchEvent( + const autocompleteMenu = document.querySelector('[data-autocomplete-menu]'); + const isMenuVisible = !!(autocompleteQuery && autocompleteMenu); + + if (isMenuVisible) { + if (isKeyHotkey('arrowdown', evt)) { + evt.preventDefault(); + autocompleteMenu.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }) + ); + return; + } + if (isKeyHotkey('arrowup', evt)) { + evt.preventDefault(); + autocompleteMenu.dispatchEvent( new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) ); - return; + return; + } + + if (isKeyHotkey('enter', evt) && !isComposing(evt)) { + const selectedItem = + autocompleteMenu.querySelector('button[data-selected]') ?? + autocompleteMenu.querySelector('button'); + + if (selectedItem) { + evt.preventDefault(); + selectedItem.click(); + return; + } + } } + if ( (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) && !isComposing(evt) ) { evt.preventDefault(); - if (autocompleteQuery) { - const selectedItem = - document.querySelector( - '[data-autocomplete-menu] button[data-selected]' - ) ?? document.querySelector('[data-autocomplete-menu] button'); - selectedItem?.click(); - return; - } submit().catch((error) => { log.error('submit failed', { roomId }, error); }); + return; } if (isKeyHotkey('escape', evt)) { evt.preventDefault(); From 1a9f41805aee384155f7d2bf53af5bb222c0b26e Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 12:09:28 -0500 Subject: [PATCH 05/31] Update MsgTypeRenderers.tsx --- src/app/components/message/MsgTypeRenderers.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index edd1af26c..d1e2601ad 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -121,7 +121,7 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: return true; }, [trimmedBody, safeCustomBody]); - if (!body) return ; + if (!body && !customBody) return ; const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG); const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; From 2a1e4105ac69209242c812c596bd55dcbaeeeb27 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 12:41:43 -0500 Subject: [PATCH 06/31] fix images not rendering --- .changeset/fix-image-render.md | 5 +++++ .../components/message/content/ImageContent.tsx | 14 +++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .changeset/fix-image-render.md diff --git a/.changeset/fix-image-render.md b/.changeset/fix-image-render.md new file mode 100644 index 000000000..4b4aeff06 --- /dev/null +++ b/.changeset/fix-image-render.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix images without explicit dimensions not appearing. diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 92be5f9d6..11afcd600 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -65,6 +65,7 @@ export const ImageContent = as<'div', ImageContentProps>( ( { className, + style, body, mimeType, url, @@ -122,9 +123,15 @@ export const ImageContent = as<'div', ImageContentProps>( if (autoPlay) loadSrc(); }, [autoPlay, loadSrc]); + const hasDimensions = typeof info?.w === 'number' && typeof info?.h === 'number'; + return ( setIsHovered(true)} @@ -185,7 +192,12 @@ export const ImageContent = as<'div', ImageContentProps>( )} {srcState.status === AsyncStatus.Success && ( - + {renderImage({ alt: body, title: body, From 4ed7f65399958cffcccddc242e1269a57ab54e9f Mon Sep 17 00:00:00 2001 From: hazre Date: Tue, 17 Mar 2026 16:44:23 +0100 Subject: [PATCH 07/31] fix: prevent first waveform bar from being lit when audio not playing --- src/app/components/upload-card/UploadCardRenderer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index aa060835c..7ca37028c 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -226,7 +226,7 @@ function PreviewAudio({ fileItem }: PreviewAudioProps) { > {bars.map((level, i) => { const barRatio = i / BAR_COUNT; - const played = barRatio <= progress; + const played = progress > 0 && barRatio <= progress; return (
Date: Tue, 17 Mar 2026 17:45:38 +0100 Subject: [PATCH 08/31] fix: waveform algorithm --- .../upload-card/UploadCardRenderer.tsx | 20 ++++++++++++- .../features/room/AudioMessageRecorder.tsx | 28 +++++++++++++++---- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index ed77bf7ca..931215b63 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -99,8 +99,26 @@ function PreviewAudio({ fileItem }: PreviewAudioProps) { if (!waveform || waveform.length === 0) { return Array(BAR_COUNT).fill(0.3); } + if (waveform.length <= BAR_COUNT) { + const step = (waveform.length - 1) / (BAR_COUNT - 1); + return Array.from({ length: BAR_COUNT }, (_, i) => { + const position = i * step; + const lower = Math.floor(position); + const upper = Math.min(Math.ceil(position), waveform.length - 1); + const fraction = position - lower; + if (lower === upper) { + return waveform[lower] ?? 0.3; + } + return (waveform[lower] ?? 0.3) * (1 - fraction) + (waveform[upper] ?? 0.3) * fraction; + }); + } const step = waveform.length / BAR_COUNT; - return Array.from({ length: BAR_COUNT }, (_, i) => waveform[Math.floor(i * step)] ?? 0); + return Array.from({ length: BAR_COUNT }, (_, i) => { + const start = Math.floor(i * step); + const end = Math.floor((i + 1) * step); + const slice = waveform.slice(start, end); + return slice.length > 0 ? Math.max(...slice) : 0.3; + }); }, [waveform]); const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index cca7d5772..0c40dcd7f 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -150,11 +150,29 @@ export const AudioMessageRecorder = forwardRef< const BAR_COUNT = 28; const bars = useMemo(() => { - const step = Math.max(1, levels.length / BAR_COUNT); - return Array.from( - { length: BAR_COUNT }, - (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 - ); + if (levels.length === 0) { + return Array(BAR_COUNT).fill(0.15); + } + if (levels.length <= BAR_COUNT) { + const step = (levels.length - 1) / (BAR_COUNT - 1); + return Array.from({ length: BAR_COUNT }, (_, i) => { + const position = i * step; + const lower = Math.floor(position); + const upper = Math.min(Math.ceil(position), levels.length - 1); + const fraction = position - lower; + if (lower === upper) { + return levels[lower] ?? 0.15; + } + return (levels[lower] ?? 0.15) * (1 - fraction) + (levels[upper] ?? 0.15) * fraction; + }); + } + const step = levels.length / BAR_COUNT; + return Array.from({ length: BAR_COUNT }, (_, i) => { + const start = Math.floor(i * step); + const end = Math.floor((i + 1) * step); + const slice = levels.slice(start, end); + return slice.length > 0 ? Math.max(...slice) : 0.15; + }); }, [levels]); const containerClassName = [ From 35e842f7680802b369c7a2c544fb4001a75be461 Mon Sep 17 00:00:00 2001 From: hazre Date: Tue, 17 Mar 2026 18:05:35 +0100 Subject: [PATCH 09/31] fix: simplify mobile stuff --- .../features/room/AudioMessageRecorder.tsx | 74 +------------------ src/app/features/room/RoomInput.tsx | 25 +++---- .../voice-recorder-kit/useVoiceRecorder.ts | 35 +++++---- 3 files changed, 31 insertions(+), 103 deletions(-) diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index 0c40dcd7f..5ec592bc8 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -9,7 +9,6 @@ import { } from 'react'; import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; -import { mobileOrTablet } from '$utils/user-agent'; import { Box, Text } from 'folds'; import * as css from './AudioMessageRecorder.css'; @@ -45,12 +44,7 @@ export const AudioMessageRecorder = forwardRef< const isDismissedRef = useRef(false); const userRequestedStopRef = useRef(false); const [isCanceling, setIsCanceling] = useState(false); - const [isShaking, setIsShaking] = useState(false); - const [swipeX, setSwipeX] = useState(0); - const [showCancelHint, setShowCancelHint] = useState(false); const [announcedTime, setAnnouncedTime] = useState(0); - const touchStartXRef = useRef(0); - const isSwipingRef = useRef(false); const onRecordingCompleteRef = useRef(onRecordingComplete); onRecordingCompleteRef.current = onRecordingComplete; @@ -108,46 +102,6 @@ export const AudioMessageRecorder = forwardRef< } }, [seconds, announcedTime]); - const CANCEL_THRESHOLD = 80; - - const handlePointerDown = useCallback((e: React.PointerEvent) => { - if (!mobileOrTablet()) return; - touchStartXRef.current = e.clientX; - isSwipingRef.current = true; - (e.target as HTMLElement).setPointerCapture(e.pointerId); - }, []); - - const handlePointerMove = useCallback((e: React.PointerEvent) => { - if (!isSwipingRef.current || !mobileOrTablet()) return; - const deltaX = e.clientX - touchStartXRef.current; - if (deltaX < 0) { - setSwipeX(Math.max(deltaX, -CANCEL_THRESHOLD - 20)); - setShowCancelHint(deltaX < -30); - } else { - setSwipeX(0); - setShowCancelHint(false); - } - }, []); - - const handlePointerUp = useCallback( - (e: React.PointerEvent) => { - if (!isSwipingRef.current || !mobileOrTablet()) return; - isSwipingRef.current = false; - (e.target as HTMLElement).releasePointerCapture(e.pointerId); - - const deltaX = e.clientX - touchStartXRef.current; - if (deltaX < -CANCEL_THRESHOLD) { - doCancel(); - } else if (deltaX < -30) { - setIsShaking(true); - setTimeout(() => setIsShaking(false), 300); - } - setSwipeX(0); - setShowCancelHint(false); - }, - [doCancel] - ); - const BAR_COUNT = 28; const bars = useMemo(() => { if (levels.length === 0) { @@ -175,11 +129,7 @@ export const AudioMessageRecorder = forwardRef< }); }, [levels]); - const containerClassName = [ - css.Container, - isCanceling ? css.ContainerCanceling : null, - isShaking ? css.ContainerShake : null, - ] + const containerClassName = [css.Container, isCanceling ? css.ContainerCanceling : null] .filter(Boolean) .join(' '); @@ -190,17 +140,7 @@ export const AudioMessageRecorder = forwardRef< {error} )} - +
@@ -222,16 +162,6 @@ export const AudioMessageRecorder = forwardRef< Recording duration: {formatTime(announcedTime)} )} - - {showCancelHint && ( -
- Release to cancel -
- )}
); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 44747d906..099cfe5cc 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1237,10 +1237,6 @@ export const RoomInput = forwardRef( aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'} aria-pressed={showAudioRecorder} onClick={() => { - if (mobileOrTablet() && showAudioRecorder) { - audioRecorderRef.current?.stop(); - return; - } if (mobileOrTablet()) return; if (showAudioRecorder) { audioRecorderRef.current?.stop(); @@ -1250,31 +1246,30 @@ export const RoomInput = forwardRef( }} onPointerDown={() => { if (!mobileOrTablet()) return; - if (showAudioRecorder) return; // already recording — onClick will stop it + if (showAudioRecorder) return; 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. let cleanup: () => void; const onUp = () => { cleanup(); const held = Date.now() - micHoldStartRef.current; if (held >= HOLD_THRESHOLD_MS) { - audioRecorderRef.current?.stop(); + setTimeout(() => { + audioRecorderRef.current?.stop(); + }, 50); + } else { + setTimeout(() => { + audioRecorderRef.current?.cancel(); + }, 50); } - // Short tap → recorder stays open; tap stop-icon to finish - }; - const onCancel = () => { - cleanup(); - audioRecorderRef.current?.cancel(); }; cleanup = () => { window.removeEventListener('pointerup', onUp); - window.removeEventListener('pointercancel', onCancel); + window.removeEventListener('pointercancel', cleanup); }; window.addEventListener('pointerup', onUp); - window.addEventListener('pointercancel', onCancel); + window.addEventListener('pointercancel', cleanup); }} > {showAudioRecorder ? ( diff --git a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts index d0f1c2250..f73f7daf0 100644 --- a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts +++ b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts @@ -22,24 +22,27 @@ function getSharedAudioContext(): AudioContext { // downsample an array of samples to a target count by averaging blocks of samples together function downsampleWaveform(samples: number[], targetCount: number): number[] { - if (samples.length === 0) return Array.from({ length: targetCount }, () => 0); + if (samples.length === 0) return Array.from({ length: targetCount }, () => 0.15); if (samples.length <= targetCount) { - const padded = [...samples]; - while (padded.length < targetCount) padded.push(0); - return padded; + const step = (samples.length - 1) / (targetCount - 1); + return Array.from({ length: targetCount }, (_, i) => { + const position = i * step; + const lower = Math.floor(position); + const upper = Math.min(Math.ceil(position), samples.length - 1); + const fraction = position - lower; + if (lower === upper) { + return samples[lower] ?? 0.15; + } + return (samples[lower] ?? 0.15) * (1 - fraction) + (samples[upper] ?? 0.15) * fraction; + }); } - const result: number[] = []; - const blockSize = samples.length / targetCount; - for (let i = 0; i < targetCount; i += 1) { - const start = Math.floor(i * blockSize); - const end = Math.floor((i + 1) * blockSize); - let sum = 0; - for (let j = start; j < end; j += 1) { - sum += samples[j]; - } - result.push(sum / (end - start)); - } - return result; + const step = samples.length / targetCount; + return Array.from({ length: targetCount }, (_, i) => { + const start = Math.floor(i * step); + const end = Math.floor((i + 1) * step); + const slice = samples.slice(start, end); + return slice.length > 0 ? Math.max(...slice) : 0.15; + }); } export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoiceRecorderReturn { From 42351dac0361d86e734b8df3c9114b2e86df8816 Mon Sep 17 00:00:00 2001 From: hazre Date: Tue, 17 Mar 2026 18:56:10 +0100 Subject: [PATCH 10/31] docs: add changeset --- ...ecording_ui_it_should_now_feel_a_lot_more_intergrated_.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md diff --git a/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md b/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md new file mode 100644 index 000000000..eaeb76ec6 --- /dev/null +++ b/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +# Improved voice message recording UI, it should now feel a lot more integrated. From e033e36a1e8e1c0afffb8169cc4d05d1645e53aa Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:17:37 -0400 Subject: [PATCH 11/31] fix(autocomplete): Enter always selects first item; first item not highlighted Two related bugs in the mention/room/emoji autocomplete: 1. Enter key always inserted the first suggestion instead of the highlighted one. Cause: querySelector('[data-selected]') matched ALL buttons since every button has the attribute set to either 'true' or 'false'. The first button in DOM order was always returned. Fix: use '[data-selected="true"]' to select only the active item. 2. The first item had no visual highlight on initial open (the CSS rule requires data-selected='true', but the useLayoutEffect responsible for stamping that attribute only re-ran when selectedIndex changed -- not when buttons first appeared after async search results loaded). Fix: remove the dep array so the effect runs after every render; newly-loaded buttons are stamped immediately. --- src/app/components/editor/autocomplete/AutocompleteMenu.tsx | 6 ++++-- src/app/features/room/RoomInput.tsx | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 0b82001b5..def55c2f6 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -28,7 +28,9 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto } }; - // Sync data-selected to DOM; reset to index 0 when the item list changes + // Sync data-selected to DOM; reset to index 0 when the item list changes. + // No dep array — runs after every render so newly-loaded buttons are stamped + // immediately (buttons arrive async when search results load). useLayoutEffect(() => { const buttons = Array.from( itemsRef.current?.querySelectorAll('button') ?? [] @@ -46,7 +48,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto buttons.forEach((btn, i) => { btn.setAttribute('data-selected', String(i === safeIdx)); }); - }, [selectedIndex]); + }); // Listen for navigation events dispatched by the editor key handler useEffect(() => { diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index be7a468b4..840368124 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -833,7 +833,7 @@ export const RoomInput = forwardRef( if (isKeyHotkey('enter', evt) && !isComposing(evt)) { const selectedItem = - autocompleteMenu.querySelector('button[data-selected]') ?? +autocompleteMenu.querySelector('button[data-selected="true"]') ?? autocompleteMenu.querySelector('button'); if (selectedItem) { From 2a63f596fe4a129f1ce4488f65abe52bdd434720 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:20:51 -0400 Subject: [PATCH 12/31] fix(threads): thread drawer empty with classic sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With classic sync, RoomViewHeader creates Thread objects via room.createThread(id, rootEvent, [], false) — passing no initialEvents. This means thread.events starts as just [rootEvent] (or empty). Two bugs resulted: 1. The gate `if (fromThread.length > 0)` blocked the live-timeline fallback. Since thread.events = [rootEvent], length was 1 (truthy), but after filtering the root out the array was empty — yielding zero replies even though the events were present in the main room timeline. Fix: compute the filtered array first, then gate on its length so the fallback is reached when the thread object has no actual replies yet. 2. Even after #1, subsequent renders and read-receipt logic used thread.events (empty) rather than the live timeline. Fix: add a mount-time useEffect that backfills matching events from the unfiltered live timeline into the Thread object via thread.addEvents() so the authoritative source is populated for future interactions. --- src/app/features/room/ThreadDrawer.tsx | 39 ++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 00957bc34..3a9d6bb93 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -398,6 +398,33 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const rootEvent = room.findEventById(threadRootId); + // When the drawer is opened with classic sync, room.createThread() may have + // been called with empty initialEvents so thread.events only has the root. + // Backfill events from the main room timeline into the Thread object so the + // authoritative source is populated for subsequent renders and receipts. + useEffect(() => { + const thread = room.getThread(threadRootId); + if (!thread) return; + const hasRepliesInThread = thread.events.some( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (hasRepliesInThread) return; // already populated, nothing to do + + const liveEvents = room + .getUnfilteredTimelineSet() + .getLiveTimeline() + .getEvents() + .filter( + (ev) => + ev.threadRootId === threadRootId && + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) + ); + if (liveEvents.length > 0) { + thread.addEvents(liveEvents, false); + } + }, [room, threadRootId]); + // Re-render when new thread events arrive (including reactions via ThreadEvent.Update). useEffect(() => { const isEventInThread = (mEvent: MatrixEvent): boolean => { @@ -484,11 +511,19 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra // Use the Thread object if available (authoritative source with full history). // Fall back to scanning the live room timeline for local echoes and the // window before the Thread object is registered by the SDK. + // NOTE: With classic sync the Thread object is created via room.createThread() + // with empty initialEvents, so thread.events may only contain the root event. + // We must filter first, then decide whether to fall back — otherwise a thread + // whose events array consists solely of the root event (length === 1) prevents + // the live-timeline fallback from running, and the drawer shows nothing. const replyEvents: MatrixEvent[] = (() => { const thread = room.getThread(threadRootId); const fromThread = thread?.events ?? []; - if (fromThread.length > 0) { - return fromThread.filter((ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)); + const filteredFromThread = fromThread.filter( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (filteredFromThread.length > 0) { + return filteredFromThread; } return room .getUnfilteredTimelineSet() From 86bdb80816621d7edbbd1935f942cc21d140be7e Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:43:31 -0400 Subject: [PATCH 13/31] refactor+test(threads): extract getThreadReplyEvents and add unit tests Extract the replyEvents IIFE into a module-level function so the fix-first- then-check-length logic can be exercised in isolated unit tests without mounting the full component. Tests cover: - Returns thread.events (minus root) when the Thread object has replies. - Excludes reactions (RelationType.Annotation) from the results. - Classic-sync regression: thread.events = [rootEvent] => falls back to the live room timeline (the bug was that length-1 thread blocked the fallback). - Falls back to live timeline when getThread() returns null. - Filters out events belonging to a different thread. - Returns [] when neither source has relevant events. --- .changeset/fix-thread-classic-sync.md | 5 + src/app/features/room/ThreadDrawer.test.ts | 155 +++++++++++++++++++++ src/app/features/room/ThreadDrawer.tsx | 59 ++++---- 3 files changed, 191 insertions(+), 28 deletions(-) create mode 100644 .changeset/fix-thread-classic-sync.md create mode 100644 src/app/features/room/ThreadDrawer.test.ts diff --git a/.changeset/fix-thread-classic-sync.md b/.changeset/fix-thread-classic-sync.md new file mode 100644 index 000000000..bb8cda0b5 --- /dev/null +++ b/.changeset/fix-thread-classic-sync.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix thread drawer showing no messages when using classic sync. diff --git a/src/app/features/room/ThreadDrawer.test.ts b/src/app/features/room/ThreadDrawer.test.ts new file mode 100644 index 000000000..ef7863480 --- /dev/null +++ b/src/app/features/room/ThreadDrawer.test.ts @@ -0,0 +1,155 @@ +/** + * Unit tests for getThreadReplyEvents — the function that decides which events + * to display as replies in the thread drawer. + * + * The bug these tests cover (classic-sync empty thread): + * room.createThread(id, root, [], false) creates a Thread whose .events array + * contains only the root event. After filtering out the root, the old code + * checked `if (fromThread.length > 0)` on the un-filtered array — which was + * truthy — and returned an empty list instead of falling back to the live + * timeline. The fix: filter first, then check. + */ +import { describe, it, expect } from 'vitest'; +import { RelationType } from '$types/matrix-sdk'; +import { getThreadReplyEvents } from './ThreadDrawer'; + +// ── Minimal MatrixEvent factory ─────────────────────────────────────────────── + +type EventInit = { + id: string; + threadRootId?: string; + /** When set, the event is treated as a reaction/annotation */ + relType?: string; +}; + +function makeEvent({ id, threadRootId, relType }: EventInit) { + return { + getId: () => id, + threadRootId, + getRelation: () => (relType ? { rel_type: relType } : null), + getContent: () => ({}), + }; +} + +// ── Minimal Room factory ────────────────────────────────────────────────────── + +type RoomInit = { + thread?: { events: ReturnType[] } | null; + liveEvents?: ReturnType[]; +}; + +function makeRoom({ thread = null, liveEvents = [] }: RoomInit) { + return { + getThread: () => thread, + getUnfilteredTimelineSet: () => ({ + getLiveTimeline: () => ({ + getEvents: () => liveEvents, + }), + }), + }; +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +const ROOT_ID = '$root-event-id'; +const REPLY_ID = '$reply-event-id'; +const REACTION_ID = '$reaction-event-id'; + +describe('getThreadReplyEvents', () => { + it('returns thread events minus the root when the Thread object has replies', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent, replyEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('excludes reactions from thread events', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const reactionEvent = makeEvent({ + id: REACTION_ID, + threadRootId: ROOT_ID, + relType: RelationType.Annotation, + }); + + const room = makeRoom({ + thread: { events: [rootEvent, replyEvent, reactionEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + // ── Classic-sync empty-thread regression ────────────────────────────────── + + it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => { + // classic sync: thread created with no initialEvents → events = [rootEvent] + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent] as any }, + liveEvents: [liveReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + // Without the fix: `fromThread.length > 0` was truthy → returned filtered + // empty array. With the fix: filtered array is empty → falls back to live. + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('falls back to the live timeline when there is no Thread object at all', () => { + const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: null, + liveEvents: [liveReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('excludes events from the live timeline that belong to a different thread', () => { + const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' }); + const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: null, + liveEvents: [otherReply as any, ourReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('returns an empty array when neither the thread nor the live timeline has replies', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(0); + }); +}); diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 3a9d6bb93..23ef1ff0a 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -54,6 +54,36 @@ import { RoomInput } from './RoomInput'; import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing'; import * as css from './ThreadDrawer.css'; +/** + * Resolve the list of reply events to show in the thread drawer. + * + * Prefers events from the SDK Thread object (authoritative, full history) but + * falls back to scanning the main room timeline when the Thread object was + * created without `initialEvents` (as happens with classic sync). In that + * case `thread.events` contains only the root event, so filtering it yields an + * empty array — we must fall back rather than showing nothing. + * + * Exported for unit testing. + */ +export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEvent[] { + const thread = room.getThread(threadRootId); + const fromThread = thread?.events ?? []; + const filteredFromThread = fromThread.filter( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (filteredFromThread.length > 0) { + return filteredFromThread; + } + return room + .getUnfilteredTimelineSet() + .getLiveTimeline() + .getEvents() + .filter( + (ev) => + ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); +} + type ForwardedMessageProps = { isForwarded: boolean; originalTimestamp: number; @@ -508,34 +538,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra markThreadAsRead(); }, [mx, room, threadRootId, forceUpdate]); - // Use the Thread object if available (authoritative source with full history). - // Fall back to scanning the live room timeline for local echoes and the - // window before the Thread object is registered by the SDK. - // NOTE: With classic sync the Thread object is created via room.createThread() - // with empty initialEvents, so thread.events may only contain the root event. - // We must filter first, then decide whether to fall back — otherwise a thread - // whose events array consists solely of the root event (length === 1) prevents - // the live-timeline fallback from running, and the drawer shows nothing. - const replyEvents: MatrixEvent[] = (() => { - const thread = room.getThread(threadRootId); - const fromThread = thread?.events ?? []; - const filteredFromThread = fromThread.filter( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) - ); - if (filteredFromThread.length > 0) { - return filteredFromThread; - } - return room - .getUnfilteredTimelineSet() - .getLiveTimeline() - .getEvents() - .filter( - (ev) => - ev.threadRootId === threadRootId && - ev.getId() !== threadRootId && - !reactionOrEditEvent(ev) - ); - })(); + const replyEvents = getThreadReplyEvents(room, threadRootId); replyEventsRef.current = replyEvents; From cc8bad2853a089c4c9a9f11af3c7361538836007 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:21:52 -0400 Subject: [PATCH 14/31] fix(threads): reduce dead space around root message in thread drawer The root message section had two sources of excess whitespace: 1. hideTrack={false} forced a visible scrollbar gutter on the Scroll component even when the message fit within the 200px max-height and no scrolling was needed. Changed to hideTrack (default true = hidden) so the gutter only appears when actually scrollable. 2. padding: S400 0 S200 0 (16px top / 8px bottom) on the root message box was adding significant dead space above the message content that compounds with the Message component's own internal padding. Reduced to S200 0 S100 0 (8px top / 4px bottom). --- src/app/features/room/ThreadDrawer.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 00957bc34..e4bf2625b 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -722,7 +722,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra variant="Background" visibility="Hover" direction="Vertical" - hideTrack={false} + hideTrack style={{ maxHeight: '200px', height: 'fit-content', @@ -733,7 +733,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra className={css.messageList} direction="Column" style={{ - padding: `${config.space.S400} 0 ${config.space.S200} 0`, + padding: `${config.space.S200} 0 ${config.space.S100} 0`, }} > From 8dba3afe85228815a5d014b9b180ab938b54d2f0 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:43:36 -0400 Subject: [PATCH 15/31] chore(threads): add changeset for thread drawer spacing fix --- .changeset/fix-thread-ui-spacing.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-thread-ui-spacing.md diff --git a/.changeset/fix-thread-ui-spacing.md b/.changeset/fix-thread-ui-spacing.md new file mode 100644 index 000000000..445ff0823 --- /dev/null +++ b/.changeset/fix-thread-ui-spacing.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Reduce dead space around the root message in the thread drawer. From 0fb883bfaa2a99a06f7145cfb3e2edb09adae797 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:43:20 -0400 Subject: [PATCH 16/31] test(autocomplete): add tests for data-selected stamping and keyboard navigation Covers the two bugs fixed in the previous commit: - Verifies the first button gets data-selected="true" on initial render so the CSS highlight rule fires immediately (regression for the dep-array fix). - Verifies the first button is also stamped when async search results load new buttons after the initial render (the original regression). - Verifies keyboard navigation via the AUTOCOMPLETE_NAVIGATE_EVENT moves the selected index and that it clamps at the list boundaries. Also adds an eslint-disable comment in AutocompleteMenu.tsx explaining why the no-dep-array useLayoutEffect is intentional (setSelectedIndex is a stable React setter; the conditional call cannot cause an infinite loop). --- .changeset/fix-autocomplete-selection.md | 5 + .../autocomplete/AutocompleteMenu.test.tsx | 193 ++++++++++++++++++ .../editor/autocomplete/AutocompleteMenu.tsx | 3 + src/app/features/room/RoomInput.tsx | 2 +- 4 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 .changeset/fix-autocomplete-selection.md create mode 100644 src/app/components/editor/autocomplete/AutocompleteMenu.test.tsx diff --git a/.changeset/fix-autocomplete-selection.md b/.changeset/fix-autocomplete-selection.md new file mode 100644 index 000000000..6abefe185 --- /dev/null +++ b/.changeset/fix-autocomplete-selection.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix autocomplete Enter key always selecting the first item and the first item not being highlighted on open. diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.test.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.test.tsx new file mode 100644 index 000000000..f0e2fd2f2 --- /dev/null +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.test.tsx @@ -0,0 +1,193 @@ +import { type ReactNode } from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { render, act } from '@testing-library/react'; +import { + AutocompleteMenu, + AUTOCOMPLETE_NAVIGATE_EVENT, + type AutocompleteNavigateDetail, +} from './AutocompleteMenu'; + +// ── Mocks ───────────────────────────────────────────────────────────────────── + +vi.mock('focus-trap-react', () => ({ + default: ({ children }: { children: ReactNode }) => <>{children}, +})); + +vi.mock('folds', () => ({ + Header: ({ children }: { children: ReactNode }) =>
{children}
, + Menu: ({ children }: { children: ReactNode }) =>
{children}
, + Scroll: ({ children, onKeyDown }: { children: ReactNode; onKeyDown?: unknown }) => ( + // eslint-disable-next-line jsx-a11y/no-static-element-interactions +
{children}
+ ), + config: { space: { S200: '8px' } }, + Icons: {}, +})); + +vi.mock('$utils/keyboard', () => ({ + preventScrollWithArrowKey: vi.fn(), + stopPropagation: vi.fn(() => true), +})); + +vi.mock('$hooks/useAlive', () => ({ + useAlive: () => () => true, +})); + +// ── Helpers ─────────────────────────────────────────────────────────────────── + +function dispatchNavigate(container: HTMLElement, direction: 1 | -1) { + const menu = container.querySelector('[data-autocomplete-menu]'); + if (!menu) throw new Error('data-autocomplete-menu element not found'); + menu.dispatchEvent( + new CustomEvent(AUTOCOMPLETE_NAVIGATE_EVENT, { + bubbles: true, + detail: { direction }, + }) + ); +} + +function renderMenu(children: ReactNode) { + return render( + header} requestClose={() => {}}> + {children} + + ); +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +describe('AutocompleteMenu — data-selected stamping', () => { + it('stamps the first button with data-selected="true" on initial render', () => { + const { container } = renderMenu( + <> + + + + + ); + + const buttons = container.querySelectorAll('button'); + expect(buttons[0].getAttribute('data-selected')).toBe('true'); + expect(buttons[1].getAttribute('data-selected')).toBe('false'); + expect(buttons[2].getAttribute('data-selected')).toBe('false'); + }); + + it('stamps buttons when children load after initial render (async results)', async () => { + // Start with no children (empty search, buttons not yet present) + const { container, rerender } = renderMenu(null); + + // Simulate async search results arriving + await act(async () => { + rerender( + header} requestClose={() => {}}> + + + + ); + }); + + const buttons = container.querySelectorAll('button'); + expect(buttons).toHaveLength(2); + // First button must be marked selected — this was the bug: with the old + // [selectedIndex] dep array the effect didn't re-run when buttons appeared. + expect(buttons[0].getAttribute('data-selected')).toBe('true'); + expect(buttons[1].getAttribute('data-selected')).toBe('false'); + }); + + it('resets selection to the first button when the item list changes', async () => { + const { container } = renderMenu( + <> + + + + ); + + // Navigate to the second item + act(() => dispatchNavigate(container, 1)); + + const before = container.querySelectorAll('button'); + expect(before[1].getAttribute('data-selected')).toBe('true'); + + // Re-render with a completely different set of buttons (new search results) + await act(async () => { + render( + header} requestClose={() => {}}> + + + + , + { container: container.firstElementChild?.parentElement ?? document.body } + ); + }); + }); +}); + +describe('AutocompleteMenu — keyboard navigation', () => { + it('moves selection forward with direction +1', () => { + const { container } = renderMenu( + <> + + + + + ); + + act(() => dispatchNavigate(container, 1)); + + const buttons = container.querySelectorAll('button'); + expect(buttons[0].getAttribute('data-selected')).toBe('false'); + expect(buttons[1].getAttribute('data-selected')).toBe('true'); + expect(buttons[2].getAttribute('data-selected')).toBe('false'); + }); + + it('moves selection backward with direction -1', () => { + const { container } = renderMenu( + <> + + + + + ); + + // Go to last item first + act(() => dispatchNavigate(container, 1)); + act(() => dispatchNavigate(container, 1)); + + act(() => dispatchNavigate(container, -1)); + + const buttons = container.querySelectorAll('button'); + expect(buttons[0].getAttribute('data-selected')).toBe('false'); + expect(buttons[1].getAttribute('data-selected')).toBe('true'); + expect(buttons[2].getAttribute('data-selected')).toBe('false'); + }); + + it('clamps selection at the first item when navigating backward at index 0', () => { + const { container } = renderMenu( + <> + + + + ); + + act(() => dispatchNavigate(container, -1)); + + const buttons = container.querySelectorAll('button'); + expect(buttons[0].getAttribute('data-selected')).toBe('true'); + }); + + it('clamps selection at the last item when navigating forward past the end', () => { + const { container } = renderMenu( + <> + + + + ); + + act(() => dispatchNavigate(container, 1)); + act(() => dispatchNavigate(container, 1)); // attempt to go past the end + + const buttons = container.querySelectorAll('button'); + expect(buttons[0].getAttribute('data-selected')).toBe('false'); + expect(buttons[1].getAttribute('data-selected')).toBe('true'); + }); +}); diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index def55c2f6..9b907a8ac 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -31,6 +31,9 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto // Sync data-selected to DOM; reset to index 0 when the item list changes. // No dep array — runs after every render so newly-loaded buttons are stamped // immediately (buttons arrive async when search results load). + // setSelectedIndex is a stable React setter; the conditional call never + // triggers an infinite update chain (it only fires when button count changes). + // eslint-disable-next-line react-hooks/exhaustive-deps useLayoutEffect(() => { const buttons = Array.from( itemsRef.current?.querySelectorAll('button') ?? [] diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 840368124..41ef50a57 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -833,7 +833,7 @@ export const RoomInput = forwardRef( if (isKeyHotkey('enter', evt) && !isComposing(evt)) { const selectedItem = -autocompleteMenu.querySelector('button[data-selected="true"]') ?? + autocompleteMenu.querySelector('button[data-selected="true"]') ?? autocompleteMenu.querySelector('button'); if (selectedItem) { From f94d400584139e32e861d96d6296532b067c7b24 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 16:11:11 -0500 Subject: [PATCH 17/31] add tab --- .changeset/fix-autocomplete-selection.md | 2 +- src/app/features/room/RoomInput.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/fix-autocomplete-selection.md b/.changeset/fix-autocomplete-selection.md index 6abefe185..2a5ff305e 100644 --- a/.changeset/fix-autocomplete-selection.md +++ b/.changeset/fix-autocomplete-selection.md @@ -2,4 +2,4 @@ default: patch --- -Fix autocomplete Enter key always selecting the first item and the first item not being highlighted on open. +Fix autocomplete Enter & Tab key always selecting the first item and the first item not being highlighted on open. diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 41ef50a57..a79eb2beb 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -831,7 +831,7 @@ export const RoomInput = forwardRef( return; } - if (isKeyHotkey('enter', evt) && !isComposing(evt)) { + if ((isKeyHotkey('enter', evt) || isKeyHotkey('tab', evt)) && !isComposing(evt)) { const selectedItem = autocompleteMenu.querySelector('button[data-selected="true"]') ?? autocompleteMenu.querySelector('button'); From 55d27dcd5e1dc6b61e8d262a030d32e9a66d4632 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 21:41:40 +0000 Subject: [PATCH 18/31] chore: prepare release 1.9.3 --- .changeset/fix-autocomplete-selection.md | 5 ----- .changeset/fix-empty-message.md | 5 ----- .changeset/fix-enter-autocomplete.md | 5 ----- .changeset/fix-image-render.md | 5 ----- .changeset/fix-macos-casing.md | 5 ----- ..._ui_it_should_now_feel_a_lot_more_intergrated_.md | 5 ----- .changeset/sentry-opt-in-crash-reporting.md | 5 ----- CHANGELOG.md | 12 ++++++++++++ package.json | 2 +- 9 files changed, 13 insertions(+), 36 deletions(-) delete mode 100644 .changeset/fix-autocomplete-selection.md delete mode 100644 .changeset/fix-empty-message.md delete mode 100644 .changeset/fix-enter-autocomplete.md delete mode 100644 .changeset/fix-image-render.md delete mode 100644 .changeset/fix-macos-casing.md delete mode 100644 .changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md delete mode 100644 .changeset/sentry-opt-in-crash-reporting.md diff --git a/.changeset/fix-autocomplete-selection.md b/.changeset/fix-autocomplete-selection.md deleted file mode 100644 index 2a5ff305e..000000000 --- a/.changeset/fix-autocomplete-selection.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix autocomplete Enter & Tab key always selecting the first item and the first item not being highlighted on open. diff --git a/.changeset/fix-empty-message.md b/.changeset/fix-empty-message.md deleted file mode 100644 index 2febfa102..000000000 --- a/.changeset/fix-empty-message.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix messages with body empty but formatted body filled rendering as empty. diff --git a/.changeset/fix-enter-autocomplete.md b/.changeset/fix-enter-autocomplete.md deleted file mode 100644 index c44d196b3..000000000 --- a/.changeset/fix-enter-autocomplete.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix emoticon autocomplete not respecting character threshold setting. diff --git a/.changeset/fix-image-render.md b/.changeset/fix-image-render.md deleted file mode 100644 index 4b4aeff06..000000000 --- a/.changeset/fix-image-render.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix images without explicit dimensions not appearing. diff --git a/.changeset/fix-macos-casing.md b/.changeset/fix-macos-casing.md deleted file mode 100644 index 735318ab4..000000000 --- a/.changeset/fix-macos-casing.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix Mac OS to macOS in the the devices tab diff --git a/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md b/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md deleted file mode 100644 index eaeb76ec6..000000000 --- a/.changeset/improved_voice_message_recording_ui_it_should_now_feel_a_lot_more_intergrated_.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -# Improved voice message recording UI, it should now feel a lot more integrated. diff --git a/.changeset/sentry-opt-in-crash-reporting.md b/.changeset/sentry-opt-in-crash-reporting.md deleted file mode 100644 index 175ef0889..000000000 --- a/.changeset/sentry-opt-in-crash-reporting.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Add opt-in Sentry crash reporting with a consent banner. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f6792b6a..46b8a1989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Sable Client Changelog +## 1.9.3 (2026-03-17) + +### Fixes + +* Fix autocomplete Enter & Tab key always selecting the first item and the first item not being highlighted on open. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane) +* Fix messages with body empty but formatted body filled rendering as empty. ([#337](https://github.com/SableClient/Sable/pull/337) by @7w1) +* Fix emoticon autocomplete not respecting character threshold setting. ([#337](https://github.com/SableClient/Sable/pull/337) by @7w1) +* Fix images without explicit dimensions not appearing. ([#338](https://github.com/SableClient/Sable/pull/338) by @7w1) +* Fix Mac OS to macOS in the the devices tab ([#328](https://github.com/SableClient/Sable/pull/328) by @DidiDidi129) +* Improved voice message recording UI, it should now feel a lot more integrated. ([#311](https://github.com/SableClient/Sable/pull/311) by @hazre) +* Add opt-in Sentry crash reporting with a consent banner. ([#333](https://github.com/SableClient/Sable/pull/333) by @Just-Insane) + ## 1.9.2 (2026-03-17) ### Fixes diff --git a/package.json b/package.json index 9739e961c..6c52a2e05 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sable", - "version": "1.9.2", + "version": "1.9.3", "description": "An almost stable Matrix client", "type": "module", "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be", From 3f26cd9515ed99c647d3d29c3b531fbceb8b1354 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 17:56:24 -0400 Subject: [PATCH 19/31] fix: hide ThreadIndicator badge inside ThreadDrawer compose box Inside the ThreadDrawer the user is already in thread context, so showing the "Thread" badge in the reply chip is redundant and visually noisy. The compose box always sets replyDraft.relation.rel_type = RelationType.Thread when threadRootId is set (so the message goes to the right thread), but that should not make the ThreadIndicator visible there. Add !threadRootId guard to the ThreadIndicator render condition. Adds 4 unit tests covering the four branches of the condition. --- .../message/ThreadIndicator.test.tsx | 43 +++++++++++++++++++ src/app/features/room/RoomInput.tsx | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/app/components/message/ThreadIndicator.test.tsx diff --git a/src/app/components/message/ThreadIndicator.test.tsx b/src/app/components/message/ThreadIndicator.test.tsx new file mode 100644 index 000000000..d06e1f15e --- /dev/null +++ b/src/app/components/message/ThreadIndicator.test.tsx @@ -0,0 +1,43 @@ +/** + * Tests for the ThreadIndicator visibility condition in the compose strip. + * + * The indicator renders when a user is replying to a thread message from the + * main timeline (no threadRootId). It must NOT appear when composing inside + * the ThreadDrawer (threadRootId is set), because the drawer already makes the + * thread context obvious. + * + * Mirrors the exact render guard in RoomInput.tsx: + * {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && ( + * + * )} + */ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { RelationType } from '$types/matrix-sdk'; +import { ThreadIndicator } from './Reply'; + +function Subject({ relType, threadRootId }: { relType?: string; threadRootId?: string }) { + return <>{relType === RelationType.Thread && !threadRootId && }; +} + +describe('ThreadIndicator visibility in compose strip', () => { + it('renders in the main timeline compose box when a thread relation is active', () => { + render(); + expect(screen.getByText('Thread')).toBeInTheDocument(); + }); + + it('is hidden inside the ThreadDrawer when threadRootId is set', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); + + it('is hidden when the draft has no relation', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); + + it('is hidden for a non-thread relation type', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 60ee8d20b..6eec4209a 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1126,7 +1126,7 @@ export const RoomInput = forwardRef( grow="Yes" style={{ minWidth: 0 }} > - {replyDraft.relation?.rel_type === RelationType.Thread && ( + {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && ( )} Date: Tue, 17 Mar 2026 18:05:57 -0400 Subject: [PATCH 20/31] chore: add changeset --- .changeset/fix-thread-indicator-badge.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-thread-indicator-badge.md diff --git a/.changeset/fix-thread-indicator-badge.md b/.changeset/fix-thread-indicator-badge.md new file mode 100644 index 000000000..c9303ac1a --- /dev/null +++ b/.changeset/fix-thread-indicator-badge.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Hide the redundant "Thread" indicator badge in the compose box when inside the Thread Drawer. From 4b4d41f98f9072d3120cd912c59bfdebc749d954 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 18:50:59 -0500 Subject: [PATCH 21/31] Update CODEOWNERS --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 696e96793..4a7250577 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @7w1 @Just-Insane @hazre +* @7w1 @hazre From 0f14e675baf1cfea92c35434cd327d2241e8488d Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 21:15:38 -0500 Subject: [PATCH 22/31] pronoun pills for all --- .changeset/pronoun-pills.md | 5 ++ src/app/features/room/message/Message.tsx | 58 ++++++++++++++++--- .../features/settings/cosmetics/Cosmetics.tsx | 8 +++ src/app/state/settings.ts | 2 + 4 files changed, 65 insertions(+), 8 deletions(-) create mode 100644 .changeset/pronoun-pills.md diff --git a/.changeset/pronoun-pills.md b/.changeset/pronoun-pills.md new file mode 100644 index 000000000..416f3764f --- /dev/null +++ b/.changeset/pronoun-pills.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Added a setting to Appearance that attempts to convert text in names like (it/its) into a pronoun pill, enlabed by default. diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 9dd200ed5..fdd015c23 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -390,11 +390,6 @@ function MessageInternal( return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined; }, [pmp, collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]); - const displayName = useMemo( - () => pmp?.displayname || senderDisplayName, - [pmp, senderDisplayName] - ); - const cachedAvatar = useBlobCache(avatarUrl ?? undefined); // UI State @@ -423,9 +418,56 @@ function MessageInternal( const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false); const optionsRef = useRef(null); + const [showPronouns] = useSetting(settingsAtom, 'showPronouns'); + const [parsePronouns] = useSetting(settingsAtom, 'parsePronouns'); + const [useRightBubbles] = useSetting(settingsAtom, 'useRightBubbles'); + const { cleanedDisplayName, inlinePronoun } = useMemo(() => { + const rawName = pmp?.displayname || senderDisplayName || ''; + + if (!parsePronouns) { + return { cleanedDisplayName: rawName, inlinePronoun: null }; + } + + // match text like (she/her) or [he/they/them] but not (hi) + const regex = /[\(\[]?([a-zA-Z]+\/[a-zA-Z]+(?:\/[a-zA-Z]+)?)[\)\]]?/; + const match = rawName.match(regex); + + if (match) { + let strippedName = rawName.replace(match[0], '').trim(); + + if (!strippedName || strippedName === '') { + strippedName = rawName; + } + + return { + cleanedDisplayName: strippedName, + inlinePronoun: match[1].toLowerCase().slice(0, 16), + }; + } + + return { cleanedDisplayName: rawName, inlinePronoun: null }; + }, [pmp, senderDisplayName, parsePronouns]); + + const mergedPronouns = useMemo(() => { + const existing = profile.pronouns ? [...profile.pronouns] : []; + + if (inlinePronoun) { + const isDupe = existing.some((p) => p.summary?.toLowerCase() === inlinePronoun); + + if (!isDupe) { + existing.push({ + summary: inlinePronoun, + language: 'en', + }); + } + } + + return existing; + }, [profile.pronouns, inlinePronoun]); + useEffect(() => { if (!mobileOptionsOpen) return undefined; const handleClickOutside = (e: globalThis.Event) => { @@ -457,11 +499,11 @@ function MessageInternal( onClick={onUsernameClick} > - {displayName} + {cleanedDisplayName} {showPronouns && ( - + )} {tagIconSrc && } @@ -500,7 +542,7 @@ function MessageInternal( } /> diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index d1a65b6ba..f0bf1d8fc 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -165,6 +165,7 @@ function IdentityCosmetics() { 'legacyUsernameColor' ); const [showPronouns, setShowPronouns] = useSetting(settingsAtom, 'showPronouns'); + const [parsePronouns, setParsePronouns] = useSetting(settingsAtom, 'parsePronouns'); const [renderGlobalColors, setRenderGlobalColors] = useSetting( settingsAtom, 'renderGlobalNameColors' @@ -196,6 +197,13 @@ function IdentityCosmetics() { after={} /> + + } + /> + Date: Tue, 17 Mar 2026 21:23:18 -0500 Subject: [PATCH 23/31] cache things --- src/app/features/room/message/Message.tsx | 27 ++------------- src/app/utils/pronouns.ts | 42 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 25 deletions(-) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index fdd015c23..2602ab261 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -79,7 +79,7 @@ import { MessageSourceCodeItem } from '$components/message/modals/MessageSource' import { MessageForwardItem } from '$components/message/modals/MessageForward'; import { MessageDeleteItem } from '$components/message/modals/MessageDelete'; import { MessageReportItem } from '$components/message/modals/MessageReport'; -import { filterPronounsByLanguage } from '$utils/pronouns'; +import { filterPronounsByLanguage, getParsedPronouns } from '$utils/pronouns'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; import { addStickerToDefaultPack, @@ -423,32 +423,9 @@ function MessageInternal( const [parsePronouns] = useSetting(settingsAtom, 'parsePronouns'); const [useRightBubbles] = useSetting(settingsAtom, 'useRightBubbles'); - const { cleanedDisplayName, inlinePronoun } = useMemo(() => { const rawName = pmp?.displayname || senderDisplayName || ''; - - if (!parsePronouns) { - return { cleanedDisplayName: rawName, inlinePronoun: null }; - } - - // match text like (she/her) or [he/they/them] but not (hi) - const regex = /[\(\[]?([a-zA-Z]+\/[a-zA-Z]+(?:\/[a-zA-Z]+)?)[\)\]]?/; - const match = rawName.match(regex); - - if (match) { - let strippedName = rawName.replace(match[0], '').trim(); - - if (!strippedName || strippedName === '') { - strippedName = rawName; - } - - return { - cleanedDisplayName: strippedName, - inlinePronoun: match[1].toLowerCase().slice(0, 16), - }; - } - - return { cleanedDisplayName: rawName, inlinePronoun: null }; + return getParsedPronouns(rawName, parsePronouns); }, [pmp, senderDisplayName, parsePronouns]); const mergedPronouns = useMemo(() => { diff --git a/src/app/utils/pronouns.ts b/src/app/utils/pronouns.ts index c653d9fdc..6d111a2a1 100644 --- a/src/app/utils/pronouns.ts +++ b/src/app/utils/pronouns.ts @@ -63,3 +63,45 @@ export function filterPronounsByLanguage( return filteredPronouns; } + +const pronounParseCache = new Map< + string, + { cleanedDisplayName: string; inlinePronoun: string | null } +>(); + +export function getParsedPronouns(rawName: string, parseSetting: boolean) { + if (!parseSetting || !rawName) { + return { cleanedDisplayName: rawName, inlinePronoun: null }; + } + + if (pronounParseCache.has(rawName)) { + return pronounParseCache.get(rawName)!; + } + + // match text like (she/her) or [he/they/them] but not (hi) + const regex = /[([]?([a-zA-Z]+\/[a-zA-Z]+(?:\/[a-zA-Z]+)?)[)\]]?/; + const match = rawName.match(regex); + + let result: { cleanedDisplayName: string; inlinePronoun: string | null } = { + cleanedDisplayName: rawName, + inlinePronoun: null, + }; + + if (match) { + let strippedName = rawName.replace(match[0], '').trim(); + if (!strippedName || strippedName === '') { + strippedName = rawName; + } + result = { + cleanedDisplayName: strippedName, + inlinePronoun: match[1].toLowerCase().slice(0, 16), + }; + } + + if (pronounParseCache.size > 1000) { + pronounParseCache.clear(); + } + + pronounParseCache.set(rawName, result); + return result; +} From dcfafa4f5e07ecb0a62d2ab47b5e2c2b5bec7092 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 21:28:22 -0500 Subject: [PATCH 24/31] Update Message.tsx --- src/app/features/room/message/Message.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 2602ab261..7ce5adbe3 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -995,7 +995,7 @@ function MessageInternal( autoFocus value={nickDraft} onChange={(e) => setNickDraft(e.target.value)} - placeholder={displayName} + placeholder={cleanedDisplayName} onKeyDown={(e) => { if (e.key === 'Enter') { setNickname(senderId, nickDraft || undefined, mx); From 4eef3cefef48eb9151e19bb34f1dab3d99fd537a Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 17 Mar 2026 21:36:48 -0500 Subject: [PATCH 25/31] Hide presence badge in members list for users without homeserver support, mimicking room profile apperance. --- .changeset/fix-presence-badge-member-list.md | 5 +++++ src/app/features/room/MembersDrawer.tsx | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 .changeset/fix-presence-badge-member-list.md diff --git a/.changeset/fix-presence-badge-member-list.md b/.changeset/fix-presence-badge-member-list.md new file mode 100644 index 000000000..f227b478b --- /dev/null +++ b/.changeset/fix-presence-badge-member-list.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Hide presence badge in members list for users without homeserver support, mimicking room profile apperance. diff --git a/src/app/features/room/MembersDrawer.tsx b/src/app/features/room/MembersDrawer.tsx index c54d96507..1834d283c 100644 --- a/src/app/features/room/MembersDrawer.tsx +++ b/src/app/features/room/MembersDrawer.tsx @@ -155,7 +155,11 @@ function MemberItem({ }} > } + badge={ + presence && presence.lastActiveTs !== 0 ? ( + + ) : undefined + } > Date: Tue, 17 Mar 2026 21:58:31 -0500 Subject: [PATCH 26/31] add toggle for mention highlighting --- .changeset/mention-highlight-toggle.md | 5 +++++ src/app/features/room/message/Message.tsx | 7 +++++-- .../settings/notifications/SystemNotification.tsx | 15 +++++++++++++++ src/app/state/settings.ts | 2 ++ 4 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 .changeset/mention-highlight-toggle.md diff --git a/.changeset/mention-highlight-toggle.md b/.changeset/mention-highlight-toggle.md new file mode 100644 index 000000000..d2c7ddd2b --- /dev/null +++ b/.changeset/mention-highlight-toggle.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Added a toggle to notifications to disable full message mention highlighting. diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 9dd200ed5..20625d7e1 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -381,6 +381,8 @@ function MessageInternal( const profile = useUserProfile(senderId, room); const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); + const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions'); + // Avatars // Prefer the room-scoped member avatar (m.room.member) over the global profile // avatar so per-room avatar overrides are respected in the timeline. @@ -725,7 +727,7 @@ function MessageInternal( space={messageSpacing} collapse={collapse} highlight={highlight} - notifyHighlight={notifyHighlight} + notifyHighlight={highlightMentions ? notifyHighlight : undefined} selected={!!menuAnchor || !!emojiBoardAnchor} {...props} {...hoverProps} @@ -1150,6 +1152,7 @@ export const Event = as<'div', EventProps>( const [menuAnchor, setMenuAnchor] = useState(); const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false); + const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions'); const handleContextMenu: MouseEventHandler = (evt) => { if (mobileOrTablet()) { @@ -1226,7 +1229,7 @@ export const Event = as<'div', EventProps>( space={messageSpacing} autoCollapse highlight={highlight} - notifyHighlight={notifyHighlight} + notifyHighlight={highlightMentions ? notifyHighlight : undefined} selected={!!menuAnchor} {...props} {...hoverProps} diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 47266460e..c9b59549a 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -193,6 +193,7 @@ export function SystemNotification() { settingsAtom, 'faviconForMentionsOnly' ); + const [highlightMentions, setHighlightMentions] = useSetting(settingsAtom, 'highlightMentions'); // Describe what the current badge combo actually does so users aren't left guessing. const badgeBehaviourSummary = (): string => { @@ -400,6 +401,20 @@ export function SystemNotification() { after={} /> + + + } + /> + ); } diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index e9331c62f..82d111537 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -97,6 +97,7 @@ export interface Settings { saveStickerEmojiBandwidth: boolean; alwaysShowCallButton: boolean; faviconForMentionsOnly: boolean; + highlightMentions: boolean; // furry stuff renderAnimals: boolean; @@ -178,6 +179,7 @@ const defaultSettings: Settings = { saveStickerEmojiBandwidth: false, alwaysShowCallButton: false, faviconForMentionsOnly: false, + highlightMentions: true, // furry stuff renderAnimals: true, From 9c736203adbdefd57b00a522f04d9239c3b8fe3a Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 18 Mar 2026 12:56:52 -0500 Subject: [PATCH 27/31] Update ImageContent.tsx --- src/app/components/message/content/ImageContent.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 11afcd600..ad51d2a4f 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -204,7 +204,10 @@ export const ImageContent = as<'div', ImageContentProps>( src: srcState.data, onLoad: handleLoad, onError: handleError, - onClick: () => setViewer(true), + onClick: () => { + setIsHovered(false); + setViewer(true); + }, tabIndex: 0, })} From c5eb3020f59b8f31bc8a5e8b068f49d981312fd9 Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 19:35:36 +0100 Subject: [PATCH 28/31] fix stripping nickname from replies and plain mentions --- src/app/components/editor/output.ts | 71 +++++++++++++++++++++++++++-- src/app/features/room/RoomInput.tsx | 64 +++++++++++++++++++++++++- 2 files changed, 130 insertions(+), 5 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 9e3901925..383678e1a 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -17,6 +17,14 @@ export type OutputOptions = { allowTextFormatting?: boolean; allowInlineMarkdown?: boolean; allowBlockMarkdown?: boolean; + /** + * if true it will remove the nickname of the person from the message + */ + stripNickname?: boolean; + /** + * a map of regex patterns to replace nicknames with, used when stripNickname is true + */ + nickNameReplacement?: Map; }; const textToCustomHtml = (node: Text, opts: OutputOptions): string => { @@ -99,6 +107,12 @@ const ignoreHTMLParseInlineMD = (text: string): string => (txt) => parseInlineMD(txt) ).join(''); +/** + * convert slate internal representation to a custom HTML string that can be sent to the server + * @param node slate node + * @param opts options for output + * @returns custom HTML string + */ export const toMatrixCustomHTML = ( node: Descendant | Descendant[], opts: OutputOptions @@ -106,7 +120,7 @@ export const toMatrixCustomHTML = ( let markdownLines = ''; const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => { if (opts.allowBlockMarkdown && 'type' in n && n.type === BlockType.Paragraph) { - const line = toMatrixCustomHTML(n, { + let line = toMatrixCustomHTML(n, { ...opts, allowInlineMarkdown: false, allowBlockMarkdown: false, @@ -114,6 +128,13 @@ export const toMatrixCustomHTML = ( .replace(/$/, '\n') .replace(/^(\\*)>/, '$1>'); + // strip nicknames if needed + if (opts.stripNickname && opts.nickNameReplacement) { + opts.nickNameReplacement?.keys().forEach((key) => { + const replacement = opts.nickNameReplacement!.get(key) ?? ''; + line = line.replaceAll(key, replacement); + }); + } markdownLines += line; if (index === targetNodes.length - 1) { return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD); @@ -175,12 +196,37 @@ const elementToPlainText = (node: CustomElement, children: string): string => { } }; -export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean): string => { - if (Array.isArray(node)) return node.map((n) => toPlainText(n, isMarkdown)).join(''); - if (Text.isText(node)) +/** + * convert slate internal representation to a plain text string that can be sent to the server + * @param node the slate node + * @param isMarkdown set true if it's a markdown formatted text + * @param stripNickname whether to strip nicknames + * @param nickNameReplacement the nickname replacement + * @returns the plain text we want to send + */ +export const toPlainText = ( + node: Descendant | Descendant[], + isMarkdown: boolean, + stripNickname = false, + nickNameReplacement?: Map +): string => { + if (Array.isArray(node)) + return node.map((n) => toPlainText(n, isMarkdown, stripNickname, nickNameReplacement)).join(''); + if (Text.isText(node)) { + if (stripNickname && nickNameReplacement) { + let { text } = node; + nickNameReplacement?.keys().forEach((key) => { + const replacement = nickNameReplacement.get(key) ?? ''; + text = text.replaceAll(key, replacement); + }); + return isMarkdown + ? unescapeMarkdownBlockSequences(text, unescapeMarkdownInlineSequences) + : text; + } return isMarkdown ? unescapeMarkdownBlockSequences(node.text, unescapeMarkdownInlineSequences) : node.text; + } const children = node.children.map((n) => toPlainText(n, isMarkdown)).join(''); return elementToPlainText(node, children); @@ -208,10 +254,27 @@ export const trimCommand = (cmdName: string, str: string) => { return str.slice(match[0].length); }; +/** + * Type representing Mentions + */ export type MentionsData = { + /** + * a boolean to denote if it's a room mention + */ room: boolean; + /** + * a set of user ids that are mentioned in the message + */ users: Set; }; + +/** + * get the mentions in a message + * @param mx the matrix client + * @param roomId the room id we will send the message in + * @param editor the slate editor + * @returns the mentions in a message {@link MentionsData} + */ export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): MentionsData => { const mentionData: MentionsData = { room: false, diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 65e54ab9f..719a47a4a 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -254,6 +254,10 @@ export const RoomInput = forwardRef( const emojiBtnRef = useRef(null); const micBtnRef = useRef(null); const roomToParents = useAtomValue(roomToParentsAtom); + /** + * Nickname someone set for another user + * this nickname should be treated as private + */ const nicknames = useAtomValue(nicknamesAtom); const powerLevels = usePowerLevelsContext(); @@ -372,6 +376,9 @@ export const RoomInput = forwardRef( let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null; if (htmlBody) { + /** + * message with linebreaks, etc stripped + */ const strippedHtml = trimReplyFromFormattedBody(htmlBody) .replaceAll(//gi, ' ') .replaceAll(/<\/p>\s*]*>/gi, ' ') @@ -574,12 +581,65 @@ export const RoomInput = forwardRef( uploadBoardHandlers.current?.handleSend(); const commandName = getBeginCommand(editor); - let plainText = toPlainText(editor.children, isMarkdown).trim(); + /** + * a map of regex patterns to replace nicknames with, + * used when stripNickname is true in toMatrixCustomHTML + * during HTML generation for the message content. + * This is necessary because the HTML generation needs to know + * which nicknames to strip in order to generate the correct formatted_body, + * and the plain text generation needs to replace those same nicknames with + * the original user IDs so that the message content remains consistent and + * mentions are correctly processed by the server and clients. + */ + const nicknameReplacement = new Map(); + if (replyEvent) { + /** + * the id of the user being replied to, + * whose nickname (if any) should be stripped + * from the message content and replaced with their + * user ID for correct mention processing + */ + const senderId = replyEvent.getSender(); + if (senderId) { + const nick = nicknames[senderId]; + if (typeof nick === 'string' && nick.length > 0) { + nicknameReplacement.set( + new RegExp(`@?${nick}`, 'g'), + room.getMember(senderId)?.rawDisplayName ?? senderId + ); + } + } + } + /** + * any other users mentioned in the message being replied to, + * whose nicknames should also be stripped and replaced with user IDs + */ + const mentions = getMentions(mx, roomId, editor); + if (mentions?.users) { + mentions.users.forEach((id) => { + const nick = nicknames[id]; + if (typeof nick === 'string' && nick.length > 0) { + nicknameReplacement.set( + new RegExp(`@?${nick}`, 'g'), + room.getMember(id)?.rawDisplayName ?? id + ); + } + }); + } + /** + * the plain text we will send + */ + let plainText = toPlainText(editor.children, isMarkdown, true, nicknameReplacement).trim(); + /** + * the html we will send + */ let customHtml = trimCustomHtml( toMatrixCustomHTML(editor.children, { allowTextFormatting: true, allowBlockMarkdown: isMarkdown, allowInlineMarkdown: isMarkdown, + stripNickname: true, + nickNameReplacement: nicknameReplacement, }) ); let msgType = MsgType.Text; @@ -720,6 +780,7 @@ export const RoomInput = forwardRef( } }, [ editor, + replyEvent, isMarkdown, canSendReaction, mx, @@ -729,6 +790,7 @@ export const RoomInput = forwardRef( silentReply, scheduledTime, editingScheduledDelayId, + nicknames, handleQuickReact, commands, sendTypingStatus, From ce3d20b1f8a3d431984a6ee210a9c95ee0b6a923 Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 19:45:49 +0100 Subject: [PATCH 29/31] added changeset --- .changeset/fix-mentions-leaking-nicknames.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-mentions-leaking-nicknames.md diff --git a/.changeset/fix-mentions-leaking-nicknames.md b/.changeset/fix-mentions-leaking-nicknames.md new file mode 100644 index 000000000..3f4f299dc --- /dev/null +++ b/.changeset/fix-mentions-leaking-nicknames.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +fix [accidental leaking of private nicknames](https://github.com/SableClient/Sable/issues/362) for users to be included in the message From 60e8e960a6d5ee5c131c1798cfeff3f908111332 Mon Sep 17 00:00:00 2001 From: melogale Date: Wed, 18 Mar 2026 23:21:59 -0400 Subject: [PATCH 30/31] update to sable call 1.1.4 --- package.json | 4 ++-- pnpm-lock.yaml | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 6c52a2e05..1b3cb9db5 100644 --- a/package.json +++ b/package.json @@ -95,7 +95,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@sableclient/sable-call-embedded": "v1.1.3", + "@sableclient/sable-call-embedded": "v1.1.4", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", @@ -137,4 +137,4 @@ "vitest": "^4.1.0", "wrangler": "^4.70.0" } -} \ No newline at end of file +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be96be6a4..753230294 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -222,8 +222,8 @@ importers: specifier: ^6.2.2 version: 6.2.2(rollup@4.59.0) '@sableclient/sable-call-embedded': - specifier: v1.1.3 - version: 1.1.3 + specifier: v1.1.4 + version: 1.1.4 '@sentry/vite-plugin': specifier: ^5.1.1 version: 5.1.1(rollup@4.59.0) @@ -2426,8 +2426,8 @@ packages: '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@sableclient/sable-call-embedded@1.1.3': - resolution: {integrity: sha512-HNxppMEF8am6qhABbvJNc2mlkex7SntUeAMATOoNo2QkiTrutrJ9LPWy0TZskjAp++RrSpEpypKcN3MmOlZEWA==} + '@sableclient/sable-call-embedded@1.1.4': + resolution: {integrity: sha512-XLRcbUPcn7i3QKZAPjIfUkUEXP0E4DOr0dyRoVCWMjHWj28kq+T7jeB2fRr5lB77olBwNHMjIuoTwrv02xiepQ==} '@sentry-internal/browser-utils@10.43.0': resolution: {integrity: sha512-8zYTnzhAPvNkVH1Irs62wl0J/c+0QcJ62TonKnzpSFUUD3V5qz8YDZbjIDGfxy+1EB9fO0sxtddKCzwTHF/MbQ==} @@ -8119,7 +8119,7 @@ snapshots: '@rtsao/scc@1.1.0': {} - '@sableclient/sable-call-embedded@1.1.3': {} + '@sableclient/sable-call-embedded@1.1.4': {} '@sentry-internal/browser-utils@10.43.0': dependencies: From ea2c32a5c0f1543e17337cccb7cc90df550866d7 Mon Sep 17 00:00:00 2001 From: melogale Date: Wed, 18 Mar 2026 23:25:53 -0400 Subject: [PATCH 31/31] changeset --- .changeset/update_calls_to_have_rnnoise_noise_suppression.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/update_calls_to_have_rnnoise_noise_suppression.md diff --git a/.changeset/update_calls_to_have_rnnoise_noise_suppression.md b/.changeset/update_calls_to_have_rnnoise_noise_suppression.md new file mode 100644 index 000000000..ada13936e --- /dev/null +++ b/.changeset/update_calls_to_have_rnnoise_noise_suppression.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +# Update calls to have RNNoise noise suppression.