chore: merge dev into feat/tauri-integration

This commit is contained in:
hazre committed 2026-04-10 09:16:24 +02:00
commit 5c93992b41
40 files changed
+958 -681

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
default: minor
---
Add support for rendering bundled urls per MSC4095
@@ -1,5 +0,0 @@
---
default: minor
---
Improve code blocks with faster, more accurate syntax highlighting, broader language support, and separate light and dark theme options.
-5
View File
@@ -1,5 +0,0 @@
---
default: minor
---
Add statuses to DMs
-5
View File
@@ -1,5 +0,0 @@
---
default: minor
---
Add custom DM images and descriptions
@@ -1,5 +0,0 @@
---
default: minor
---
Add statuses to Member Tile
@@ -1,5 +0,0 @@
---
default: minor
---
Add a setting to collapse sidebar folders by default.
-5
View File
@@ -1,5 +0,0 @@
---
default: minor
---
Add a "Dismiss" button to command response messages.
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fix reply button not capturing editor focus.
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fixes links not being clickable in formatted messages, including messages that use abbreviations.
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fix some zero-width (invisible) names
@@ -1,5 +0,0 @@
---
default: minor
---
Re-introduced custom HTML formatting for long messages
@@ -1,5 +0,0 @@
---
default: patch
---
Fixed the "sticky scrolling" issue in encrypted rooms with many PMP messages.
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Image zooming is now centered on the cursor position
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Image zooming is now multiplicative instead of additive, resulting in a consistent "zooming speed".
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Image zoom buttons now zoom towards the center of the screen
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Right clicks no longer drag images in the viewer.
-5
View File
@@ -1,5 +0,0 @@
---
default: minor
---
You can now share direct links to specific settings, and opening one takes you to the right section and highlights the target option.
@@ -1,5 +0,0 @@
---
default: minor
---
Settings now use route-based navigation with improved desktop and mobile behavior, including better back and close handling.
+34
View File
@@ -1,5 +1,39 @@
# Sable Client Changelog
## 1.14.0 (2026-04-10)
### Features
* Add support for rendering bundled urls per MSC4095 ([#590](https://github.com/SableClient/Sable/pull/590) by @nushea)
* Improve code blocks with faster, more accurate syntax highlighting, broader language support, and separate light and dark theme options. ([#576](https://github.com/SableClient/Sable/pull/576) by @hazre)
* Add statuses to DMs ([#644](https://github.com/SableClient/Sable/pull/644) by @nushea)
* Add custom DM images and descriptions ([#644](https://github.com/SableClient/Sable/pull/644) by @nushea)
* Add statuses to Member Tile ([#644](https://github.com/SableClient/Sable/pull/644) by @nushea)
* Add the ability to set Global Name Colors dependent on the theme (dark/light) ([#656](https://github.com/SableClient/Sable/pull/656) by @nushea)
* Add a setting to collapse sidebar folders by default. ([#624](https://github.com/SableClient/Sable/pull/624) by @7w1)
* Add a "Dismiss" button to command response messages. ([#625](https://github.com/SableClient/Sable/pull/625) by @7w1)
* Update threads: various fixes, browse all room threads, and see live reply counts on messages. ([#564](https://github.com/SableClient/Sable/pull/564) by @Just-Insane)
* Re-introduced custom HTML formatting for long messages ([#641](https://github.com/SableClient/Sable/pull/641) by @Septicity)
* You can now share direct links to specific settings, and opening one takes you to the right section and highlights the target option. ([#577](https://github.com/SableClient/Sable/pull/577) by @hazre)
* Settings now use route-based navigation with improved desktop and mobile behavior, including better back and close handling. ([#577](https://github.com/SableClient/Sable/pull/577) by @hazre)
### Fixes
* Use file name instead of "a voice message" for non-voice audio files. ([#651](https://github.com/SableClient/Sable/pull/651) by @mvanhorn)
* Constrain bug report modal to viewport height to prevent overflow. ([#652](https://github.com/SableClient/Sable/pull/652) by @mvanhorn)
* Fix dms navigation not navigating to dms when local storage is messed up. ([#653](https://github.com/SableClient/Sable/pull/653) by @7w1)
* Fix reply button not capturing editor focus. ([#623](https://github.com/SableClient/Sable/pull/623) by @7w1)
* Fixes links not being clickable in formatted messages, including messages that use abbreviations. ([#632](https://github.com/SableClient/Sable/pull/632) by @hazre)
* Fix some zero-width (invisible) names ([#640](https://github.com/SableClient/Sable/pull/640) by @nushea)
* Fix iOS elastic bounce-back overscroll on the root element. ([#650](https://github.com/SableClient/Sable/pull/650) by @mvanhorn)
* Fixed the "sticky scrolling" issue in encrypted rooms with many PMP messages. ([#626](https://github.com/SableClient/Sable/pull/626) by @Septicity)
* Fix blank room timeline when app returns from background. When sliding sync delivers an `initial: true` response for the open room, a `TimelineReset` event now correctly shows skeleton placeholders while events reload instead of leaving an empty view. ([#657](https://github.com/SableClient/Sable/pull/657) by @Just-Insane)
* Image zooming is now centered on the cursor position ([#602](https://github.com/SableClient/Sable/pull/602) by @mini-bomba)
* Image zooming is now multiplicative instead of additive, resulting in a consistent "zooming speed". ([#602](https://github.com/SableClient/Sable/pull/602) by @mini-bomba)
* Image zoom buttons now zoom towards the center of the screen ([#602](https://github.com/SableClient/Sable/pull/602) by @mini-bomba)
* Right clicks no longer drag images in the viewer. ([#620](https://github.com/SableClient/Sable/pull/620) by @Septicity)
* Updated Support links to point to https://opencollective.com/sable ([#661](https://github.com/SableClient/Sable/pull/661) by @7w1)
## 1.13.1 (2026-03-30)
### Fixes
+1
View File
@@ -7,6 +7,7 @@ All types of contributions are encouraged and valued. Please make sure to read t
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
>
> - Star the project
> - [Donate](https://opencollective.com/sable)! ❤️
> - Talk about it!
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sable",
"version": "1.13.1",
"version": "1.14.0",
"description": "An almost stable Matrix client",
"type": "module",
"packageManager": "[email protected]+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
@@ -233,8 +233,8 @@ function BugReportModal() {
escapeDeactivates: stopPropagation,
}}
>
<Modal size="500" flexHeight variant="Surface">
<Box direction="Column">
<Modal size="500" flexHeight variant="Surface" style={{ maxHeight: '90vh' }}>
<Box direction="Column" style={{ maxHeight: '90vh', overflow: 'hidden' }}>
<Header
size="500"
style={{ padding: config.space.S200, paddingLeft: config.space.S400 }}
+18 -7
View File
@@ -32,6 +32,7 @@ import { MessageBase, CompactPlaceholder, DefaultPlaceholder } from '$components
import { RoomIntro } from '$components/room-intro';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useAlive } from '$hooks/useAlive';
import { useMessageEdit } from '$hooks/useMessageEdit';
import { useDocumentFocusChange } from '$hooks/useDocumentFocusChange';
import { markAsRead } from '$utils/notifications';
import {
@@ -124,6 +125,8 @@ export function RoomTimeline({
}: Readonly<RoomTimelineProps>) {
const mx = useMatrixClient();
const alive = useAlive();
const { editId, handleEdit } = useMessageEdit(editor, { onReset: onEditorReset, alive });
const { navigateRoom } = useRoomNavigate();
const [hideReads] = useSetting(settingsAtom, 'hideReads');
@@ -167,7 +170,6 @@ export function RoomTimeline({
return myPowerLevel < sendLevel;
}, [powerLevels, mx]);
const [editId, setEditId] = useState<string>();
const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true));
const readUptoEventIdRef = useRef<string | undefined>(undefined);
@@ -328,6 +330,17 @@ export function RoomTimeline({
[]
);
// If the timeline was blanked while content was already visible — e.g. a
// TimelineReset fired by mx.retryImmediately() when the app comes back from
// background — hide the timeline (opacity 0) and re-arm the initial-scroll so
// it runs again once events refill the live timeline.
useLayoutEffect(() => {
if (!isReady) return;
if (timelineSync.eventsLength > 0) return;
setIsReady(false);
hasInitialScrolledRef.current = false;
}, [isReady, timelineSync.eventsLength]);
const recalcTopSpacer = useCallback(() => {
const v = vListRef.current;
if (!v) return;
@@ -461,7 +474,6 @@ export function RoomTimeline({
room,
mx,
editor,
alive,
nicknames,
globalProfiles,
spaceId: optionalSpace?.roomId,
@@ -470,8 +482,7 @@ export function RoomTimeline({
setReplyDraft,
openThreadId,
setOpenThread,
setEditId,
onEditorReset,
handleEdit,
handleOpenEvent: (id) => {
const evtTimeline = getEventTimeline(room, id);
const absoluteIndex = evtTimeline
@@ -640,7 +651,7 @@ export function RoomTimeline({
const showLoadingPlaceholders =
timelineSync.eventsLength === 0 &&
(timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading');
(!isReady || timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading');
let backPaginationJSX: ReactNode | undefined;
if (timelineSync.canPaginateBack || timelineSync.backwardStatus !== 'idle') {
@@ -708,7 +719,7 @@ export function RoomTimeline({
const vListItemCount =
timelineSync.eventsLength === 0 &&
(timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading')
(!isReady || timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading')
? 3
: timelineSync.eventsLength;
const vListIndices = useMemo(
@@ -840,7 +851,7 @@ export function RoomTimeline({
minHeight: 0,
overflow: 'hidden',
position: 'relative',
opacity: isReady ? 1 : 0,
opacity: isReady || showLoadingPlaceholders ? 1 : 0,
}}
>
<VList<ProcessedEvent>
+239 -41
View File
@@ -15,12 +15,21 @@ import {
Icons,
Input,
Scroll,
Spinner,
Text,
Avatar,
config,
Chip,
} from 'folds';
import { MatrixEvent, Room, Thread, ThreadEvent } from '$types/matrix-sdk';
import {
EventTimelineSet,
MatrixEvent,
NotificationCountType,
Room,
RoomEvent,
Thread,
ThreadEvent,
} from '$types/matrix-sdk';
import { useAtomValue } from 'jotai';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
@@ -54,6 +63,7 @@ import {
makeMentionCustomProps,
renderMatrixMention,
} from '$plugins/react-custom-html-parser';
import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge';
import { EncryptedContent } from './message';
import * as css from './ThreadDrawer.css';
@@ -61,9 +71,10 @@ type ThreadPreviewProps = {
room: Room;
thread: Thread;
onClick: (threadId: string) => void;
onJump?: () => void;
};
function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) {
function ThreadPreview({ room, thread, onClick, onJump }: ThreadPreviewProps) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const { navigateRoom } = useRoomNavigate();
@@ -121,8 +132,25 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) {
(evt) => {
evt.stopPropagation();
navigateRoom(room.roomId, thread.id);
onJump?.();
},
[navigateRoom, room.roomId, thread.id]
[navigateRoom, room.roomId, thread.id, onJump]
);
const [, forceUnread] = useState(0);
useEffect(() => {
const onUnread = (_count: unknown, threadId?: string) => {
if (!threadId || threadId === thread.id) forceUnread((n) => n + 1);
};
room.on(RoomEvent.UnreadNotifications as any, onUnread);
return () => {
room.off(RoomEvent.UnreadNotifications as any, onUnread);
};
}, [room, thread.id]);
const unreadTotal = room.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total);
const unreadHighlight = room.getThreadUnreadNotificationCount(
thread.id,
NotificationCountType.Highlight
);
const { rootEvent } = thread;
@@ -134,9 +162,11 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) {
const senderAvatarMxc = getMemberAvatarMxc(room, senderId);
const getContent = (() => rootEvent.getContent()) as GetContentCallback;
const replyCount = thread.events.filter(
const localReplyCount = thread.events.filter(
(ev: MatrixEvent) => ev.getId() !== thread.id && !reactionOrEditEvent(ev)
).length;
// Use Math.max so we never show fewer replies than the server reports.
const replyCount = Math.max(localReplyCount, thread.length ?? 0);
const lastReply = thread.events
.filter((ev: MatrixEvent) => ev.getId() !== thread.id && !reactionOrEditEvent(ev))
@@ -189,7 +219,12 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) {
dateFormatString={dateFormatString}
/>
</Box>
<Box shrink="No">
<Box shrink="No" alignItems="Center" gap="200">
{unreadTotal > 0 && (
<UnreadBadgeCenter>
<UnreadBadge highlight={unreadHighlight > 0} count={unreadTotal} />
</UnreadBadgeCenter>
)}
<Chip data-event-id={thread.id} onClick={handleJumpClick} radii="Pill">
<Text size="T200">Jump</Text>
</Chip>
@@ -204,13 +239,7 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) {
onClick={handleJumpClick}
/>
)}
<Box
style={{
maxHeight: '200px',
overflow: 'auto',
flexShrink: 0,
}}
>
<Box style={{ maxHeight: '200px', overflow: 'auto', flexShrink: 0 }}>
<EncryptedContent mEvent={rootEvent}>
{() => {
if (rootEvent.isRedacted()) {
@@ -268,22 +297,162 @@ type ThreadBrowserProps = {
};
export function ThreadBrowser({ room, onOpenThread, onClose, overlay }: ThreadBrowserProps) {
const mx = useMatrixClient();
const [, forceUpdate] = useState(0);
const [query, setQuery] = useState('');
const [loadingMore, setLoadingMore] = useState(false);
const [canLoadMore, setCanLoadMore] = useState(false);
const searchRef = useRef<HTMLInputElement>(null);
const threadListTimelineSetRef = useRef<EventTimelineSet | null>(null);
const loadingMoreRef = useRef(false);
const canLoadMoreRef = useRef(false);
canLoadMoreRef.current = canLoadMore;
// Re-render when threads change.
// On mount, set up thread event listeners, create the server-side thread
// timeline sets, then fetch page 1 via paginate. The two operations are
// sequenced in a single effect so that createThreadsTimelineSets() always
// resolves before fetchRoomThreads() runs — the SDK's fetchRoomThreadList
// has an early-return guard (`if (this.threadsTimelineSets.length === 0)`)
// that silently no-ops when the sets haven't been created yet, so running
// both in parallel (the old two-effect approach) caused fetchRoomThreads to
// always be a no-op and left threadsReady=true prematurely.
useEffect(() => {
const onUpdate = () => forceUpdate((n) => n + 1);
room.on(ThreadEvent.New as any, onUpdate);
room.on(ThreadEvent.Update as any, onUpdate);
room.on(ThreadEvent.NewReply as any, onUpdate);
let cancelled = false;
const loadThreads = async () => {
setLoadingMore(true);
try {
// Create the timeline sets first — required before fetchRoomThreads().
const sets = await room.createThreadsTimelineSets();
if (!sets || cancelled) return;
const [allThreadsSet] = sets;
threadListTimelineSetRef.current = allThreadsSet;
// Now fetch page 1 from the /threads endpoint. threadsTimelineSets is
// populated so fetchRoomThreadList will not early-return.
await room.fetchRoomThreads().catch((err: unknown) => {
// eslint-disable-next-line no-console
console.warn('ThreadBrowser: fetchRoomThreads failed', err);
});
// Paginate to load the first page into the timeline set.
const hasMore = await mx.paginateEventTimeline(allThreadsSet.getLiveTimeline(), {
backwards: true,
});
// Ensure Thread objects exist for server-returned thread roots not yet
// known locally (threads outside the current sliding-sync window).
// fetchRoomThreads() creates Thread objects internally but uses
// room.findEventById() to set rootEvent — if the root event isn't in
// the sliding-sync cache, rootEvent ends up undefined, and
// ThreadPreview returns null for those threads. Backfill here using
// the event we already have from the threads timeline set.
allThreadsSet
.getLiveTimeline()
.getEvents()
.filter((event) => !!event.getId())
.forEach((event) => {
const id = event.getId()!;
const existingThread = room.getThread(id);
const bundled = (event.getUnsigned() as any)?.['m.relations']?.['m.thread'];
const bundledCount: number | undefined =
typeof bundled?.count === 'number' ? bundled.count : undefined;
if (!existingThread) {
room.createThread(id, event, [], false);
} else {
if (!existingThread.rootEvent) {
existingThread.rootEvent = event;
existingThread.setEventMetadata(event);
}
// Seed/update replyCount from bundled aggregations. This is needed
// for threads that were created by sliding-sync BEFORE fetchRoomThreads
// ran: SS delivers root events without bundled aggregations, so
// room.createThread() sets replyCount=0 and the SDK's fast-path
// ("replyCount===0 → initialEventsFetched=true, no server fetch") fires.
// Later, fetchRoomThreads() brings events WITH bundled counts, but
// createThread() is idempotent and returns the stale thread unchanged.
// Backfilling replyCount here lets ThreadPreview show the right count
// and lets Case C in ThreadDrawer know there are replies to fetch.
if (bundledCount !== undefined && (existingThread as any).replyCount === 0) {
(existingThread as any).replyCount = bundledCount;
}
}
});
if (!cancelled) {
setCanLoadMore(hasMore);
forceUpdate((n) => n + 1);
}
} catch {
// Server doesn't support thread list API; fall back to locally known threads.
} finally {
if (!cancelled) setLoadingMore(false);
}
};
loadThreads();
return () => {
cancelled = true;
room.off(ThreadEvent.New as any, onUpdate);
room.off(ThreadEvent.Update as any, onUpdate);
room.off(ThreadEvent.NewReply as any, onUpdate);
};
}, [room]);
}, [room, mx]);
const handleLoadMore = useCallback(async () => {
const tls = threadListTimelineSetRef.current;
if (!tls || loadingMore) return;
setLoadingMore(true);
try {
const hasMore = await mx.paginateEventTimeline(tls.getLiveTimeline(), { backwards: true });
tls
.getLiveTimeline()
.getEvents()
.filter((event) => !!event.getId())
.forEach((event) => {
const id = event.getId()!;
const existingThread = room.getThread(id);
const bundled = (event.getUnsigned() as any)?.['m.relations']?.['m.thread'];
const bundledCount: number | undefined =
typeof bundled?.count === 'number' ? bundled.count : undefined;
if (!existingThread) {
room.createThread(id, event, [], false);
} else {
if (!existingThread.rootEvent) {
existingThread.rootEvent = event;
existingThread.setEventMetadata(event);
}
if (bundledCount !== undefined && (existingThread as any).replyCount === 0) {
(existingThread as any).replyCount = bundledCount;
}
}
});
setCanLoadMore(hasMore);
forceUpdate((n) => n + 1);
} catch {
// ignore
} finally {
setLoadingMore(false);
loadingMoreRef.current = false;
}
}, [mx, room, loadingMore]);
const handleLoadMoreRef = useRef(handleLoadMore);
handleLoadMoreRef.current = handleLoadMore;
const handleThreadsScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
const el = e.currentTarget;
const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
if (distanceFromBottom < 200 && canLoadMoreRef.current && !loadingMoreRef.current) {
handleLoadMoreRef.current();
}
}, []);
const allThreads = room.getThreads().sort((a: Thread, b: Thread) => {
const aTs = a.events.at(-1)?.getTs() ?? a.rootEvent?.getTs() ?? 0;
@@ -309,7 +478,7 @@ export function ThreadBrowser({ room, onOpenThread, onClose, overlay }: ThreadBr
direction="Column"
shrink="No"
>
<Header className={css.ThreadDrawerHeader} variant="Background" size="400">
<Header className={css.ThreadDrawerHeader} variant="Background" size="600">
<Box grow="Yes" alignItems="Center" gap="200">
<Icon size="200" src={Icons.Thread} />
<Text size="H4" truncate>
@@ -317,9 +486,6 @@ export function ThreadBrowser({ room, onOpenThread, onClose, overlay }: ThreadBr
</Text>
</Box>
<Box alignItems="Center" gap="200" shrink="No">
<Text size="T300" priority="300" truncate>
# {room.name}
</Text>
<IconButton
onClick={onClose}
variant="SurfaceVariant"
@@ -371,31 +537,63 @@ export function ThreadBrowser({ room, onOpenThread, onClose, overlay }: ThreadBr
variant="Background"
visibility="Hover"
direction="Vertical"
hideTrack
size="300"
onScroll={handleThreadsScroll}
style={{ flexGrow: 1 }}
>
{threads.length === 0 ? (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Icon size="400" src={Icons.Thread} />
<Text size="T300" align="Center">
{lowerQuery ? 'No threads match your search.' : 'No threads yet.'}
</Text>
</Box>
) : (
<Box
direction="Column"
style={{ padding: `${config.space.S100} ${config.space.S200}` }}
>
{threads.map((thread: Thread) => (
<ThreadPreview key={thread.id} room={room} thread={thread} onClick={onOpenThread} />
))}
</Box>
)}
{(() => {
if (threads.length === 0 && loadingMore)
return (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Spinner variant="Secondary" size="400" />
</Box>
);
if (threads.length === 0)
return (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Icon size="400" src={Icons.Thread} />
<Text size="T300" align="Center">
{lowerQuery ? 'No threads match your search.' : 'No threads yet.'}
</Text>
</Box>
);
return (
<>
<Box
direction="Column"
style={{ padding: `${config.space.S100} ${config.space.S200}` }}
>
{threads.map((thread: Thread) => (
<ThreadPreview
key={thread.id}
room={room}
thread={thread}
onClick={onOpenThread}
onJump={onClose}
/>
))}
</Box>
{loadingMore && (
<Box
justifyContent="Center"
style={{ padding: config.space.S300, flexShrink: 0 }}
>
<Spinner variant="Secondary" size="400" />
</Box>
)}
</>
);
})()}
</Scroll>
</Box>
</Box>
@@ -60,7 +60,9 @@ export const ThreadBrowserItem = style({
background: 'none',
border: 'none',
color: 'inherit',
overflow: 'hidden',
':hover': {
backgroundColor: color.SurfaceVariant.Container,
transform: 'none',
},
});
+374 -408
View File
@@ -1,6 +1,8 @@
import { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Header, Icon, IconButton, Icons, Scroll, Text, config } from 'folds';
import { Box, Header, Icon, IconButton, Icons, Scroll, Spinner, Text, config } from 'folds';
import {
Direction,
IEvent,
MatrixEvent,
PushProcessor,
ReceiptType,
@@ -13,11 +15,6 @@ import { useAtomValue, useSetAtom } from 'jotai';
import { ReactEditor } from 'slate-react';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { ImageContent, MSticker, RedactedContent, Reply } from '$components/message';
import { RenderMessageContent } from '$components/RenderMessageContent';
import { Image } from '$components/media';
import { ImageViewer } from '$components/image-viewer';
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
import {
factoryRenderLinkifyWithMention,
getReactCustomHtmlParser,
@@ -25,26 +22,20 @@ import {
makeMentionCustomProps,
renderMatrixMention,
} from '$plugins/react-custom-html-parser';
import {
getEditedEvent,
getEventReactions,
getMemberDisplayName,
reactionOrEditEvent,
} from '$utils/room';
import { getEditedEvent, getMemberDisplayName, reactionOrEditEvent } from '$utils/room';
import { getMxIdLocalPart, toggleReaction } from '$utils/matrix';
import { minuteDifference } from '$utils/time';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
import { nicknamesAtom } from '$state/nicknames';
import { MessageLayout, MessageSpacing, settingsAtom } from '$state/settings';
import { settingsAtom } from '$state/settings';
import { useSetting } from '$state/hooks/settings';
import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
import { buildAbbrReplaceTextNode } from '$components/message/RenderBody';
import { createMentionElement, moveCursor, useEditor } from '$components/editor';
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
import { GetContentCallback, MessageEvent, StateEvent } from '$types/matrix/room';
import { MessageEvent, StateEvent } from '$types/matrix/room';
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { useRoomCreators } from '$hooks/useRoomCreators';
@@ -52,7 +43,12 @@ import { useImagePackRooms } from '$hooks/useImagePackRooms';
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
import { IReplyDraft, roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts';
import { roomToParentsAtom } from '$state/room/roomToParents';
import { EncryptedContent, Message, Reactions } from './message';
import { useIgnoredUsers } from '$hooks/useIgnoredUsers';
import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag';
import { useMemberEventParser } from '$hooks/useMemberEventParser';
import { useMessageEdit } from '$hooks/useMessageEdit';
import { useProcessedTimeline, ProcessedEvent } from '$hooks/timeline/useProcessedTimeline';
import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer';
import { RoomInput } from './RoomInput';
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
import * as css from './ThreadDrawer.css';
@@ -87,268 +83,6 @@ export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEv
);
}
type ForwardedMessageProps = {
isForwarded: boolean;
originalTimestamp: number;
originalRoomId: string;
originalEventId: string;
originalEventPrivate: boolean;
};
type ThreadMessageProps = {
room: Room;
mEvent: MatrixEvent;
threadRootId: string;
editId: string | undefined;
onEditId: (id?: string) => void;
messageLayout: MessageLayout;
messageSpacing: MessageSpacing;
canDelete: boolean;
canSendReaction: boolean;
canPinEvent: boolean;
imagePackRooms: Room[];
activeReplyId: string | undefined;
hour24Clock: boolean;
dateFormatString: string;
onUserClick: MouseEventHandler<HTMLButtonElement>;
onUsernameClick: MouseEventHandler<HTMLButtonElement>;
onReplyClick: MouseEventHandler<HTMLButtonElement>;
onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void;
onResend?: (event: MatrixEvent) => void;
onDeleteFailedSend?: (event: MatrixEvent) => void;
pushProcessor: PushProcessor;
linkifyOpts: LinkifyOpts;
htmlReactParserOptions: HTMLReactParserOptions;
showHideReads: boolean;
showDeveloperTools: boolean;
onReferenceClick: MouseEventHandler<HTMLButtonElement>;
jumpToEventId?: string;
collapse?: boolean;
};
function ThreadMessage({
room,
threadRootId: threadRootIdProp,
mEvent,
editId,
onEditId,
messageLayout,
messageSpacing,
canDelete,
canSendReaction,
collapse = false,
canPinEvent,
imagePackRooms,
activeReplyId,
hour24Clock,
dateFormatString,
onUserClick,
onUsernameClick,
onReplyClick,
onReactionToggle,
onResend,
onDeleteFailedSend,
pushProcessor,
linkifyOpts,
htmlReactParserOptions,
showHideReads,
showDeveloperTools,
onReferenceClick,
jumpToEventId,
}: ThreadMessageProps) {
// Use the thread's own timeline set so reactions/edits on thread events are found correctly
const threadTimelineSet = room.getThread(threadRootIdProp)?.timelineSet;
const timelineSet = threadTimelineSet ?? room.getUnfilteredTimelineSet();
const mEventId = mEvent.getId()!;
const senderId = mEvent.getSender() ?? '';
const nicknames = useAtomValue(nicknamesAtom);
const senderDisplayName =
getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId;
const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
const [urlPreview] = useSetting(settingsAtom, 'urlPreview');
const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview');
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers');
const editedEvent = getEditedEvent(mEventId, mEvent, timelineSet);
const editedNewContent = editedEvent?.getContent()['m.new_content'];
const baseContent = mEvent.getContent();
const safeContent =
Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent();
const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback;
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations?.getSortedAnnotationsByKey();
const hasReactions = reactions && reactions.length > 0;
const pushActions = pushProcessor.actionsForEvent(mEvent);
let notifyHighlight: 'silent' | 'loud' | undefined;
if (pushActions?.notify && pushActions.tweaks?.highlight) {
notifyHighlight = pushActions.tweaks?.sound ? 'loud' : 'silent';
}
// Extract message forwarding info
const forwardContent = safeContent['moe.sable.message.forward'] as
| {
original_timestamp?: unknown;
original_room_id?: string;
original_event_id?: string;
original_event_private?: boolean;
}
| undefined;
const messageForwardedProps: ForwardedMessageProps | undefined = forwardContent
? {
isForwarded: true,
originalTimestamp:
typeof forwardContent.original_timestamp === 'number'
? forwardContent.original_timestamp
: mEvent.getTs(),
originalRoomId: forwardContent.original_room_id ?? room.roomId,
originalEventId: forwardContent.original_event_id ?? '',
originalEventPrivate: forwardContent.original_event_private ?? false,
}
: undefined;
const { replyEventId } = mEvent;
const relation = mEvent.getRelation();
const contentRelatesTo = mEvent.getContent()?.['m.relates_to'];
const isFallback =
relation?.is_falling_back === true || contentRelatesTo?.is_falling_back === true;
return (
<Message
key={mEvent.getId()}
data-message-id={mEventId}
room={room}
mEvent={mEvent}
messageSpacing={messageSpacing}
messageLayout={messageLayout}
collapse={collapse}
highlight={jumpToEventId === mEventId}
notifyHighlight={notifyHighlight}
edit={editId === mEventId}
canDelete={canDelete}
canSendReaction={canSendReaction}
canPinEvent={canPinEvent}
imagePackRooms={imagePackRooms}
relations={hasReactions ? reactionRelations : undefined}
onUserClick={onUserClick}
onUsernameClick={onUsernameClick}
onReplyClick={onReplyClick}
onReactionToggle={onReactionToggle}
onEditId={onEditId}
senderId={senderId}
senderDisplayName={senderDisplayName}
messageForwardedProps={messageForwardedProps}
sendStatus={mEvent.getAssociatedStatus()}
onResend={onResend}
onDeleteFailedSend={onDeleteFailedSend}
activeReplyId={activeReplyId ?? null}
hour24Clock={hour24Clock}
dateFormatString={dateFormatString}
hideReadReceipts={showHideReads}
showDeveloperTools={showDeveloperTools}
reply={
replyEventId &&
!isFallback && (
<Reply
room={room}
timelineSet={timelineSet}
replyEventId={replyEventId}
mentions={baseContent['m.mentions']}
onClick={onReferenceClick}
/>
)
}
reactions={
hasReactions ? (
<Reactions
style={{ marginTop: config.space.S200 }}
room={room}
relations={reactionRelations!}
mEventId={mEventId}
canSendReaction={canSendReaction}
canDeleteOwn={canDelete}
onReactionToggle={onReactionToggle}
/>
) : undefined
}
>
{mEvent.isRedacted() ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<EncryptedContent mEvent={mEvent}>
{() => {
if (mEvent.isRedacted())
return (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
);
if (mEvent.getType() === MessageEvent.Sticker)
return (
<MSticker
content={mEvent.getContent()}
renderImageContent={(props) => (
<ImageContent
{...props}
autoPlay={mediaAutoLoad}
renderImage={(p) => {
if (!autoplayStickers && p.src) {
return (
<ClientSideHoverFreeze src={p.src}>
<Image {...p} loading="lazy" />
</ClientSideHoverFreeze>
);
}
return <Image {...p} loading="lazy" />;
}}
renderViewer={(p) => <ImageViewer {...p} />}
/>
)}
/>
);
if (mEvent.getType() === MessageEvent.RoomMessage) {
return (
<RenderMessageContent
displayName={senderDisplayName}
msgType={(editedNewContent ?? safeContent).msgtype ?? ''}
ts={mEvent.getTs()}
edited={!!editedEvent}
getContent={getContent}
mediaAutoLoad={mediaAutoLoad}
urlPreview={showUrlPreview}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
outlineAttachment={messageLayout === MessageLayout.Bubble}
/>
);
}
return (
<RenderMessageContent
displayName={senderDisplayName}
msgType={(editedNewContent ?? safeContent).msgtype ?? ''}
ts={mEvent.getTs()}
edited={!!editedEvent}
getContent={getContent}
mediaAutoLoad={mediaAutoLoad}
urlPreview={showUrlPreview}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
outlineAttachment={messageLayout === MessageLayout.Bubble}
/>
);
}}
</EncryptedContent>
)}
</Message>
);
}
type ThreadDrawerProps = {
room: Room;
threadRootId: string;
@@ -360,12 +94,17 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const mx = useMatrixClient();
const drawerRef = useRef<HTMLDivElement>(null);
const editor = useEditor();
const [, forceUpdate] = useState(0);
const [editId, setEditId] = useState<string | undefined>(undefined);
const [forceUpdateCounter, forceUpdate] = useState(0);
const [jumpToEventId, setJumpToEventId] = useState<string | undefined>(undefined);
const [loadingOlderReplies, setLoadingOlderReplies] = useState(false);
const [canPageBack, setCanPageBack] = useState(true);
const paginatingOlderRef = useRef(false);
const scrollRef = useRef<HTMLDivElement>(null);
const prevReplyCountRef = useRef(0);
const replyEventsRef = useRef<MatrixEvent[]>([]);
const processedEventsRef = useRef<ProcessedEvent[]>([]);
const serverFetchAttemptedRef = useRef<string | null>(null);
const autoFillInProgressRef = useRef(false);
const { editId, handleEdit } = useMessageEdit(editor);
const nicknames = useAtomValue(nicknamesAtom);
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
const useAuthentication = useMediaAuthentication();
@@ -380,6 +119,21 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
const [hideReads] = useSetting(settingsAtom, 'hideReads');
const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools');
const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
const [urlPreview] = useSetting(settingsAtom, 'urlPreview');
const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview');
const [clientUrlPreview] = useSetting(settingsAtom, 'clientUrlPreview');
const [encClientUrlPreview] = useSetting(settingsAtom, 'encClientUrlPreview');
const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers');
const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis');
const [showHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents');
const [showTombstoneEvents] = useSetting(settingsAtom, 'showTombstoneEvents');
const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly');
const [showBundledPreview] = useSetting(settingsAtom, 'bundledPreview');
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
const showClientUrlPreview = room.hasEncryptionStateEvent()
? clientUrlPreview && encClientUrlPreview
: clientUrlPreview;
// Memoized parsing options
const linkifyOpts = useMemo<LinkifyOpts>(
@@ -412,6 +166,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
nicknames,
autoplayEmojis,
replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts),
}),
[
@@ -423,6 +178,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
useAuthentication,
nicknames,
settingsLinkBaseUrl,
autoplayEmojis,
abbrMap,
]
);
@@ -435,6 +191,17 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const canDeleteOwn = permissions.event(MessageEvent.RoomRedaction, mx.getSafeUserId());
const canSendReaction = permissions.event(MessageEvent.Reaction, mx.getSafeUserId());
const canPinEvent = permissions.stateEvent(StateEvent.RoomPinnedEvents, mx.getSafeUserId());
const isReadOnly = useMemo(() => {
const myPowerLevel = powerLevels?.users?.[mx.getUserId()!] ?? powerLevels?.users_default ?? 0;
const sendLevel = powerLevels?.events?.['m.room.message'] ?? powerLevels?.events_default ?? 0;
return myPowerLevel < sendLevel;
}, [powerLevels, mx]);
const getMemberPowerTag = useGetMemberPowerTag(room, creators, powerLevels);
const parseMemberEvent = useMemberEventParser();
// Ignored users
const ignoredUsersList = useIgnoredUsers();
const ignoredUsersSet = useMemo(() => new Set(ignoredUsersList), [ignoredUsersList]);
// Image packs
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -448,31 +215,92 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
// User profile popup
const openUserRoomProfile = useOpenUserRoomProfile();
const rootEvent = room.findEventById(threadRootId);
// Thread timeline data for useProcessedTimeline
const thread = room.getThread(threadRootId);
const threadTimeline = thread?.timelineSet.getLiveTimeline();
// When the drawer is opened with classic sync (no server-side thread support),
// room.createThread() may have been called with empty initialEvents so
// thread.events only has the root. Backfill events from the main room
// timeline so the authoritative source is populated for subsequent renders.
//
// IMPORTANT: skip this backfill when server-side thread support is active
// (initialEventsFetched starts false). In that case the SDK will call
// updateThreadMetadata() → resetLiveTimeline() + paginateEventTimeline()
// automatically. Calling thread.addEvents() ourselves first would trigger
// that same cascade prematurely and cause a flood of
// "EventTimelineSet.addEventToTimeline: Ignoring event=…" warnings because
// canContain() fails while the timeline is in the middle of being reset and
// repopulated.
// Prefer the event from the main timeline (already indexed), but fall back
// to thread.rootEvent — populated from bundled /threads server data even when
// the root is outside the currently-loaded timeline window.
const rootEvent = room.findEventById(threadRootId) ?? thread?.rootEvent;
const totalEvents = threadTimeline?.getEvents().length ?? 0;
const linkedTimelines = useMemo(
() => (threadTimeline ? [threadTimeline] : []),
// eslint-disable-next-line react-hooks/exhaustive-deps
[threadTimeline, totalEvents]
);
const items = useMemo(() => Array.from({ length: totalEvents }, (_, i) => i), [totalEvents]);
const processedEvents = useProcessedTimeline({
items,
linkedTimelines,
skipThreadFilter: true,
ignoredUsersSet,
showHiddenEvents,
showTombstoneEvents,
mxUserId: mx.getUserId(),
readUptoEventId: undefined,
hideMembershipEvents: true,
hideNickAvatarEvents: true,
isReadOnly,
hideMemberInReadOnly,
});
// When the thread's own timeline is empty (server-side threads not yet fetched,
// or classic sync before backfill completes), fall back to scanning the main
// room timeline directly so replies are shown immediately.
const displayReplies = useMemo((): ProcessedEvent[] => {
const filtered = processedEvents.filter((e) => e.id !== threadRootId);
if (filtered.length > 0) return filtered;
const timelineSet = thread?.timelineSet ?? room.getUnfilteredTimelineSet();
return getThreadReplyEvents(room, threadRootId).map((ev, idx) => ({
id: ev.getId()!,
itemIndex: idx,
mEvent: ev,
timelineSet,
eventSender: ev.getSender() ?? null,
collapsed: false,
willRenderNewDivider: false,
willRenderDayDivider: false,
}));
// forceUpdateCounter makes this recompute whenever events arrive
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [room, threadRootId, thread, processedEvents, forceUpdateCounter]);
processedEventsRef.current = displayReplies;
const processedReplies = displayReplies;
// Ensure the Thread object exists and has its reply events loaded.
useEffect(() => {
const thread = room.getThread(threadRootId);
if (!thread) return;
// initialEventsFetched === false ↔ Thread.hasServerSideSupport is set.
// The SDK handles initialization itself; our manual backfill must not run.
if (!thread.initialEventsFetched) return;
const hasRepliesInThread = thread.events.some(
// Case A: create thread shell; SDK handles the rest asynchronously.
if (!room.getThread(threadRootId)) {
const localRoot = room.findEventById(threadRootId);
if (localRoot) {
room.createThread(threadRootId, localRoot, [], false);
} else {
// Root not in local timeline — fetch it from the server without
// touching the main timeline (no TimelineRefresh side-effect).
mx.fetchRoomEvent(room.roomId, threadRootId)
.then((rawEvt) => {
if (room.getThread(threadRootId)) return; // created concurrently
room.createThread(threadRootId, new MatrixEvent(rawEvt as IEvent), [], false);
})
.catch(() => {});
}
}
const currThread = room.getThread(threadRootId);
// Case B: SDK is actively initialising — don't interfere.
if (!currThread || !currThread.initialEventsFetched) return;
// Case C: SDK is done (or classic sync). Backfill from live timeline if
// thread.events is still empty (classic sync path; server-side was already
// populated by paginateEventTimeline inside updateThreadMetadata).
const hasRepliesInThread = currThread.events.some(
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (hasRepliesInThread) return; // already populated, nothing to do
if (hasRepliesInThread) return;
const liveEvents = room
.getUnfilteredTimelineSet()
@@ -485,9 +313,23 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
!reactionOrEditEvent(ev)
);
if (liveEvents.length > 0) {
thread.addEvents(liveEvents, false);
// thread.addEvents() is typed as void but is internally async; schedule
// forceUpdate in a microtask so the timeline has been updated first.
currThread.addEvents(liveEvents, false);
Promise.resolve().then(() => forceUpdate((n) => n + 1));
return;
}
}, [room, threadRootId]);
if (serverFetchAttemptedRef.current === threadRootId) return;
serverFetchAttemptedRef.current = threadRootId;
mx.paginateEventTimeline(currThread.timelineSet.getLiveTimeline(), { backwards: true })
.then(() => forceUpdate((n) => n + 1))
.catch(() => {});
// forceUpdateCounter must be in deps so this effect re-runs after
// ThreadEvent.Update fires (which flips initialEventsFetched from false to
// true).
}, [mx, room, threadRootId, forceUpdate, forceUpdateCounter]);
// Re-render when new thread events arrive (including reactions via ThreadEvent.Update).
useEffect(() => {
@@ -542,10 +384,10 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
// Mark thread as read when viewing it
useEffect(() => {
const markThreadAsRead = async () => {
const thread = room.getThread(threadRootId);
if (!thread) return;
const currentThread = room.getThread(threadRootId);
if (!currentThread) return;
const events = thread.events || [];
const events = currentThread.events || [];
if (events.length === 0) return;
const lastEvent = events[events.length - 1];
@@ -554,7 +396,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const userId = mx.getUserId();
if (!userId) return;
const readUpToId = thread.getEventReadUpTo(userId, false);
const readUpToId = currentThread.getEventReadUpTo(userId, false);
const lastEventId = lastEvent.getId();
// Only send receipt if we haven't already read up to the last event
@@ -570,22 +412,85 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
// Mark as read when opened and when new messages arrive
markThreadAsRead();
}, [mx, room, threadRootId, forceUpdate]);
}, [mx, room, threadRootId, forceUpdateCounter]);
const replyEvents = getThreadReplyEvents(room, threadRootId);
const isThreadLoading = !!thread && !thread.initialEventsFetched && replyEvents.length === 0;
replyEventsRef.current = replyEvents;
const hasOlderReplies =
canPageBack &&
!!thread?.initialEventsFetched &&
thread?.timelineSet.getLiveTimeline().getPaginationToken(Direction.Backward) != null;
// Auto-scroll to bottom when event count grows (if the user is near the bottom).
// Keep a ref so the scroll handler always reads the latest value without deps.
const hasOlderRepliesRef = useRef(hasOlderReplies);
hasOlderRepliesRef.current = hasOlderReplies;
const loadOlderReplies = useCallback(() => {
const t = room.getThread(threadRootId);
if (!t || !t.initialEventsFetched || paginatingOlderRef.current) return;
paginatingOlderRef.current = true;
setLoadingOlderReplies(true);
mx.paginateEventTimeline(t.timelineSet.getLiveTimeline(), { backwards: true })
.then((hasMore) => {
paginatingOlderRef.current = false;
if (!hasMore) setCanPageBack(false);
setLoadingOlderReplies(false);
forceUpdate((n) => n + 1);
})
.catch(() => {
paginatingOlderRef.current = false;
setLoadingOlderReplies(false);
});
}, [mx, room, threadRootId, forceUpdate]);
const loadOlderRepliesRef = useRef(loadOlderReplies);
loadOlderRepliesRef.current = loadOlderReplies;
useEffect(() => {
setCanPageBack(true);
autoFillInProgressRef.current = false;
}, [threadRootId]);
const handleRepliesScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
if (el.scrollTop < 200 && hasOlderRepliesRef.current && !paginatingOlderRef.current) {
loadOlderRepliesRef.current();
}
}, []);
// Auto-scroll to bottom when event count grows.
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150;
if (prevReplyCountRef.current === 0 || isAtBottom) {
if (prevReplyCountRef.current === 0 || isAtBottom || autoFillInProgressRef.current) {
el.scrollTop = el.scrollHeight;
}
prevReplyCountRef.current = replyEvents.length;
}, [replyEvents.length]);
prevReplyCountRef.current = processedReplies.length;
}, [processedReplies.length]);
// Auto-fill viewport: paginate backwards until content overflows the scroll
// container, then stop. The scroll handler (handleRepliesScroll) loads more
// when the user scrolls back up past the top threshold.
useEffect(() => {
if (paginatingOlderRef.current) return;
const el = scrollRef.current;
if (!el) return;
if (!hasOlderReplies) {
autoFillInProgressRef.current = false;
return;
}
if (el.scrollHeight <= el.clientHeight) {
// Content doesn't yet fill the viewport — paginate one more page.
autoFillInProgressRef.current = true;
loadOlderRepliesRef.current();
} else {
// Content now overflows — fill is complete.
autoFillInProgressRef.current = false;
}
}, [processedReplies.length, hasOlderReplies]);
const handleUserClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
@@ -677,16 +582,29 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
[mx, room, threadRootId]
);
const handleEdit = useCallback(
(evtId?: string) => {
setEditId(evtId);
if (!evtId) {
ReactEditor.focus(editor);
moveCursor(editor);
const handleEditLastMessage = useCallback(() => {
const userId = mx.getUserId();
const ownReply = [...processedEventsRef.current]
.reverse()
.find(
(e) =>
e.id !== threadRootId &&
e.mEvent.getSender() === userId &&
!e.mEvent.isRedacted() &&
!reactionOrEditEvent(e.mEvent)
);
const ownId = ownReply?.id;
if (ownId) {
handleEdit(ownId);
const el = drawerRef.current;
if (el) {
el.querySelector(`[data-message-id="${ownId}"]`)?.scrollIntoView({
block: 'nearest',
behavior: 'smooth',
});
}
},
[editor]
);
}
}, [mx, threadRootId, handleEdit]);
const handleResend = useCallback(
(event: MatrixEvent) => {
@@ -707,7 +625,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const targetId = evt.currentTarget.getAttribute('data-event-id');
if (!targetId) return;
const isRoot = targetId === threadRootId;
const isInReplies = replyEventsRef.current.some((e) => e.getId() === targetId);
const isInReplies = processedEventsRef.current.some((e) => e.id === targetId);
if (!isRoot && !isInReplies) return;
setJumpToEventId(targetId);
setTimeout(() => setJumpToEventId(undefined), 2500);
@@ -720,42 +638,64 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
[threadRootId]
);
const sharedMessageProps = {
// Map jumpToEventId to a focusItem index for useTimelineEventRenderer highlighting
const jumpIndex = jumpToEventId ? processedEvents.findIndex((e) => e.id === jumpToEventId) : -1;
const focusItem =
jumpIndex >= 0
? { index: processedEvents[jumpIndex].itemIndex, highlight: true, scrollTo: false as const }
: undefined;
const renderMatrixEvent = useTimelineEventRenderer({
room,
threadRootId,
editId,
onEditId: handleEdit,
messageLayout,
messageSpacing,
canDelete: canRedact || canDeleteOwn,
canSendReaction,
canPinEvent,
imagePackRooms,
activeReplyId,
hour24Clock,
dateFormatString,
onUserClick: handleUserClick,
onUsernameClick: handleUsernameClick,
onReplyClick: handleReplyClick,
onReactionToggle: handleReactionToggle,
onResend: handleResend,
onDeleteFailedSend: handleDeleteFailedSend,
mx,
pushProcessor,
linkifyOpts,
htmlReactParserOptions,
showHideReads: hideReads,
showDeveloperTools,
onReferenceClick: handleOpenReply,
jumpToEventId,
};
nicknames,
imagePackRooms,
settings: {
messageLayout,
messageSpacing,
hideReads,
showDeveloperTools,
hour24Clock,
dateFormatString,
mediaAutoLoad,
showUrlPreview,
showClientUrlPreview,
showBundledPreview,
autoplayStickers,
hideMemberInReadOnly,
isReadOnly,
hideMembershipEvents: true,
hideNickAvatarEvents: true,
showHiddenEvents,
hideThreadChip: true,
},
state: { focusItem, editId, activeReplyId, openThreadId: threadRootId },
permissions: {
canRedact,
canDeleteOwn,
canSendReaction,
canPinEvent,
},
callbacks: {
onUserClick: handleUserClick,
onUsernameClick: handleUsernameClick,
onReplyClick: handleReplyClick,
onReactionToggle: handleReactionToggle,
onEditId: handleEdit,
onResend: handleResend,
onDeleteFailedSend: handleDeleteFailedSend,
setOpenThread: () => {},
handleOpenReply,
},
utils: { htmlReactParserOptions, linkifyOpts, getMemberPowerTag, parseMemberEvent },
});
// Latest thread event for the following indicator (latest reply, or root if no replies)
const threadParticipantIds = new Set(
[rootEvent, ...replyEvents].map((ev) => ev?.getSender()).filter(Boolean) as string[]
processedEvents.map((e) => e.mEvent.getSender()).filter(Boolean) as string[]
);
const latestThreadEventId = (
replyEvents.length > 0 ? replyEvents[replyEvents.length - 1] : rootEvent
)?.getId();
const latestThreadEventId = processedEvents.at(-1)?.id ?? rootEvent?.getId();
return (
<Box
@@ -773,9 +713,6 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
</Text>
</Box>
<Box alignItems="Center" gap="200" shrink="No">
<Text size="T300" priority="300" truncate>
# {room.name}
</Text>
<IconButton
onClick={onClose}
variant="SurfaceVariant"
@@ -794,6 +731,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
variant="Background"
visibility="Hover"
direction="Vertical"
size="300"
hideTrack
style={{
maxHeight: '200px',
@@ -808,7 +746,15 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
padding: `${config.space.S200} 0 ${config.space.S100} 0`,
}}
>
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
{renderMatrixEvent(
rootEvent.getType(),
typeof rootEvent.getStateKey() === 'string',
rootEvent.getId()!,
rootEvent,
processedEvents.find((e) => e.id === threadRootId)?.itemIndex ?? 0,
thread?.timelineSet ?? room.getUnfilteredTimelineSet(),
false
)}
</Box>
</Scroll>
)}
@@ -820,58 +766,77 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
variant="Background"
visibility="Hover"
direction="Vertical"
hideTrack
size="300"
onScroll={handleRepliesScroll}
style={{ flexGrow: 1 }}
>
{replyEvents.length === 0 ? (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Icon size="400" src={Icons.Thread} />
<Text size="T300" align="Center">
No replies yet. Start the thread below!
</Text>
</Box>
) : (
<>
{/* Reply count label inside scroll area */}
<Box
style={{
padding: `${config.space.S200} ${config.space.S400}`,
flexShrink: 0,
}}
>
<Text size="T300" priority="300">
{replyEvents.length} {replyEvents.length === 1 ? 'reply' : 'replies'}
</Text>
</Box>
<Box
className={css.messageList}
direction="Column"
style={{ padding: `0 0 ${config.space.S600} 0` }}
>
{replyEvents.map((mEvent, i) => {
const prevEvent = i > 0 ? replyEvents[i - 1] : undefined;
const collapse =
prevEvent !== undefined &&
prevEvent.getSender() === mEvent.getSender() &&
prevEvent.getType() === mEvent.getType() &&
minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2;
return (
<ThreadMessage
key={mEvent.getId()}
{...sharedMessageProps}
mEvent={mEvent}
collapse={collapse}
/>
);
})}
</Box>
</>
)}
{(() => {
if (isThreadLoading)
return (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400 }}
>
<Spinner variant="Secondary" size="400" />
</Box>
);
if (processedReplies.length === 0)
return (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Icon size="400" src={Icons.Thread} />
<Text size="T300" align="Center">
No replies yet. Start the thread below!
</Text>
</Box>
);
return (
<>
{loadingOlderReplies && (
<Box
justifyContent="Center"
style={{ padding: config.space.S300, flexShrink: 0 }}
>
<Spinner variant="Secondary" size="200" />
</Box>
)}
{/* Reply count label inside scroll area */}
<Box
style={{
padding: `${config.space.S200} ${config.space.S400}`,
flexShrink: 0,
}}
>
<Text size="T300" priority="300">
{processedReplies.length} {processedReplies.length === 1 ? 'reply' : 'replies'}
</Text>
</Box>
<Box
className={css.messageList}
direction="Column"
style={{ padding: `0 0 ${config.space.S600} 0` }}
>
{processedReplies.map((e) =>
renderMatrixEvent(
e.mEvent.getType(),
typeof e.mEvent.getStateKey() === 'string',
e.id,
e.mEvent,
e.itemIndex,
e.timelineSet,
e.collapsed
)
)}
</Box>
</>
);
})()}
</Scroll>
</Box>
@@ -885,6 +850,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
threadRootId={threadRootId}
editor={editor}
fileDropContainerRef={drawerRef}
onEditLastMessage={handleEditLastMessage}
/>
</div>
{hideReads ? (
+4 -2
View File
@@ -147,10 +147,12 @@ export type AudioMsgContent = IContent & {
export const getAudioMsgContent = (item: TUploadItem, mxc: string): AudioMsgContent => {
const { file, encInfo, metadata } = item;
const { waveform, audioDuration, markedAsSpoiler } = metadata;
const isVoice = waveform !== undefined && waveform.length > 0;
const fallbackBody = isVoice ? 'a voice message' : file.name;
let content: IContent = {
msgtype: MsgType.Audio,
filename: file.name,
body: item.body && item.body.length > 0 ? item.body : 'a voice message',
body: item.body && item.body.length > 0 ? item.body : fallbackBody,
info: {
mimetype: file.type,
size: file.size,
@@ -162,7 +164,7 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): AudioMsgCont
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.msc1767.text': item.body && item.body.length > 0 ? item.body : fallbackBody,
'org.matrix.msc3245.voice.v2': {
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration,
waveform: waveform?.map((v) => Math.round(v * 1024)),
+1 -1
View File
@@ -209,7 +209,7 @@ export function About({ requestBack, requestClose }: Readonly<AboutProps>) {
</Button>
<Button
as="a"
href="https://github.com/SableClient/Sable/pulls"
href="https://opencollective.com/sable"
rel="noreferrer noopener"
target="_blank"
variant="Critical"
@@ -7,6 +7,7 @@ import { HexColorPickerPopOut } from '$components/HexColorPickerPopOut';
type NameColorEditorProps = {
title: string;
description?: string;
focusId?: string;
current?: string;
onSave: (color: string | null) => void;
disabled?: boolean;
@@ -15,6 +16,7 @@ type NameColorEditorProps = {
export function NameColorEditor({
title,
description,
focusId,
current,
onSave,
disabled,
@@ -57,89 +59,94 @@ export function NameColorEditor({
return (
<Box direction="Column" gap="100">
<SettingTile title={title} focusId="name-color" description={description} />
<Box
alignItems="Center"
justifyContent="SpaceBetween"
gap="300"
style={{
padding: config.space.S400,
backgroundColor: 'var(--sable-surface-container)',
borderRadius: config.radii.R400,
}}
>
<Box alignItems="Center" gap="300" grow="Yes">
<HexColorPickerPopOut
picker={<HexColorPicker color={tempColor} onChange={handleUpdate} />}
<SettingTile
title={title}
focusId={focusId}
description={description}
after={
<Box
alignItems="Center"
justifyContent="SpaceBetween"
gap="300"
style={{
padding: config.space.S100,
backgroundColor: 'var(--sable-surface-container)',
borderRadius: config.radii.R400,
}}
>
{(onOpen, opened) => (
<Button
onClick={onOpen}
size="400"
variant="Secondary"
fill="None"
radii="300"
disabled={disabled ?? false}
style={{
padding: config.space.S100,
border: `2px solid ${opened ? 'var(--sable-primary-main)' : 'var(--sable-border-focus)'}`,
}}
<Box alignItems="Center" gap="300" grow="Yes">
{hasChanged && (
<Button
variant="Primary"
size="300"
radii="Pill"
onClick={handleSave}
disabled={!/^#[0-9A-F]{6}$/i.test(tempColor)}
>
<Text size="B300">Save</Text>
</Button>
)}
<HexColorPickerPopOut
picker={<HexColorPicker color={tempColor} onChange={handleUpdate} />}
>
<Box
{(onOpen, opened) => (
<Button
onClick={onOpen}
size="400"
variant="Secondary"
fill="None"
radii="300"
disabled={disabled ?? false}
style={{
padding: config.space.S100,
border: `2px solid ${opened ? 'var(--sable-primary-main)' : 'var(--sable-border-focus)'}`,
}}
>
<Box
style={{
width: '32px',
height: '32px',
borderRadius: '50%',
backgroundColor: tempColor,
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)',
}}
/>
</Button>
)}
</HexColorPickerPopOut>
<Box direction="Row" alignItems="Center" gap="100">
<Input
value={tempColor}
onChange={(e) => handleUpdate(e.currentTarget.value)}
placeholder="#FFFFFF"
variant="Background"
size="300"
radii="300"
disabled={disabled ?? false}
style={{
width: '32px',
height: '32px',
borderRadius: '50%',
backgroundColor: tempColor,
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)',
textTransform: 'uppercase',
fontFamily: 'monospace',
width: '100px',
}}
/>
</Button>
)}
</HexColorPickerPopOut>
<Box direction="Row" alignItems="Center" gap="100">
<Input
value={tempColor}
onChange={(e) => handleUpdate(e.currentTarget.value)}
placeholder="#FFFFFF"
variant="Background"
size="300"
radii="300"
disabled={disabled ?? false}
style={{
textTransform: 'uppercase',
fontFamily: 'monospace',
width: '100px',
}}
/>
{current && (
<IconButton
variant="Secondary"
size="300"
radii="300"
disabled={disabled ?? false}
onClick={handleReset}
title="Reset to default"
>
<Icon src={Icons.Cross} size="100" />
</IconButton>
)}
{current && (
<IconButton
variant="Secondary"
size="300"
radii="300"
disabled={disabled ?? false}
onClick={handleReset}
title="Reset to default"
>
<Icon src={Icons.Cross} size="100" />
</IconButton>
)}
</Box>
</Box>
</Box>
</Box>
{hasChanged && (
<Button
variant="Primary"
size="300"
radii="Pill"
onClick={handleSave}
disabled={!/^#[0-9A-F]{6}$/i.test(tempColor)}
>
<Text size="B300">Save</Text>
</Button>
)}
</Box>
}
/>
</Box>
);
}
+20 -2
View File
@@ -539,11 +539,30 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
gap="400"
>
<NameColorEditor
title="Global Name Color"
title="General Global Name Color"
description="Custom name color everywhere names have color!"
focusId="name-color"
current={profile.nameColor || profile.extended?.['moe.sable.app.name_color']}
onSave={(color) => handleSaveField('moe.sable.app.name_color', color)}
/>
<NameColorEditor
title="Dark theme Global Name Color"
description="Your name's color for a dark theme user."
focusId="name-color-dark-theme"
current={
profile.nameColorDark || profile.extended?.['moe.sable.app.name_color_dark_theme']
}
onSave={(color) => handleSaveField('moe.sable.app.name_color_dark_theme', color)}
/>
<NameColorEditor
title="Light theme Global Name Color"
description="Your name's color for a light theme user."
focusId="name-color-light-theme"
current={
profile.nameColorLight || profile.extended?.['moe.sable.app.name_color_light_theme']
}
onSave={(color) => handleSaveField('moe.sable.app.name_color_light_theme', color)}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
@@ -658,7 +677,6 @@ export function Profile() {
const mx = useMatrixClient();
const userId = mx.getUserId()!;
const profile = useUserProfile(userId);
return (
<Box direction="Column" gap="700">
<Box direction="Column" gap="100">
@@ -20,6 +20,12 @@ export interface UseProcessedTimelineOptions {
hideNickAvatarEvents: boolean;
isReadOnly: boolean;
hideMemberInReadOnly: boolean;
/**
* When true, skip the filter that removes events whose `threadRootId` points
* to a different event. Required when processing a thread's own timeline
* where every reply legitimately has `threadRootId` set to the root.
*/
skipThreadFilter?: boolean;
}
export interface ProcessedEvent {
@@ -55,6 +61,7 @@ export function useProcessedTimeline({
hideNickAvatarEvents,
isReadOnly,
hideMemberInReadOnly,
skipThreadFilter,
}: UseProcessedTimelineOptions): ProcessedEvent[] {
return useMemo(() => {
let prevEvent: MatrixEvent | undefined;
@@ -116,7 +123,7 @@ export function useProcessedTimeline({
}
}
if (threadRootId !== undefined && threadRootId !== mEventId) return acc;
if (!skipThreadFilter && threadRootId !== undefined && threadRootId !== mEventId) return acc;
const isReactionOrEdit = reactionOrEditEvent(mEvent);
if (isReactionOrEdit) return acc;
@@ -193,5 +200,6 @@ export function useProcessedTimeline({
hideNickAvatarEvents,
isReadOnly,
hideMemberInReadOnly,
skipThreadFilter,
]);
}
+3 -25
View File
@@ -5,13 +5,12 @@ import { ReactEditor } from 'slate-react';
import { getMxIdLocalPart, toggleReaction } from '$utils/matrix';
import { getMemberDisplayName, getEditedEvent } from '$utils/room';
import { createMentionElement, isEmptyEditor, moveCursor } from '$components/editor';
import { createMentionElement, moveCursor } from '$components/editor';
export interface UseTimelineActionsOptions {
room: Room;
mx: MatrixClient;
editor: Editor;
alive: () => boolean;
nicknames: Record<string, string>;
globalProfiles: Record<string, any>;
spaceId?: string;
@@ -27,8 +26,7 @@ export interface UseTimelineActionsOptions {
setReplyDraft: (draft: any) => void;
openThreadId?: string;
setOpenThread: (threadId: string | undefined) => void;
setEditId: (editId: string | undefined) => void;
onEditorReset?: () => void;
handleEdit: (editId?: string) => void;
handleOpenEvent: (eventId: string) => void;
}
@@ -36,7 +34,6 @@ export function useTimelineActions({
room,
mx,
editor,
alive,
nicknames,
globalProfiles,
spaceId,
@@ -45,8 +42,7 @@ export function useTimelineActions({
setReplyDraft,
openThreadId,
setOpenThread,
setEditId,
onEditorReset,
handleEdit,
handleOpenEvent,
}: UseTimelineActionsOptions) {
const handleOpenReply: MouseEventHandler<HTMLButtonElement> = useCallback(
@@ -209,24 +205,6 @@ export function useTimelineActions({
[mx]
);
const handleEdit = useCallback(
(targetEditId?: string) => {
if (targetEditId) {
setEditId(targetEditId);
return;
}
setEditId(undefined);
requestAnimationFrame(() => {
if (!alive()) return;
if (isEmptyEditor(editor)) onEditorReset?.();
ReactEditor.focus(editor);
moveCursor(editor);
});
},
[editor, alive, onEditorReset, setEditId]
);
return {
handleOpenReply,
handleUserClick,
@@ -1,10 +1,14 @@
import { MouseEventHandler, useCallback, useMemo } from 'react';
import { MouseEventHandler, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAtomValue } from 'jotai';
import {
IThreadBundledRelationship,
MatrixClient,
MatrixEvent,
NotificationCountType,
Room,
RoomEvent,
ThreadEvent,
PushProcessor,
EventTimelineSet,
IContent,
@@ -47,6 +51,7 @@ import {
} from '$utils/room';
import { getLinkedTimelines, getLiveTimeline } from '$utils/timeline';
import * as customHtmlCss from '$styles/CustomHtml.css';
import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge';
import {
EncryptedContent,
Event,
@@ -105,20 +110,49 @@ function ThreadReplyChip({
const useAuthentication = useMediaAuthentication();
const nicknames = useAtomValue(nicknamesAtom);
const [counter, forceUpdate] = useState(0);
const thread = room.getThread(mEventId);
useEffect(() => {
if (!thread) return () => {};
const onUpdate = () => forceUpdate((n) => n + 1);
thread.on(ThreadEvent.NewReply as any, onUpdate);
thread.on(ThreadEvent.Update as any, onUpdate);
room.on(RoomEvent.Redaction as any, onUpdate);
return () => {
thread.off(ThreadEvent.NewReply as any, onUpdate);
thread.off(ThreadEvent.Update as any, onUpdate);
room.off(RoomEvent.Redaction as any, onUpdate);
};
}, [room, thread]);
const replyEvents = useMemo(() => {
// With threadSupport:true, reply events live in thread.timelineSet not the main room timeline.
// Prefer thread.events when available so avatars and preview text are populated.
if (thread) {
const fromThread = thread.events.filter(
(ev) => ev.getId() !== mEventId && !reactionOrEditEvent(ev)
);
if (fromThread.length > 0) return fromThread;
}
const linkedTimelines = getLinkedTimelines(getLiveTimeline(room));
return linkedTimelines
.flatMap((tl) => tl.getEvents())
.filter(
(ev) => ev.threadRootId === mEventId && ev.getId() !== mEventId && !reactionOrEditEvent(ev)
);
}, [room, mEventId]);
// eslint-disable-next-line react-hooks/exhaustive-deps -- counter is a cache-busting key, not used directly in body
}, [room, mEventId, thread, counter]);
if (!thread) return null;
const replyCount = thread.length ?? 0;
// Prefer the server-authoritative bundled count. thread.length only reflects
// events fetched into the local timeline, which can be much lower than the
// true total before the thread drawer is first opened and paginated.
const bundledCount =
thread.rootEvent?.getServerAggregatedRelation<IThreadBundledRelationship>('m.thread')?.count;
const replyCount = bundledCount ?? thread.length ?? 0;
if (replyCount === 0) return null;
const uniqueSenders: string[] = [];
@@ -146,6 +180,12 @@ function ThreadReplyChip({
const isOpen = openThreadId === mEventId;
const unreadTotal = room.getThreadUnreadNotificationCount(mEventId, NotificationCountType.Total);
const unreadHighlight = room.getThreadUnreadNotificationCount(
mEventId,
NotificationCountType.Highlight
);
return (
<Chip
size="400"
@@ -201,6 +241,11 @@ function ThreadReplyChip({
&nbsp;·&nbsp;{latestSenderName}:&nbsp;{latestBody.slice(0, 60)}
</Text>
)}
{unreadTotal > 0 && (
<UnreadBadgeCenter>
<UnreadBadge highlight={unreadHighlight > 0} count={unreadTotal} />
</UnreadBadgeCenter>
)}
</Chip>
);
}
@@ -227,6 +272,7 @@ export interface TimelineEventRendererOptions {
hideMembershipEvents: boolean;
hideNickAvatarEvents: boolean;
showHiddenEvents: boolean;
hideThreadChip?: boolean;
};
state: {
focusItem?: { index: number; highlight: boolean; scrollTo: boolean };
@@ -282,6 +328,7 @@ export function useTimelineEventRenderer({
hideMembershipEvents,
hideNickAvatarEvents,
showHiddenEvents,
hideThreadChip,
},
state: { focusItem, editId, activeReplyId, openThreadId },
permissions: { canRedact, canDeleteOwn, canSendReaction, canPinEvent },
@@ -311,9 +358,16 @@ export function useTimelineEventRenderer({
isRedacted,
getUnsigned,
getTs,
replyEventId,
getWireContent,
replyEventId: rawReplyEventId,
threadRootId,
} = mEvent;
// In the thread drawer (hideThreadChip=true), suppress reply headers for events
// that only have m.in_reply_to as a non-thread-client fallback (is_falling_back: true).
const replyEventId =
hideThreadChip && getWireContent.call(mEvent)?.['m.relates_to']?.is_falling_back
? undefined
: rawReplyEventId;
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations?.getSortedAnnotationsByKey();
@@ -402,7 +456,7 @@ export function useTimelineEventRenderer({
room={room}
timelineSet={timelineSet}
replyEventId={replyEventId}
threadRootId={threadRootId}
threadRootId={hideThreadChip ? undefined : threadRootId}
mentions={baseContent['m.mentions']}
onClick={handleOpenReply}
/>
@@ -410,7 +464,7 @@ export function useTimelineEventRenderer({
}
reactions={(() => {
const threadChip =
room.getThread(mEventId) || threadRootId ? (
!hideThreadChip && (room.getThread(mEventId) || threadRootId) ? (
<ThreadReplyChip
room={room}
mEventId={mEventId}
@@ -472,9 +526,14 @@ export function useTimelineEventRenderer({
getContent: getEventContent,
getOriginalContent,
getTs,
replyEventId,
getWireContent,
replyEventId: rawReplyEventId,
threadRootId,
} = mEvent;
const replyEventId =
hideThreadChip && getWireContent.call(mEvent)?.['m.relates_to']?.is_falling_back
? undefined
: rawReplyEventId;
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations?.getSortedAnnotationsByKey();
@@ -525,14 +584,14 @@ export function useTimelineEventRenderer({
room={room}
timelineSet={timelineSet}
replyEventId={replyEventId}
threadRootId={threadRootId}
threadRootId={hideThreadChip ? undefined : threadRootId}
onClick={handleOpenReply}
/>
)
}
reactions={(() => {
const threadChip =
room.getThread(mEventId) || threadRootId ? (
!hideThreadChip && (room.getThread(mEventId) || threadRootId) ? (
<ThreadReplyChip
room={room}
mEventId={mEventId}
@@ -642,9 +701,14 @@ export function useTimelineEventRenderer({
isRedacted,
getUnsigned,
getContent: getEventContent,
replyEventId,
getWireContent,
replyEventId: rawReplyEventId,
threadRootId,
} = mEvent;
const replyEventId =
hideThreadChip && getWireContent.call(mEvent)?.['m.relates_to']?.is_falling_back
? undefined
: rawReplyEventId;
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations?.getSortedAnnotationsByKey();
@@ -687,7 +751,7 @@ export function useTimelineEventRenderer({
room={room}
timelineSet={timelineSet}
replyEventId={replyEventId}
threadRootId={threadRootId}
threadRootId={hideThreadChip ? undefined : threadRootId}
mentions={content['m.mentions']}
onClick={handleOpenReply}
/>
@@ -695,7 +759,7 @@ export function useTimelineEventRenderer({
}
reactions={(() => {
const threadChip =
room.getThread(mEventId) || threadRootId ? (
!hideThreadChip && (room.getThread(mEventId) || threadRootId) ? (
<ThreadReplyChip
room={room}
mEventId={mEventId}
+49
View File
@@ -0,0 +1,49 @@
import { useState, useCallback, useRef } from 'react';
import { Editor } from 'slate';
import { ReactEditor } from 'slate-react';
import { isEmptyEditor, moveCursor } from '$components/editor';
export interface UseMessageEditOptions {
onReset?: () => void;
alive?: () => boolean;
}
/**
* Manages the "edit mode" state for a message composer.
*
* Centralises the `editId` state and the `handleEdit` callback so both
* `RoomTimeline` and `ThreadDrawer` share identical behaviour: setting an
* edit target activates the editor for that event; clearing it resets the
* editor and returns focus.
*/
export function useMessageEdit(
editor: Editor,
options?: UseMessageEditOptions
): { editId: string | undefined; handleEdit: (editId?: string) => void } {
const [editId, setEditId] = useState<string | undefined>(undefined);
// Use refs so the callback never goes stale on options changes.
const aliveRef = useRef(options?.alive);
aliveRef.current = options?.alive;
const onResetRef = useRef(options?.onReset);
onResetRef.current = options?.onReset;
const handleEdit = useCallback(
(targetEditId?: string) => {
if (targetEditId) {
setEditId(targetEditId);
return;
}
setEditId(undefined);
requestAnimationFrame(() => {
if (aliveRef.current && !aliveRef.current()) return;
if (onResetRef.current && isEmptyEditor(editor)) onResetRef.current();
ReactEditor.focus(editor);
moveCursor(editor);
});
},
[editor]
);
return { editId, handleEdit };
}
+30 -7
View File
@@ -9,6 +9,7 @@ import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { MSC1767Text } from '$types/matrix/common';
import { useMatrixClient } from './useMatrixClient';
import { ThemeKind, useActiveTheme } from './useTheme';
const inFlightProfiles = new Map<string, Promise<any>>();
@@ -25,6 +26,8 @@ export type UserProfile = {
status?: string;
bannerUrl?: string;
nameColor?: string;
nameColorDark?: string;
nameColorLight?: string;
isCat?: boolean;
hasCats?: boolean;
extended?: Record<string, any>;
@@ -45,6 +48,8 @@ const normalizeInfo = (info: any): UserProfile => {
'chat.commet.profile_banner',
'chat.commet.profile_status',
'moe.sable.app.name_color',
'moe.sable.app.name_color_dark_theme',
'moe.sable.app.name_color_light_theme',
'kitty.meow.has_cats',
'kitty.meow.is_cat',
]);
@@ -68,6 +73,8 @@ const normalizeInfo = (info: any): UserProfile => {
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
nameColorDark: info['moe.sable.app.name_color_dark_theme'],
nameColorLight: info['moe.sable.app.name_color_light_theme'],
isCat: info['kitty.meow.is_cat'] === true,
hasCats: info['kitty.meow.has_cats'] === true,
extended,
@@ -98,6 +105,7 @@ export const useUserProfile = (
const [renderGlobalColors] = useSetting(settingsAtom, 'renderGlobalNameColors');
const [renderRoomColors] = useSetting(settingsAtom, 'renderRoomColors');
const [renderRoomFonts] = useSetting(settingsAtom, 'renderRoomFonts');
const themeKind = useActiveTheme().kind;
const userSelector = useMemo(() => selectAtom(profilesCacheAtom, (db) => db[userId]), [userId]);
@@ -202,12 +210,26 @@ export const useUserProfile = (
}
}
const validGlobalVal = isValidHex(data?.nameColor);
const validGlobalValDark = isValidHex(data?.nameColorDark);
const validGlobalValLight = isValidHex(data?.nameColorLight);
const hasGlobalColor = !!validGlobalVal;
const validGlobal =
(renderGlobalColors || userId === mx.getUserId()) && hasGlobalColor
const validGlobalGeneral =
(renderGlobalColors || userId === mx.getUserId()) && !!validGlobalVal
? validGlobalVal
: undefined;
const validGlobalDark =
(renderGlobalColors || userId === mx.getUserId()) &&
themeKind === ThemeKind.Dark &&
!!validGlobalValDark
? validGlobalValDark
: undefined;
const validGlobalLight =
(renderGlobalColors || userId === mx.getUserId()) &&
themeKind === ThemeKind.Light &&
!!validGlobalValLight
? validGlobalValLight
: undefined;
const validGlobal = validGlobalDark ?? validGlobalLight ?? validGlobalGeneral;
const validLocal = localColor && isValidHex(localColor) ? localColor : undefined;
const validSpace = spaceColor && isValidHex(spaceColor) ? spaceColor : undefined;
@@ -237,13 +259,14 @@ export const useUserProfile = (
};
}, [
cached,
initialProfile,
mx,
userId,
room,
mx,
legacyUsernameColor,
renderGlobalColors,
initialProfile,
renderRoomColors,
renderRoomFonts,
renderGlobalColors,
themeKind,
legacyUsernameColor,
]);
};
+1 -3
View File
@@ -41,10 +41,9 @@ export function WelcomePage() {
Source Code
</Text>
</Button>
{/*
<Button
as="a"
href="https://github.com/SableClient/Sable"
href="https://opencollective.com/sable"
target="_blank"
rel="noreferrer noopener"
fill="Soft"
@@ -54,7 +53,6 @@ export function WelcomePage() {
Support
</Text>
</Button>
*/}
</Box>
</Box>
<Box direction="Column" gap="200" alignItems="Center">
+4 -1
View File
@@ -82,7 +82,10 @@ export function DirectTab() {
const handleDirectClick = () => {
const activePath = navToActivePath.get('direct');
if (activePath && screenSize !== ScreenSize.Mobile) {
const activePathname = activePath?.pathname;
const isValidDirectPath =
typeof activePathname === 'string' && activePathname.startsWith('/direct/');
if (activePath && isValidDirectPath && screenSize !== ScreenSize.Mobile) {
navigate(joinPathComponent(activePath));
return;
}
+3 -1
View File
@@ -40,7 +40,9 @@ globalStyle(
button[class*="_1684mq51"]:has(img):hover,
[data-index] [class*="_1r9nvaso"]:hover,
[data-index] [class*="_1r9nvaso"] *:hover,
[data-index] button:has(p):hover
[data-index] button:has(p):hover,
[data-index] button:hover,
[data-index] [role="button"]:hover
`,
{
transform: 'none !important',
+2
View File
@@ -429,6 +429,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
await mx.startClient({
lazyLoadMembers: true,
pollTimeout: FAST_SYNC_POLL_TIMEOUT_MS,
threadSupport: true,
});
// Attach an ongoing classic-sync observer — equivalent to SlidingSyncManager's
// onLifecycle listener. Tracks state transitions, initial-sync timing, and errors.
@@ -581,6 +582,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
await mx.startClient({
lazyLoadMembers: true,
slidingSync: manager.slidingSync,
threadSupport: true,
});
} catch (err) {
debugLog.error('network', 'Failed to start client with sliding sync', {
+1
View File
@@ -78,6 +78,7 @@
html {
height: 100%;
overflow: hidden;
overscroll-behavior: none;
}
body {