Merge remote-tracking branch 'origin/dev' into fix/sliding-sync-memory

This commit is contained in:
Evie Gauthier committed 2026-03-19 01:16:34 -04:00
commit fa4da192be
45 files changed
+1597 -1563

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fix Mac OS to macOS in the the devices tab
@@ -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
@@ -0,0 +1,5 @@
---
default: patch
---
Hide presence badge in members list for users without homeserver support, mimicking room profile apperance.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix thread drawer showing no messages when using classic sync.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Hide the redundant "Thread" indicator badge in the compose box when inside the Thread Drawer.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Reduce dead space around the root message in the thread drawer.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Added a toggle to notifications to disable full message mention highlighting.
+5
View File
@@ -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.
@@ -1,5 +0,0 @@
---
default: patch
---
Add opt-in Sentry crash reporting with a consent banner.
@@ -0,0 +1,5 @@
---
default: minor
---
# Update calls to have RNNoise noise suppression.
+1 -1
View File
@@ -1 +1 @@
* @7w1 @Just-Insane @hazre
* @7w1 @hazre
+12
View File
@@ -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
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "sable",
"version": "1.9.2",
"version": "1.9.3",
"description": "An almost stable Matrix client",
"type": "module",
"packageManager": "[email protected]+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
@@ -36,6 +36,7 @@
"@fontsource-variable/nunito": "5.2.7",
"@sentry/react": "^10.43.0",
"@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",
@@ -94,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",
@@ -136,4 +137,4 @@
"vitest": "^4.1.0",
"wrangler": "^4.70.0"
}
}
}
+20 -5
View File
@@ -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([email protected]([email protected]))([email protected])
'@sentry/react':
specifier: ^10.43.0
version: 10.43.0([email protected])
@@ -219,8 +222,8 @@ importers:
specifier: ^6.2.2
version: 6.2.2([email protected])
'@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([email protected])
@@ -1640,6 +1643,13 @@ packages:
cpu: [x64]
os: [win32]
'@phosphor-icons/[email protected]':
resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==}
engines: {node: '>=10'}
peerDependencies:
react: '>= 16.8'
react-dom: '>= 16.8'
'@pkgr/[email protected]':
resolution: {integrity: sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==}
engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}
@@ -2416,8 +2426,8 @@ packages:
'@rtsao/[email protected]':
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
'@sableclient/[email protected].3':
resolution: {integrity: sha512-HNxppMEF8am6qhABbvJNc2mlkex7SntUeAMATOoNo2QkiTrutrJ9LPWy0TZskjAp++RrSpEpypKcN3MmOlZEWA==}
'@sableclient/[email protected].4':
resolution: {integrity: sha512-XLRcbUPcn7i3QKZAPjIfUkUEXP0E4DOr0dyRoVCWMjHWj28kq+T7jeB2fRr5lB77olBwNHMjIuoTwrv02xiepQ==}
'@sentry-internal/[email protected]':
resolution: {integrity: sha512-8zYTnzhAPvNkVH1Irs62wl0J/c+0QcJ62TonKnzpSFUUD3V5qz8YDZbjIDGfxy+1EB9fO0sxtddKCzwTHF/MbQ==}
@@ -6978,6 +6988,11 @@ snapshots:
'@oxc-resolver/[email protected]':
optional: true
'@phosphor-icons/[email protected]([email protected]([email protected]))([email protected])':
dependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
'@pkgr/[email protected]': {}
'@polka/[email protected]': {}
@@ -8104,7 +8119,7 @@ snapshots:
'@rtsao/[email protected]': {}
'@sableclient/[email protected].3': {}
'@sableclient/[email protected].4': {}
'@sentry-internal/[email protected]':
dependencies:
+1
View File
@@ -1,4 +1,5 @@
allowBuilds:
'@sentry/cli': true
'@swc/core': true
esbuild: true
sharp: true
@@ -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 }) => <div>{children}</div>,
Menu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Scroll: ({ children, onKeyDown }: { children: ReactNode; onKeyDown?: unknown }) => (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div onKeyDown={onKeyDown as React.KeyboardEventHandler}>{children}</div>
),
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<AutocompleteNavigateDetail>(AUTOCOMPLETE_NAVIGATE_EVENT, {
bubbles: true,
detail: { direction },
})
);
}
function renderMenu(children: ReactNode) {
return render(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
{children}
</AutocompleteMenu>
);
}
// ── Tests ─────────────────────────────────────────────────────────────────────
describe('AutocompleteMenu — data-selected stamping', () => {
it('stamps the first button with data-selected="true" on initial render', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
const buttons = container.querySelectorAll<HTMLButtonElement>('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(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
<button type="button">Result A</button>
<button type="button">Result B</button>
</AutocompleteMenu>
);
});
const buttons = container.querySelectorAll<HTMLButtonElement>('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(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
// Navigate to the second item
act(() => dispatchNavigate(container, 1));
const before = container.querySelectorAll<HTMLButtonElement>('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(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
<button type="button">New A</button>
<button type="button">New B</button>
<button type="button">New C</button>
</AutocompleteMenu>,
{ container: container.firstElementChild?.parentElement ?? document.body }
);
});
});
});
describe('AutocompleteMenu — keyboard navigation', () => {
it('moves selection forward with direction +1', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
act(() => dispatchNavigate(container, 1));
const buttons = container.querySelectorAll<HTMLButtonElement>('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(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
// Go to last item first
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, -1));
const buttons = container.querySelectorAll<HTMLButtonElement>('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(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
act(() => dispatchNavigate(container, -1));
const buttons = container.querySelectorAll<HTMLButtonElement>('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(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, 1)); // attempt to go past the end
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('false');
expect(buttons[1].getAttribute('data-selected')).toBe('true');
});
});
@@ -28,7 +28,12 @@ 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).
// 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<HTMLButtonElement>('button') ?? []
@@ -46,7 +51,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(() => {
+67 -4
View File
@@ -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<RegExp, string>;
};
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(/<br\/>$/, '\n')
.replace(/^(\\*)&gt;/, '$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<RegExp, string>
): 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<string>;
};
/**
* 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,
@@ -121,7 +121,7 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
return true;
}, [trimmedBody, safeCustomBody]);
if (!body) return <BrokenContent body={customBody ?? body} />;
if (!body && !customBody) return <BrokenContent body={customBody ?? body} />;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
+2 -1
View File
@@ -20,11 +20,12 @@ export function RenderBody({
htmlReactParserOptions,
linkifyOpts,
}: Readonly<RenderBodyProps>) {
if (body === '') return <MessageEmptyContent />;
if (customBody) {
if (customBody === '') return <MessageEmptyContent />;
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
}
if (body === '') return <MessageEmptyContent />;
return (
<Linkify options={linkifyOpts}>
{highlightRegex
@@ -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 && (
* <ThreadIndicator />
* )}
*/
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 && <ThreadIndicator />}</>;
}
describe('ThreadIndicator visibility in compose strip', () => {
it('renders in the main timeline compose box when a thread relation is active', () => {
render(<Subject relType={RelationType.Thread} />);
expect(screen.getByText('Thread')).toBeInTheDocument();
});
it('is hidden inside the ThreadDrawer when threadRootId is set', () => {
render(<Subject relType={RelationType.Thread} threadRootId="$root:example.com" />);
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
});
it('is hidden when the draft has no relation', () => {
render(<Subject relType={undefined} />);
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
});
it('is hidden for a non-thread relation type', () => {
render(<Subject relType="m.in_reply_to" />);
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
});
});
@@ -104,34 +104,41 @@ export function AudioContent({
max={duration || 1}
values={[currentTime]}
onChange={(values) => seek(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
as="div"
variant="Secondary"
renderTrack={(params) => {
const { key, ...restProps } = params.props as any;
return (
<div key={key} {...restProps}>
{params.children}
<ProgressBar
as="div"
variant="Secondary"
size="300"
min={0}
max={duration}
value={currentTime}
radii="300"
/>
</div>
);
}}
renderThumb={(params) => {
const { key, style, ...restProps } = params.props as any;
return (
<Badge
key={key}
size="300"
min={0}
max={duration}
value={currentTime}
radii="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...restProps}
style={{
...style,
zIndex: 0,
}}
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
);
}}
/>
),
leftControl: (
@@ -174,34 +181,41 @@ export function AudioContent({
max={1}
values={[volume]}
onChange={(values) => setVolume(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
style={{ width: toRem(48) }}
variant="Secondary"
renderTrack={(params) => {
const { key, ...restProps } = params.props as any;
return (
<div key={key} {...restProps}>
{params.children}
<ProgressBar
style={{ width: toRem(48) }}
variant="Secondary"
size="300"
min={0}
max={1}
value={volume}
radii="300"
/>
</div>
);
}}
renderThumb={(params) => {
const { key, style, ...restProps } = params.props as any;
return (
<Badge
key={key}
size="300"
min={0}
max={1}
value={volume}
radii="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...restProps}
style={{
...style,
zIndex: 0,
}}
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
);
}}
/>
</>
),
@@ -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 (
<Box
className={classNames(css.RelativeBase, className)}
style={{
...(hasDimensions ? { aspectRatio: `${info.w} / ${info.h}` } : { minHeight: '150px' }),
...style,
}}
{...props}
ref={ref}
onPointerEnter={() => setIsHovered(true)}
@@ -185,14 +192,22 @@ export const ImageContent = as<'div', ImageContentProps>(
</Box>
)}
{srcState.status === AsyncStatus.Success && (
<Box className={classNames(css.AbsoluteContainer, blurred && css.Blur)}>
<Box
className={classNames(
hasDimensions ? css.AbsoluteContainer : undefined,
blurred && css.Blur
)}
>
{renderImage({
alt: body,
title: body,
src: srcState.data,
onLoad: handleLoad,
onError: handleError,
onClick: () => setViewer(true),
onClick: () => {
setIsHovered(false);
setViewer(true);
},
tabIndex: 0,
})}
</Box>
@@ -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,
},
]);
@@ -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,196 @@ function PreviewVideo({ fileItem }: Readonly<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<HTMLAudioElement | null>(null);
const rafRef = useRef<number | null>(null);
const bars = useMemo(() => {
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) => {
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;
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<HTMLDivElement>) => {
const audio = audioRef.current;
if (!audio || !duration) return;
const rect = e.currentTarget.getBoundingClientRect();
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
audio.currentTime = ratio * duration;
setCurrentTime(audio.currentTime);
};
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 (
<Box alignItems="Center" gap="200" className={css.AudioPreviewContainer}>
<IconButton
variant="Secondary"
size="400"
radii="300"
onClick={handlePlayPause}
title={isPlaying ? 'Pause' : 'Play voice message'}
aria-label={isPlaying ? 'Pause' : 'Play voice message'}
aria-pressed={isPlaying}
>
{isPlaying ? <Pause size={20} weight="fill" /> : <Play size={20} weight="fill" />}
</IconButton>
<Box
grow="Yes"
alignItems="Center"
gap="100"
onClick={handleScrubClick}
onKeyDown={handleKeyDown}
className={css.AudioWaveformContainer}
tabIndex={0}
role="slider"
aria-label="Audio position"
aria-valuemin={0}
aria-valuemax={duration}
aria-valuenow={Math.floor(currentTime)}
title="Seek"
>
{bars.map((level, i) => {
const barRatio = i / BAR_COUNT;
const played = progress > 0 && barRatio <= progress;
return (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
className={`${css.AudioWaveformBar} ${played ? css.AudioWaveformBarPlayed : css.AudioWaveformBarUnplayed}`}
style={{ height: Math.max(3, Math.round(level * 24)) }}
/>
);
})}
</Box>
<Text size="T200" className={css.AudioTimeDisplay}>
{formatAudioTime(isPlaying ? currentTime : duration)}
</Text>
</Box>
);
}
type MediaPreviewProps = {
fileItem: TUploadItem;
onSpoiler: (marked: boolean) => void;
@@ -247,6 +439,7 @@ export function UploadCardRenderer({
<PreviewVideo fileItem={fileItem} />
</MediaPreview>
)}
{fileItem.metadata.waveform && <PreviewAudio fileItem={fileItem} />}
{upload.status === UploadStatus.Idle && !fileSizeExceeded && (
<UploadCardProgress sentBytes={0} totalBytes={file.size} />
)}
@@ -0,0 +1,120 @@
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,
{
flexGrow: 1,
minWidth: 0,
overflow: 'hidden',
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: config.space.S200,
top: 0,
bottom: 0,
display: 'flex',
alignItems: 'center',
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,
},
]);
+160 -90
View File
@@ -1,98 +1,168 @@
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,
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 } from 'folds';
import * as css from './AudioMessageRecorder.css';
export type AudioRecordingCompletePayload = {
audioBlob: Blob;
waveform: number[];
audioLength: number;
audioCodec: string;
};
export type AudioMessageRecorderHandle = {
stop: () => void;
cancel: () => void;
};
type AudioMessageRecorderProps = {
onRecordingComplete: (audioBlob: Blob) => void;
onRecordingComplete: (payload: AudioRecordingCompletePayload) => void;
onRequestClose: () => void;
onWaveformUpdate: (waveform: number[]) => void;
onAudioLengthUpdate: (length: number) => void;
onAudioCodecUpdate?: (codec: string) => 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,
onAudioCodecUpdate,
}: AudioMessageRecorderProps) {
const containerRef = useRef<HTMLDivElement>(null);
const isDismissedRef = useRef(false);
// uses default styling, we use at other places
return (
<FocusTrap
focusTrapOptions={{
returnFocusOnDeactivate: false,
initialFocus: false,
onDeactivate: () => {
isDismissedRef.current = true;
onRequestClose();
},
clickOutsideDeactivates: true,
allowOutsideClick: true,
fallbackFocus: () => containerRef.current!,
}}
>
<div ref={containerRef} tabIndex={-1} style={{ outline: 'none' }}>
<Box
direction="Column"
gap="200"
alignItems="Center"
style={{
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`,
borderRadius: config.radii.R400,
boxShadow: config.shadow.E200,
padding: config.space.S400,
width: 300,
}}
>
<Text size="H4">Audio Message Recorder</Text>
<VoiceRecorder
autoStart
onStop={({
audioFile,
waveform,
audioLength,
audioCodec,
}: {
audioFile: Blob;
waveform: number[];
audioLength: number;
audioCodec: string;
}) => {
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);
// Pass the audio codec to the parent component
if (onAudioCodecUpdate) onAudioCodecUpdate(audioCodec);
}}
buttonBackgroundColor={color.SurfaceVariant.Container}
buttonHoverBackgroundColor={color.SurfaceVariant.ContainerHover}
iconColor={color.Primary.Main}
// icons for the recorder, we use Folds' icon library to keep the styling consistent with the rest of the app
customPauseIcon={<Icon src={Icons.Pause} size="200" color={color.Primary.Main} />}
customPlayIcon={<Icon src={Icons.Play} size="200" color={color.Primary.Main} />}
customDeleteIcon={<Icon src={Icons.Delete} size="200" color={color.Primary.Main} />}
customStopIcon={<Icon src={Icons.Send} size="200" color={color.Primary.Main} />}
customRepeatIcon={<Icon src={Icons.Reload} size="200" color={color.Primary.Main} />}
customResumeIcon={<Icon src={Icons.Mic} size="200" color={color.Primary.Main} />}
style={{
backgroundColor: color.Surface.ContainerActive,
}}
/>
</Box>
</div>
</FocusTrap>
);
function formatTime(seconds: number): string {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${s.toString().padStart(2, '0')}`;
}
export const AudioMessageRecorder = forwardRef<
AudioMessageRecorderHandle,
AudioMessageRecorderProps
>(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => {
const isDismissedRef = useRef(false);
const userRequestedStopRef = useRef(false);
const [isCanceling, setIsCanceling] = useState(false);
const [announcedTime, setAnnouncedTime] = useState(0);
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;
const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => {
if (!userRequestedStopRef.current) return;
if (isDismissedRef.current) return;
onRecordingCompleteRef.current({
audioBlob: payload.audioFile,
waveform: payload.waveform,
audioLength: payload.audioLength,
audioCodec: payload.audioCodec,
});
onWaveformUpdateRef.current(payload.waveform);
onAudioLengthUpdateRef.current(payload.audioLength);
}, []);
const stableOnDelete = useCallback(() => {
isDismissedRef.current = true;
onRequestCloseRef.current();
}, []);
const { levels, seconds, error, 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;
setIsCanceling(true);
setTimeout(() => {
isDismissedRef.current = true;
handleDelete();
}, 180);
}, [handleDelete]);
useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]);
useEffect(() => {
if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) {
setAnnouncedTime(seconds);
}
}, [seconds, announcedTime]);
const BAR_COUNT = 28;
const bars = useMemo(() => {
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 = [css.Container, isCanceling ? css.ContainerCanceling : null]
.filter(Boolean)
.join(' ');
return (
<>
{error && (
<Text size="T200" style={{ color: 'var(--color-critical-main)' }}>
{error}
</Text>
)}
<Box grow="Yes" alignItems="Center" gap="200" className={containerClassName}>
<div aria-hidden className={css.RecDot} />
<Box grow="Yes" alignItems="Center" gap="100" className={css.WaveformContainer}>
{bars.map((level, i) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
className={css.WaveformBar}
style={{ height: Math.max(3, Math.round(level * 20)) }}
/>
))}
</Box>
<Text size="T200" className={css.Timer} aria-live="polite" aria-atomic="true">
{formatTime(seconds)}
</Text>
{announcedTime > 0 && announcedTime === seconds && (
<span className={css.SrOnly} aria-live="polite">
Recording duration: {formatTime(announcedTime)}
</span>
)}
</Box>
</>
);
});
+5 -1
View File
@@ -155,7 +155,11 @@ function MemberItem({
}}
>
<AvatarPresence
badge={presence && <PresenceBadge presence={presence.presence} size="200" />}
badge={
presence && presence.lastActiveTs !== 0 ? (
<PresenceBadge presence={presence.presence} size="200" />
) : undefined
}
>
<Avatar size="300" radii="400">
<UserAvatar
+210 -83
View File
@@ -25,6 +25,7 @@ import { ReactEditor } from 'slate-react';
import { Editor, Point, Range, Transforms } from 'slate';
import {
Box,
color,
config,
Dialog,
Icon,
@@ -152,6 +153,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 { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
@@ -162,7 +164,7 @@ import {
getVideoMsgContent,
} from './msgContent';
import { CommandAutocomplete } from './CommandAutocomplete';
import { AudioMessageRecorder } from './AudioMessageRecorder';
import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder';
// Returns the event ID of the most recent non-reaction/non-edit event in a thread,
// falling back to the thread root if no replies exist yet.
@@ -255,6 +257,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const emojiBtnRef = useRef<HTMLButtonElement>(null);
const micBtnRef = useRef<HTMLButtonElement>(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();
@@ -285,8 +291,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [toolbar, setToolbar] = useSetting(settingsAtom, 'editorToolbar');
const [showAudioRecorder, setShowAudioRecorder] = useState(false);
const [audioMsgWaveform, setAudioMsgWaveform] = useState<number[] | undefined>(undefined);
const [audioMsgLength, setAudioMsgLength] = useState<number | undefined>(undefined);
const audioRecorderRef = useRef<AudioMessageRecorderHandle>(null);
const micHoldStartRef = useRef<number>(0);
const HOLD_THRESHOLD_MS = 400;
const [autocompleteQuery, setAutocompleteQuery] =
useState<AutocompleteQuery<AutocompletePrefix>>();
const [isQuickTextReact, setQuickTextReact] = useState(false);
@@ -296,7 +303,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
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[] = [];
@@ -310,6 +317,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
...ef,
metadata: {
markedAsSpoiler: false,
waveform: audioMeta?.waveform,
audioDuration: audioMeta?.audioDuration,
},
})
);
@@ -321,6 +330,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
encInfo: undefined,
metadata: {
markedAsSpoiler: false,
waveform: audioMeta?.waveform,
audioDuration: audioMeta?.audioDuration,
},
})
);
@@ -373,6 +384,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null;
if (htmlBody) {
/**
* message with linebreaks, etc stripped
*/
const strippedHtml = trimReplyFromFormattedBody(htmlBody)
.replaceAll(/<br\s*\/?>/gi, ' ')
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
@@ -489,7 +503,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
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);
});
@@ -561,7 +575,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
contents.map((content) =>
mx
.sendMessage(roomId, threadRootId ?? null, content as any)
.then((res) => {
.then((res: { event_id: string }) => {
debugLog.info('message', 'Uploaded file message sent', {
roomId,
eventId: res.event_id,
@@ -621,12 +635,65 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
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<RegExp, string>();
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;
@@ -759,7 +826,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
},
() => mx.sendMessage(roomId, threadRootId ?? null, content as any)
)
.then((res) => {
.then((res: { event_id: string }) => {
debugLog.info('message', 'Message sent successfully', {
roomId,
eventId: res.event_id,
@@ -783,6 +850,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
}, [
editor,
replyEvent,
isMarkdown,
canSendReaction,
mx,
@@ -792,6 +860,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
silentReply,
scheduledTime,
editingScheduledDelayId,
nicknames,
handleQuickReact,
commands,
sendTypingStatus,
@@ -805,41 +874,54 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
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) || isKeyHotkey('tab', evt)) && !isComposing(evt)) {
const selectedItem =
autocompleteMenu.querySelector<HTMLButtonElement>('button[data-selected="true"]') ??
autocompleteMenu.querySelector<HTMLButtonElement>('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<HTMLButtonElement>(
'[data-autocomplete-menu] button[data-selected]'
) ?? document.querySelector<HTMLButtonElement>('[data-autocomplete-menu] button');
selectedItem?.click();
return;
}
submit().catch((error) => {
log.error('submit failed', { roomId }, error);
});
return;
}
if (isKeyHotkey('escape', evt)) {
evt.preventDefault();
if (showAudioRecorder) {
audioRecorderRef.current?.cancel();
return;
}
if (autocompleteQuery) {
setAutocompleteQuery(undefined);
return;
@@ -847,7 +929,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
}
},
[submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing]
[
submit,
roomId,
setReplyDraft,
enterForNewline,
autocompleteQuery,
isComposing,
showAudioRecorder,
]
);
const handleKeyUp: KeyboardEventHandler = useCallback(
@@ -1049,7 +1139,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
editableName="RoomInput"
editor={editor}
key={inputKey}
placeholder="Send a message..."
placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onPaste={handlePaste}
@@ -1126,7 +1216,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
grow="Yes"
style={{ minWidth: 0 }}
>
{replyDraft.relation?.rel_type === RelationType.Thread && (
{replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && (
<ThreadIndicator />
)}
<ReplyLayout
@@ -1169,19 +1259,97 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
</>
}
before={
<IconButton
onClick={() => pickFile('*')}
variant="SurfaceVariant"
size="300"
radii="300"
title="Upload File"
aria-label="Upload and attach a File"
>
<Icon src={Icons.PlusCircle} />
</IconButton>
!(showAudioRecorder && mobileOrTablet()) && (
<IconButton
onClick={() => pickFile('*')}
variant="SurfaceVariant"
size="300"
radii="300"
title="Upload File"
aria-label="Upload and attach a File"
>
<Icon src={Icons.PlusCircle} />
</IconButton>
)
}
after={
<>
{showAudioRecorder && (
<AudioMessageRecorder
ref={audioRecorderRef}
onRequestClose={() => setShowAudioRecorder(false)}
onRecordingComplete={(payload) => {
const extension = getSupportedAudioExtension(payload.audioCodec);
const file = new File(
[payload.audioBlob],
`sable-audio-message-${Date.now()}.${extension}`,
{
type: payload.audioCodec,
}
);
handleFiles([file], {
waveform: payload.waveform,
audioDuration: payload.audioLength,
});
setShowAudioRecorder(false);
}}
onAudioLengthUpdate={() => {}}
onWaveformUpdate={() => {}}
/>
)}
{/* ── Mic button — always present; icon swaps to Stop while recording ── */}
<IconButton
ref={micBtnRef}
variant={showAudioRecorder ? 'Critical' : 'SurfaceVariant'}
size="300"
radii="300"
title={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-pressed={showAudioRecorder}
onClick={() => {
if (mobileOrTablet()) return;
if (showAudioRecorder) {
audioRecorderRef.current?.stop();
} else {
setShowAudioRecorder(true);
}
}}
onPointerDown={() => {
if (!mobileOrTablet()) return;
if (showAudioRecorder) return;
micHoldStartRef.current = Date.now();
setShowAudioRecorder(true);
let cleanup: () => void;
const onUp = () => {
cleanup();
const held = Date.now() - micHoldStartRef.current;
if (held >= HOLD_THRESHOLD_MS) {
setTimeout(() => {
audioRecorderRef.current?.stop();
}, 50);
} else {
setTimeout(() => {
audioRecorderRef.current?.cancel();
}, 50);
}
};
cleanup = () => {
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', cleanup);
};
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', cleanup);
}}
>
{showAudioRecorder ? (
<Stop size={20} weight="fill" style={{ color: color.Critical.Main }} />
) : (
<Microphone size={20} />
)}
</IconButton>
<IconButton
variant="SurfaceVariant"
size="300"
@@ -1193,47 +1361,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
>
<Icon src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<IconButton
ref={micBtnRef}
variant="SurfaceVariant"
size="300"
radii="300"
title="record audio message"
aria-pressed={showAudioRecorder}
onClick={() => setShowAudioRecorder(!showAudioRecorder)}
>
<Icon src={Icons.Mic} />
</IconButton>
{showAudioRecorder && (
<PopOut
anchor={micBtnRef.current?.getBoundingClientRect() ?? undefined}
offset={8}
position="Top"
align="End"
alignOffset={-44}
content={
<AudioMessageRecorder
onRequestClose={() => {
setShowAudioRecorder(false);
}}
onRecordingComplete={(audioBlob) => {
const file = new File(
[audioBlob],
`sable-audio-message-${Date.now()}.${getSupportedAudioExtension(audioBlob.type)}`,
{
type: audioBlob.type,
}
);
handleFiles([file]);
// Close the recorder after handling the file, to give some feedback that the recording was successful
setShowAudioRecorder(false);
}}
onAudioLengthUpdate={(len) => setAudioMsgLength(len)}
onWaveformUpdate={(w) => setAudioMsgWaveform(w)}
/>
}
/>
)}
<UseStateProvider initial={undefined}>
{(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => (
<PopOut
+155
View File
@@ -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<typeof makeEvent>[] } | null;
liveEvents?: ReturnType<typeof makeEvent>[];
};
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);
});
});
+60 -22
View File
@@ -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;
@@ -398,6 +428,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 => {
@@ -481,26 +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.
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));
}
return room
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(
(ev) =>
ev.threadRootId === threadRootId &&
ev.getId() !== threadRootId &&
!reactionOrEditEvent(ev)
);
})();
const replyEvents = getThreadReplyEvents(room, threadRootId);
replyEventsRef.current = replyEvents;
@@ -722,7 +760,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 +771,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`,
}}
>
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
+34 -12
View File
@@ -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,
@@ -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.
@@ -390,11 +392,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,8 +420,32 @@ function MessageInternal(
const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false);
const optionsRef = useRef<HTMLDivElement>(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 || '';
return getParsedPronouns(rawName, parsePronouns);
}, [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;
@@ -457,11 +478,11 @@ function MessageInternal(
onClick={onUsernameClick}
>
<Text as="span" size={messageLayout === MessageLayout.Bubble ? 'T300' : 'T400'} truncate>
<UsernameBold>{displayName}</UsernameBold>
<UsernameBold>{cleanedDisplayName}</UsernameBold>
</Text>
</Username>
{showPronouns && (
<Pronouns pronouns={profile.pronouns} tagColor={usernameColor ?? 'currentColor'} />
<Pronouns pronouns={mergedPronouns} tagColor={usernameColor ?? 'currentColor'} />
)}
{tagIconSrc && <PowerIcon size="100" iconSrc={tagIconSrc} />}
</Box>
@@ -500,7 +521,7 @@ function MessageInternal(
<UserAvatar
userId={senderId}
src={cachedAvatar}
alt={displayName}
alt={cleanedDisplayName}
renderFallback={() => <Icon size="200" src={Icons.User} filled />}
/>
</Avatar>
@@ -725,7 +746,7 @@ function MessageInternal(
space={messageSpacing}
collapse={collapse}
highlight={highlight}
notifyHighlight={notifyHighlight}
notifyHighlight={highlightMentions ? notifyHighlight : undefined}
selected={!!menuAnchor || !!emojiBoardAnchor}
{...props}
{...hoverProps}
@@ -976,7 +997,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);
@@ -1150,6 +1171,7 @@ export const Event = as<'div', EventProps>(
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false);
const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions');
const handleContextMenu: MouseEventHandler<HTMLDivElement> = (evt) => {
if (mobileOrTablet()) {
@@ -1226,7 +1248,7 @@ export const Event = as<'div', EventProps>(
space={messageSpacing}
autoCollapse
highlight={highlight}
notifyHighlight={notifyHighlight}
notifyHighlight={highlightMentions ? notifyHighlight : undefined}
selected={!!menuAnchor}
{...props}
{...hoverProps}
+7 -11
View File
@@ -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;
let content: IContent = {
msgtype: MsgType.Audio,
filename: file.name,
@@ -164,17 +160,17 @@ export const getAudioMsgContent = (
info: {
mimetype: file.type,
size: file.size,
duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000,
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration * 1000,
},
// Element-compatible unstable extensible-event keys
'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,
},
'org.matrix.msc1767.text': item.body && item.body.length > 0 ? item.body : 'a voice message',
'org.matrix.msc3245.voice.v2': {
duration: !audioLength ? 0 : audioLength,
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration,
waveform: waveform?.map((v) => Math.round(v * 1024)),
},
// for element compat
@@ -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={<Switch variant="Primary" value={showPronouns} onChange={setShowPronouns} />}
/>
</SequenceCard>
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Pronoun Pills for All"
description="Attempts to convert pronouns in names into pills (e.g. [they/them] or (it/its) turns into a pill)."
after={<Switch variant="Primary" value={parsePronouns} onChange={setParsePronouns} />}
/>
</SequenceCard>
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Render Global Username Colors"
@@ -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={<Switch variant="Primary" value={showPingCounts} onChange={setShowPingCounts} />}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Highlight Mentions"
description="Highlight the full background message when it contains a mention/keyword."
after={
<Switch variant="Primary" value={highlightMentions} onChange={setHighlightMentions} />
}
/>
</SequenceCard>
</Box>
);
}
@@ -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)
<p align="center">
<img src="assets/Screenshot%202025-12-05%20173340.png" alt="Initial State" width="600"/>
</p>
### 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<Blob | null>(null)
const [url, setUrl] = useState<string | null>(null)
const [waveform, setWaveform] = useState<number[]>([])
const [audioLength, setAudioLength] = useState(0)
return (
<div style={{ padding: 20, maxWidth: 600, margin: '0 auto' }}>
<h1>React Voice Recorder Kit</h1>
<VoiceRecorder
autoStart={false}
onStop={({ audioFile, audioUrl, waveform, audioLength }) => {
setFile(audioFile)
setUrl(audioUrl)
setWaveform(waveform)
setAudioLength(audioLength)
}}
onDelete={() => {
setFile(null)
setUrl(null)
setWaveform([])
setAudioLength(0)
}}
/>
{url && (
<div style={{ marginTop: 16 }}>
<audio controls src={url} style={{ width: '100%' }} />
{file instanceof File && (
<p style={{ fontSize: 12, marginTop: 8 }}>
File name: {file.name} | Size: {file.size} bytes
</p>
)}
<p style={{ fontSize: 12, marginTop: 8 }}>
Length: {audioLength}s | Waveform points: {waveform.length}
</p>
</div>
)}
</div>
)
}
```
---
## Usage in Next.js (App Router)
```tsx
'use client'
import { VoiceRecorder } from 'react-voice-recorder-kit'
export default function VoicePage() {
return (
<div style={{ padding: 24 }}>
<VoiceRecorder autoStart={true} />
</div>
)
}
```
---
## 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 <VoiceRecorder />
}
```
### Example 2: Custom Styling
```tsx
import { VoiceRecorder } from 'react-voice-recorder-kit'
function CustomStyledRecorder() {
return (
<VoiceRecorder
backgroundColor="#f3f4f6"
borderColor="#d1d5db"
borderRadius={12}
recordingIndicatorColor="#10b981"
visualizerBarColor="#6366f1"
buttonBackgroundColor="#ffffff"
buttonHoverBackgroundColor="#f9fafb"
/>
)
}
```
### Example 3: Using with Callbacks
```tsx
import { useState } from 'react'
import { VoiceRecorder } from 'react-voice-recorder-kit'
function RecorderWithCallbacks() {
const [audioFile, setAudioFile] = useState<Blob | null>(null)
return (
<VoiceRecorder
autoStart={false}
onStop={({ audioFile, waveform, audioLength }) => {
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 (
<VoiceRecorder
visualizerBarColor={(level, index) => {
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 (
<div style={{ padding: 16, maxWidth: 600 }}>
<h2>Custom Voice Recorder</h2>
<div style={{ marginBottom: 8 }}>
Status: {state} | Time: {formatTime(seconds)}
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{!isRecording && !isStopped && (
<button onClick={start}>Start</button>
)}
{isRecording && !isPaused && (
<>
<button onClick={handlePause}>Pause</button>
<button onClick={handleStop}>Stop & Save</button>
<button onClick={handleRestart}>Restart</button>
</>
)}
{isPaused && (
<>
<button onClick={handleResume}>Resume</button>
<button onClick={handleRestart}>Restart</button>
<button onClick={handleStop}>Stop & Save</button>
</>
)}
{isStopped && audioUrl && (
<>
<button onClick={handlePlay}>
{isPlaying ? 'Stop Playback' : 'Play'}
</button>
<button onClick={handleDelete}>Delete</button>
<button onClick={handleRestart}>Record Again</button>
</>
)}
</div>
{error && (
<div style={{ color: 'red', marginTop: 8 }}>
{error}
</div>
)}
<div
style={{
marginTop: 20,
height: 40,
display: 'flex',
alignItems: 'flex-end',
gap: 4,
overflow: 'hidden'
}}
>
{levels.map((level, index) => {
const height = 5 + level * 35
return (
<div
key={index}
style={{
width: 4,
height,
borderRadius: 4,
background: '#444'
}}
/>
)
})}
</div>
{audioUrl && (
<div style={{ marginTop: 16 }}>
<audio controls src={audioUrl} style={{ width: '100%' }} />
</div>
)}
</div>
)
}
```
---
## 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)
@@ -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<HTMLDivElement>(null);
const [visualizerWidth, setVisualizerWidth] = useState(0);
const visualizerRef = useRef<HTMLDivElement>(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 (
<div ref={containerRef} style={containerStyle}>
<span
style={{
width: 8,
height: 8,
borderRadius: 9999,
backgroundColor: isRecording ? recordingIndicatorColor : idleIndicatorColor,
}}
/>
<span
style={{
fontSize: typeof timeFontSize === 'number' ? `${timeFontSize}px` : timeFontSize,
fontWeight: timeFontWeight,
minWidth: 40,
fontFamily: timeFontFamily,
color: timeTextColor,
}}
>
{formattedTime}
</span>
<div
ref={visualizerRef}
style={{
flex: 1,
display: 'flex',
alignItems: 'center',
gap: barGap,
overflow: 'hidden',
height: visualizerHeight,
minWidth: 0,
justifyContent: 'flex-start',
}}
>
{displayedLevels.map((level) => (
<span
key={Math.random()}
style={{
width: barWidth,
borderRadius: 999,
backgroundColor:
typeof visualizerBarColor === 'function'
? visualizerBarColor(level, displayedLevels.indexOf(level))
: visualizerBarColor,
height: 1 + Math.max(0.1, Math.min(level, 1)) * (visualizerBarHeight - 1),
flexShrink: 0,
}}
/>
))}
</div>
{state === 'recording' && (
<div style={{ display: 'flex', gap: buttonGap, marginLeft: 8 }}>
<button
type="button"
onClick={handlePause}
title="Pause recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customPauseIcon || <PauseIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleStopTemporary}
title="Stop & Review"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customStopIcon || <StopIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleRestart}
title="Restart recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customRepeatIcon || <RepeatIcon size={iconSize} />}
</button>
</div>
)}
{state === 'paused' && (
<div style={{ display: 'flex', gap: buttonGap, marginLeft: 8 }}>
<button
type="button"
onClick={handleResume}
title="Resume recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customResumeIcon || <ResumeIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handlePreviewPlay}
title="Play preview"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{isPlaying
? customPauseIcon || <PauseIcon size={iconSize} />
: customPlayIcon || <PlayIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleRestart}
title="Restart recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customRepeatIcon || <RepeatIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleStop}
title="Stop & Save"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customStopIcon || <StopIcon size={iconSize} />}
</button>
</div>
)}
{state === 'reviewing' && (
<div style={{ display: 'flex', gap: buttonGap, marginLeft: 8 }}>
<button
type="button"
onClick={isPlaying ? handlePause : handlePlay}
title={isPlaying ? 'Pause playback' : 'Play'}
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{isPlaying
? customPauseIcon || <PauseIcon size={iconSize} />
: customPlayIcon || <PlayIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleDelete}
title="Delete recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customDeleteIcon || <DeleteIcon size={iconSize} />}
</button>
<button
type="button"
onClick={handleRestart}
title="Restart recording"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customRepeatIcon || <RepeatIcon size={iconSize} />}
</button>
</div>
)}
{state === 'playing' && (
<div style={{ display: 'flex', gap: buttonGap, marginLeft: 8 }}>
<button
type="button"
onClick={handlePause}
title="Pause playback"
style={{
width: buttonSize,
height: buttonSize,
borderRadius:
typeof buttonBorderRadius === 'number'
? `${buttonBorderRadius}px`
: buttonBorderRadius,
border: `1px solid ${buttonBorderColor}`,
backgroundColor: buttonBackgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
cursor: 'pointer',
color: iconColor,
transition: buttonHoverBackgroundColor ? 'background-color 0.2s' : undefined,
}}
onMouseEnter={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonHoverBackgroundColor;
}
}}
onMouseLeave={(e) => {
if (buttonHoverBackgroundColor) {
e.currentTarget.style.backgroundColor = buttonBackgroundColor;
}
}}
>
{customPauseIcon || <PauseIcon size={iconSize} />}
</button>
</div>
)}
{error && (
<span
style={{
color: errorTextColor,
fontSize: typeof errorFontSize === 'number' ? `${errorFontSize}px` : errorFontSize,
marginLeft: 8,
fontFamily: errorFontFamily,
}}
>
{error}
</span>
)}
</div>
);
}
export default VoiceRecorder;
@@ -1,76 +0,0 @@
import type { FC } from 'react';
export const PlayIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.8" />
<path d="M8.5 7L17 12L8.5 17Z" fill="currentColor" />
</svg>
);
};
export const ResumeIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24">
<polygon points="8,5 19,12 8,19" fill="currentColor" />
</svg>
);
};
export const PauseIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24">
<rect x="6" y="5" width="4" height="14" fill="currentColor" />
<rect x="14" y="5" width="4" height="14" fill="currentColor" />
</svg>
);
};
export const StopIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24">
<rect x="6" y="6" width="12" height="12" fill="currentColor" />
</svg>
);
};
export const DeleteIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M4 7H20" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
<path d="M9 4H15" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
<path
d="M6 7L7 20C7.06457 20.7423 7.3378 21.25 8.25 21.25H15.75C16.6622 21.25 16.9354 20.7423 17 20L18 7"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path d="M10 11V17" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
<path d="M14 11V17" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
</svg>
);
};
export const RepeatIcon: FC<{ size?: number }> = function ({ size = 18 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24">
<path
d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"
fill="currentColor"
/>
</svg>
);
};
@@ -1,9 +1,7 @@
export { useVoiceRecorder } from './useVoiceRecorder';
export { default as VoiceRecorder } from './VoiceRecorder';
export type {
UseVoiceRecorderOptions,
UseVoiceRecorderReturn,
RecorderState,
VoiceRecorderProps,
VoiceRecorderStopPayload,
} from './types';
@@ -1,5 +1,3 @@
import type { CSSProperties, ReactNode } from 'react';
export type RecorderState = 'idle' | 'recording' | 'paused' | 'reviewing' | 'playing';
export type VoiceRecorderStopPayload = {
@@ -40,42 +38,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;
};
@@ -1,3 +1,4 @@
// Based on https://github.com/mohamad-fallah/react-voice-recorder-kit by mohamad-fallah
import { useCallback, useEffect, useRef, useState } from 'react';
import type {
UseVoiceRecorderOptions,
@@ -10,34 +11,40 @@ import { getSupportedAudioCodec, getSupportedAudioExtension } from './supportedC
const BAR_COUNT = 40;
const WAVEFORM_POINT_COUNT = 100;
// 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 <= targetCount) {
const padded = [...samples];
while (padded.length < targetCount) padded.push(0);
return padded;
let sharedAudioContext: AudioContext | null = null;
function getSharedAudioContext(): AudioContext {
if (!sharedAudioContext || sharedAudioContext.state === 'closed') {
sharedAudioContext = new AudioContext();
}
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 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.15);
if (samples.length <= targetCount) {
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;
});
}
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;
});
}
/**
* Custom React hook for recording voice messages using the MediaRecorder API.
* It manages the recording state, audio data, and provides functions to control the recording process (start, pause, stop, resume, play, etc.).
* It also handles audio visualization by analyzing the audio stream and generating levels for a visualizer.
* The hook supports multiple audio codecs and generates appropriate file extensions based on the supported codec.
*/
export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoiceRecorderReturn {
const { autoStart = true, onStop, onDelete } = options;
@@ -107,7 +114,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;
@@ -210,7 +219,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic
const setupAudioGraph = useCallback(
(stream: MediaStream): MediaStream => {
const audioContext = new AudioContext();
const audioContext = getSharedAudioContext();
audioContextRef.current = audioContext;
const source = audioContext.createMediaStreamSource(stream);
const analyser = audioContext.createAnalyser();
@@ -227,7 +236,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic
source.connect(analyser);
analyser.connect(destination);
audioContext.resume().catch(() => {});
if (audioContext.state === 'suspended') {
audioContext.resume().catch(() => {});
}
animateLevels();
return destination.stream;
@@ -237,7 +248,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();
@@ -249,7 +260,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]
+2
View File
@@ -9,6 +9,8 @@ import { createListAtom } from '$state/list';
export type TUploadMetadata = {
markedAsSpoiler: boolean;
waveform?: number[];
audioDuration?: number;
};
export type TUploadItem = {
+4
View File
@@ -71,6 +71,7 @@ export interface Settings {
privacyBlurAvatars: boolean;
privacyBlurEmotes: boolean;
showPronouns: boolean;
parsePronouns: boolean;
renderGlobalNameColors: boolean;
filterPronounsBasedOnLanguage?: boolean;
filterPronounsLanguages?: string[];
@@ -97,6 +98,7 @@ export interface Settings {
saveStickerEmojiBandwidth: boolean;
alwaysShowCallButton: boolean;
faviconForMentionsOnly: boolean;
highlightMentions: boolean;
// furry stuff
renderAnimals: boolean;
@@ -154,6 +156,7 @@ const defaultSettings: Settings = {
privacyBlurAvatars: false,
privacyBlurEmotes: false,
showPronouns: true,
parsePronouns: true,
renderGlobalNameColors: true,
renderRoomColors: true,
renderRoomFonts: true,
@@ -178,6 +181,7 @@ const defaultSettings: Settings = {
saveStickerEmojiBandwidth: false,
alwaysShowCallButton: false,
faviconForMentionsOnly: false,
highlightMentions: true,
// furry stuff
renderAnimals: true,
+2 -1
View File
@@ -8,7 +8,8 @@
* localStorage.removeItem('sable_debug'); location.reload();
*/
const isDebug = (): boolean => localStorage.getItem('sable_debug') === '1';
export const isDebug = (): boolean =>
import.meta.env.DEV || localStorage.getItem('sable_debug') === '1';
type LogLevel = 'log' | 'warn' | 'error';
+42
View File
@@ -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;
}