fix forums not opening in forum view & formatting fixes (#1839)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Seems to fix threads not working. About half of this was on an old
branch i had from like a month ago that i updated. Ensures forum rooms
actually open the forum view and should fix some random issues i had
with threads loading.

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [x] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->

I think the original changes from a month ago were ai generated, but
I've looked through and manually updated and copied things over and
everything seems logical and works in my testing
This commit is contained in:
7w1 authored and GitHub committed 2026-08-17 18:22:36 -05:00
commit 4701506eae
22 files changed
+550 -137

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix forum rooms opening in the normal chat view and improve forum post and thread navigation.
+1 -1
View File
@@ -5459,7 +5459,7 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "sable"
version = "1.20.0"
version = "1.21.0"
dependencies = [
"aes",
"async-stream",
+4 -12
View File
@@ -64,9 +64,7 @@
},
"plugins": {
"updater": {
"endpoints": [
"https://github.com/SableClient/Sable/releases/latest/download/latest.json"
],
"endpoints": ["https://github.com/SableClient/Sable/releases/latest/download/latest.json"],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEM0NDc2QkI0NjdCODlEQUUKUldTdW5iaG50R3RIeFBQeGFwcDZNcGhCQ2Y4UFgzVnptRmNRZjRoVDl0MkdOZmREdC9pTUZrZnAK"
},
"typegen": {
@@ -80,17 +78,11 @@
},
"deep-link": {
"desktop": {
"schemes": [
"sable",
"moe.sable.app"
]
"schemes": ["sable", "moe.sable.app"]
},
"mobile": [
{
"scheme": [
"sable",
"moe.sable.app"
],
"scheme": ["sable", "moe.sable.app"],
"appLink": false
}
]
@@ -112,4 +104,4 @@
]
}
}
}
}
+16 -2
View File
@@ -3,7 +3,14 @@ import { useCallback } from 'react';
import { useSetAtom } from 'jotai';
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
import { resolveSection } from '$pages/pathUtils';
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
import {
DIRECT_ROOM_FORUM_PATH,
DIRECT_ROOM_PATH,
HOME_ROOM_FORUM_PATH,
HOME_ROOM_PATH,
SPACE_ROOM_FORUM_PATH,
SPACE_ROOM_PATH,
} from '$pages/paths';
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
import { isRoomAlias, isRoomId } from '$utils/matrix';
import { useAndroidBackHandler } from '$utils/androidBack';
@@ -21,7 +28,14 @@ export function useBackRoute(): () => void {
const section = resolveSection(location.pathname);
if (!section) return;
const roomPaths = [HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH];
const roomPaths = [
HOME_ROOM_FORUM_PATH,
DIRECT_ROOM_FORUM_PATH,
SPACE_ROOM_FORUM_PATH,
HOME_ROOM_PATH,
DIRECT_ROOM_PATH,
SPACE_ROOM_PATH,
];
const roomMatch = roomPaths
.map((path) => matchPath({ path, end: false }, location.pathname))
.find((match) => match !== null);
+30 -5
View File
@@ -17,17 +17,27 @@ import { roomToUnreadAtom } from '$state/room/roomToUnread';
import { useKeyDown } from '$hooks/useKeyDown';
import {
getDirectRoomPath,
getDirectForumPath,
getCreateRoomPath,
getHomeForumPath,
getHomeRoomPath,
getHomeSearchPath,
getInboxBookmarksPath,
getNavigatePath,
getSpaceRoomPath,
getSpaceForumPath,
getSpaceSearchPath,
withSearchParam,
} from '$pages/pathUtils';
import type { SearchPathSearchParams } from '$pages/paths';
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
import {
DIRECT_ROOM_FORUM_PATH,
DIRECT_ROOM_PATH,
HOME_ROOM_FORUM_PATH,
HOME_ROOM_PATH,
SPACE_ROOM_FORUM_PATH,
SPACE_ROOM_PATH,
} from '$pages/paths';
import { getCanonicalAliasOrRoomId } from '$utils/matrix';
import { announce } from '$utils/announce';
import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts';
@@ -35,6 +45,7 @@ import type { Room } from '$types/matrix-sdk';
import { useSelectedSpace } from '$hooks/router/useSelectedSpace';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { CustomRoomType } from '$types/matrix/room';
import { useOpenShallowRoute } from '$pages/client/useShallowRoute';
import { matchesShortcut } from '../keyboard/shortcuts';
@@ -51,6 +62,9 @@ export function GlobalKeyboardShortcuts() {
// Derive the current room ID from the URL so we know which room is active.
const roomMatch =
matchPath(HOME_ROOM_FORUM_PATH, location.pathname) ??
matchPath(DIRECT_ROOM_FORUM_PATH, location.pathname) ??
matchPath(SPACE_ROOM_FORUM_PATH, location.pathname) ??
matchPath(HOME_ROOM_PATH, location.pathname) ??
matchPath(DIRECT_ROOM_PATH, location.pathname) ??
matchPath(SPACE_ROOM_PATH, location.pathname);
@@ -76,20 +90,31 @@ export function GlobalKeyboardShortcuts() {
(roomId: string, remaining: number) => {
const roomIdOrAliasToNav = getCanonicalAliasOrRoomId(mx, roomId);
const isDirect = mDirects.has(roomId);
const isForum = mx.getRoom(roomId)?.getType() === CustomRoomType.Forum;
if (isDirect) {
navigate(getDirectRoomPath(roomIdOrAliasToNav));
navigate(
isForum ? getDirectForumPath(roomIdOrAliasToNav) : getDirectRoomPath(roomIdOrAliasToNav)
);
} else {
const parents = roomToParents.get(roomId);
if (parents && parents.size > 0) {
const spaceId = Array.from(parents)[0];
if (!spaceId) {
navigate(getHomeRoomPath(roomIdOrAliasToNav));
navigate(
isForum ? getHomeForumPath(roomIdOrAliasToNav) : getHomeRoomPath(roomIdOrAliasToNav)
);
return;
}
const spaceIdOrAlias = getCanonicalAliasOrRoomId(mx, spaceId);
navigate(getSpaceRoomPath(spaceIdOrAlias, roomIdOrAliasToNav));
navigate(
isForum
? getSpaceForumPath(spaceIdOrAlias, roomIdOrAliasToNav)
: getSpaceRoomPath(spaceIdOrAlias, roomIdOrAliasToNav)
);
} else {
navigate(getHomeRoomPath(roomIdOrAliasToNav));
navigate(
isForum ? getHomeForumPath(roomIdOrAliasToNav) : getHomeRoomPath(roomIdOrAliasToNav)
);
}
}
const roomName = mx.getRoom(roomId)?.name ?? 'Room';
@@ -15,12 +15,15 @@ import { usePrefersReducedMotion } from '$hooks/usePrefersReducedMotion';
import {
DIRECT_PATH,
DIRECT_ROOM_PATH,
DIRECT_ROOM_FORUM_PATH,
EXPLORE_PATH,
HOME_PATH,
HOME_ROOM_PATH,
HOME_ROOM_FORUM_PATH,
INBOX_PATH,
SPACE_PATH,
SPACE_ROOM_PATH,
SPACE_ROOM_FORUM_PATH,
} from '$pages/paths';
import { resolveSection } from '$pages/pathUtils';
import { isRoomAlias, isRoomId } from '$utils/matrix';
@@ -67,6 +70,9 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
);
const roomMatch =
matchPath({ path: HOME_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: DIRECT_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: SPACE_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: HOME_ROOM_PATH, end: false }, location.pathname) ??
matchPath({ path: DIRECT_ROOM_PATH, end: false }, location.pathname) ??
matchPath({ path: SPACE_ROOM_PATH, end: false }, location.pathname);
+11 -1
View File
@@ -8,7 +8,14 @@ import { DirectRouteRoomProvider } from '$pages/client/direct';
import { SpaceRouteRoomProvider } from '$pages/client/space';
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
import { resolveSection, type SectionNav } from '$pages/pathUtils';
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
import {
DIRECT_ROOM_PATH,
DIRECT_ROOM_FORUM_PATH,
HOME_ROOM_PATH,
HOME_ROOM_FORUM_PATH,
SPACE_ROOM_PATH,
SPACE_ROOM_FORUM_PATH,
} from '$pages/paths';
import { isRoomAlias, isRoomId } from '$utils/matrix';
type DisplayedRoom = {
@@ -23,6 +30,9 @@ function useDisplayedRoom(section: SectionNav | null): DisplayedRoom | undefined
if (!section || !section.getRoomPath) return undefined;
const roomMatch =
matchPath({ path: HOME_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: DIRECT_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: SPACE_ROOM_FORUM_PATH, end: false }, location.pathname) ??
matchPath({ path: HOME_ROOM_PATH, end: false }, location.pathname) ??
matchPath({ path: DIRECT_ROOM_PATH, end: false }, location.pathname) ??
matchPath({ path: SPACE_ROOM_PATH, end: false }, location.pathname);
+60 -59
View File
@@ -62,66 +62,67 @@ export function ForumThreadItem({ thread, onClick, ...rootProps }: ForumThreadIt
<Box direction="Column" grow="Yes" style={{ minWidth: 0 }}>
<ThreadRootItem {...rootProps} thread={thread} hideReplyButton />
{/* Thread reply chip */}
<Box style={{ paddingLeft: config.space.S700, paddingTop: config.space.S100 }}>
<Chip
as="button"
style={{ alignSelf: 'flex-start' }}
size="400"
variant="SurfaceVariant"
radii="300"
onClick={(evt: React.MouseEvent) => {
evt.stopPropagation();
onClick(mEventId);
}}
before={
uniqueSenders.length > 0 ? (
<Box alignItems="Center" style={{ gap: 0 }}>
{uniqueSenders.slice(0, 3).map((sid, index) => {
const avatarMxc = getMemberAvatarMxc(room, sid);
const avatarUrl = avatarMxc
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 20, 20, 'crop') ??
undefined)
: undefined;
const dn =
getMemberDisplayName(room, sid, nicknames) ?? getMxIdLocalPart(sid) ?? sid;
return (
<Avatar key={sid} size="200" style={{ marginLeft: index > 0 ? '-4px' : 0 }}>
<UserAvatar
userId={sid}
src={avatarUrl}
alt={dn}
renderFallback={() => (
<span style={{ fontSize: '10px', fontWeight: 'bold', lineHeight: 1 }}>
{dn[0]?.toUpperCase() ?? '?'}
</span>
)}
/>
</Avatar>
);
})}
</Box>
) : undefined
}
>
<Text size="T300" style={{ whiteSpace: 'nowrap' }}>
{replyCount}&nbsp;{replyCount === 1 ? 'reply' : 'replies'}
</Text>
{lastBody && (
<Text
size="T300"
style={{
opacity: 0.7,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
&nbsp;·&nbsp;{lastDisplayName}:&nbsp;{lastBody.slice(0, 60)}
{replyCount > 0 && (
<Box style={{ paddingLeft: config.space.S700, paddingTop: config.space.S100 }}>
<Chip
as="button"
style={{ alignSelf: 'flex-start' }}
size="400"
variant="SurfaceVariant"
radii="300"
onClick={(evt: React.MouseEvent) => {
evt.stopPropagation();
onClick(mEventId);
}}
before={
uniqueSenders.length > 0 ? (
<Box alignItems="Center" style={{ gap: 0 }}>
{uniqueSenders.slice(0, 3).map((sid, index) => {
const avatarMxc = getMemberAvatarMxc(room, sid);
const avatarUrl = avatarMxc
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 20, 20, 'crop') ??
undefined)
: undefined;
const dn =
getMemberDisplayName(room, sid, nicknames) ?? getMxIdLocalPart(sid) ?? sid;
return (
<Avatar key={sid} size="200" style={{ marginLeft: index > 0 ? '-4px' : 0 }}>
<UserAvatar
userId={sid}
src={avatarUrl}
alt={dn}
renderFallback={() => (
<span style={{ fontSize: '10px', fontWeight: 'bold', lineHeight: 1 }}>
{dn[0]?.toUpperCase() ?? '?'}
</span>
)}
/>
</Avatar>
);
})}
</Box>
) : undefined
}
>
<Text size="T300" style={{ whiteSpace: 'nowrap' }}>
{replyCount}&nbsp;{replyCount === 1 ? 'reply' : 'replies'}
</Text>
)}
</Chip>
</Box>
{lastBody && (
<Text
size="T300"
style={{
opacity: 0.7,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
&nbsp;·&nbsp;{lastDisplayName}:&nbsp;{lastBody.slice(0, 60)}
</Text>
)}
</Chip>
</Box>
)}
</Box>
</Box>
);
+94
View File
@@ -0,0 +1,94 @@
/* oxlint-disable typescript/no-explicit-any */
import { describe, expect, it } from 'vitest';
import { EventType, RelationType } from '$types/matrix-sdk';
import { collectForumPosts } from './ForumView';
type EventInit = {
id: string;
ts: number;
type?: string;
content?: Record<string, unknown>;
relation?: { rel_type?: string; event_id?: string };
redacted?: boolean;
};
const makeEvent = ({
id,
ts,
type = EventType.RoomMessage,
content = { msgtype: 'm.text', body: id },
relation,
redacted = false,
}: EventInit) => ({
getId: () => id,
getTs: () => ts,
getType: () => type,
getContent: () => content,
getRelation: () => relation ?? null,
isRedacted: () => redacted,
isState: () => false,
});
const makeRoom = ({
threads = [],
timelines = [[]],
}: {
threads?: Array<{
id: string;
rootEvent: ReturnType<typeof makeEvent>;
events: ReturnType<typeof makeEvent>[];
}>;
timelines?: Array<ReturnType<typeof makeEvent>[]>;
}) => ({
getThreads: () => threads,
getUnfilteredTimelineSet: () => ({
getTimelines: () => timelines.map((events) => ({ getEvents: () => events })),
}),
});
describe('collectForumPosts', () => {
it('collects posts across linked timelines and excludes thread and legacy replies', () => {
const root = makeEvent({ id: '$root', ts: 1 });
const threadReply = makeEvent({
id: '$thread-reply',
ts: 3,
relation: { rel_type: RelationType.Thread, event_id: '$root' },
});
const legacyReply = makeEvent({
id: '$legacy-reply',
ts: 4,
content: {
msgtype: 'm.text',
body: 'reply',
'm.relates_to': { ['m.in_reply_to']: { event_id: '$root' } },
},
});
const olderPost = makeEvent({ id: '$older', ts: 2 });
const posts = collectForumPosts(
makeRoom({
threads: [{ id: '$root', rootEvent: root, events: [root, threadReply] }],
timelines: [
[root, threadReply],
[legacyReply, olderPost],
],
}) as any
);
expect(posts.map((post) => post.eventId)).toEqual(['$root', '$older']);
});
it('keeps encrypted messages as forum posts', () => {
const encryptedPost = makeEvent({
id: '$encrypted',
ts: 1,
type: EventType.RoomMessageEncrypted,
content: { algorithm: 'm.megolm.v1.aes-sha2' },
});
const posts = collectForumPosts(makeRoom({ timelines: [[encryptedPost]] }) as any);
expect(posts.map((post) => post.eventId)).toEqual(['$encrypted']);
});
});
+145 -20
View File
@@ -1,6 +1,6 @@
import type { MouseEventHandler } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, IconButton, Line, Scroll, Text, color, config } from 'folds';
import { Box, Button, IconButton, Line, Scroll, Text, color, config } from 'folds';
import { useAtom, useAtomValue } from 'jotai';
import type { EventTimeline, MatrixEvent, Room } from 'matrix-js-sdk';
import { Direction, EventType, RoomEvent } from 'matrix-js-sdk';
@@ -9,7 +9,7 @@ import type { Thread } from 'matrix-js-sdk/lib/models/thread';
import { ThreadEvent } from 'matrix-js-sdk/lib/models/thread';
import type { HTMLReactParserOptions } from 'html-react-parser';
import type { Opts as LinkifyOpts } from 'linkifyjs';
import { useRoom } from '$hooks/useRoom';
import { useDisplayedEventId, useRoom } from '$hooks/useRoom';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { Page, PageContent, PageContentCenter, PageHeroSection } from '$components/page';
import { CaretUp, Chats, composerIcon, sizedIcon } from '$components/icons/phosphor';
@@ -63,7 +63,25 @@ type ForumPost = {
* Collect all top-level messages (not thread replies, not reactions/edits/redacted)
* and return them as ForumPost items, sorted by latest activity descending.
*/
const collectForumPosts = (room: Room): ForumPost[] => {
const isPlainReplyEvent = (event: MatrixEvent): boolean => {
const content = event.getContent<Record<string, unknown>>();
const relation = content['m.relates_to'];
if (relation && typeof relation === 'object') {
const inReplyTo = (relation as { ['m.in_reply_to']?: unknown })['m.in_reply_to'];
if (inReplyTo && typeof inReplyTo === 'object') {
return typeof (inReplyTo as { event_id?: unknown }).event_id === 'string';
}
}
const inReplyTo = content['m.in_reply_to'];
return (
!!inReplyTo &&
typeof inReplyTo === 'object' &&
typeof (inReplyTo as { event_id?: unknown }).event_id === 'string'
);
};
export const collectForumPosts = (room: Room): ForumPost[] => {
const threadMap = new Map<string, Thread>();
room.getThreads().forEach((thread) => {
threadMap.set(thread.id, thread);
@@ -89,17 +107,25 @@ const collectForumPosts = (room: Room): ForumPost[] => {
});
});
// Add top-level timeline messages that are NOT thread replies
const timeline = room.getLiveTimeline();
timeline.getEvents().forEach((ev) => {
const events = room
.getUnfilteredTimelineSet()
.getTimelines()
.flatMap((timeline) => timeline.getEvents());
events.forEach((ev) => {
const evId = ev.getId();
if (!evId) return;
if (posts.has(evId)) return; // already added as thread root
if (ev.isRedacted()) return;
if (reactionOrEditEvent(ev)) return;
// Skip actual thread replies (rel_type: m.thread), but keep plain replies
// that just reference a thread root via m.in_reply_to
if (
ev.getType() !== (EventType.RoomMessage as string) &&
ev.getType() !== (EventType.RoomMessageEncrypted as string) &&
ev.getType() !== (EventType.Sticker as string)
) {
return;
}
if (ev.getRelation()?.rel_type === 'm.thread') return;
if (isPlainReplyEvent(ev)) return;
if (ev.isState()) return; // skip state events
posts.set(evId, {
@@ -117,6 +143,7 @@ const collectForumPosts = (room: Room): ForumPost[] => {
export function ForumView() {
const mx = useMatrixClient();
const room = useRoom();
const eventId = useDisplayedEventId();
const powerLevels = usePowerLevels(room);
const members = useRoomMembers(mx, room.roomId);
@@ -138,6 +165,10 @@ export function ForumView() {
const [openThreadId, setOpenThread] = useAtom(roomIdToOpenThreadAtomFamily(room.roomId));
const [updateKey, forceUpdate] = useState(0);
const [editId, setEditId] = useState<string | undefined>(undefined);
const [loadingOlderPosts, setLoadingOlderPosts] = useState(false);
const [canLoadOlderPosts, setCanLoadOlderPosts] = useState(
() => room.getLiveTimeline().getPaginationToken(Direction.Backward) !== null
);
// Settings
const [messageLayout] = useSetting(settingsAtom, 'messageLayout');
@@ -238,17 +269,71 @@ export function ForumView() {
backwardTimeline = backwardTimeline.getNeighbouringTimeline(Direction.Backward);
}
// Initialize thread timeline sets then fetch threads from server
room
.createThreadsTimelineSets()
.then(() => room.fetchRoomThreads())
.then(() => {
forceUpdate((n) => n + 1);
})
.catch(() => {
// Silently ignore — server may not support threads
let cancelled = false;
const loadThreads = async () => {
const sets = await room.createThreadsTimelineSets();
const [threadListTimelineSet] = sets ?? [];
if (!threadListTimelineSet || cancelled) return;
await room.fetchRoomThreads();
await mx.paginateEventTimeline(threadListTimelineSet.getLiveTimeline(), {
backwards: true,
});
}, [room]);
threadListTimelineSet
.getLiveTimeline()
.getEvents()
.forEach((rootEvent) => {
const rootId = rootEvent.getId();
if (!rootId) return;
const thread = room.getThread(rootId);
if (!thread) {
room.createThread(rootId, rootEvent, [], false);
} else if (!thread.rootEvent) {
thread.rootEvent = rootEvent;
thread.setEventMetadata(rootEvent);
}
});
if (!cancelled) {
setCanLoadOlderPosts(
room.getLiveTimeline().getPaginationToken(Direction.Backward) !== null
);
forceUpdate((n) => n + 1);
}
};
loadThreads().catch(() => {
// Silently ignore, server may not support threads.
});
return () => {
cancelled = true;
};
}, [mx, room]);
useEffect(() => {
if (!eventId) return;
const event = room.findEventById(eventId);
let threadRootId = event?.threadRootId;
if (!threadRootId && room.getThread(eventId)) {
threadRootId = eventId;
}
if (!threadRootId) {
const thread = room
.getThreads()
.find(
(candidate) =>
candidate.id === eventId || candidate.events.some((ev) => ev.getId() === eventId)
);
threadRootId = thread?.id;
}
if (threadRootId && openThreadId !== threadRootId) {
setOpenThread(threadRootId);
}
}, [eventId, openThreadId, room, setOpenThread, updateKey]);
// Re-render when threads or timeline change
useEffect(() => {
@@ -324,9 +409,29 @@ export function ForumView() {
// eslint-disable-next-line react-hooks/exhaustive-deps
const posts = useMemo(() => collectForumPosts(room), [room, updateKey]);
const handleLoadOlderPosts = useCallback(async () => {
if (loadingOlderPosts || !canLoadOlderPosts) return;
setLoadingOlderPosts(true);
try {
const hasMore = await mx.paginateEventTimeline(room.getLiveTimeline(), {
backwards: true,
limit: 50,
});
setCanLoadOlderPosts(
hasMore && room.getLiveTimeline().getPaginationToken(Direction.Backward) !== null
);
forceUpdate((n) => n + 1);
} catch {
setCanLoadOlderPosts(false);
} finally {
setLoadingOlderPosts(false);
}
}, [canLoadOlderPosts, loadingOlderPosts, mx, room]);
const handleOpenThread = useCallback(
(eventId: string) => {
setOpenThread(eventId);
(postEventId: string) => {
setOpenThread(postEventId);
},
[setOpenThread]
);
@@ -514,6 +619,26 @@ export function ForumView() {
showMaps={showMaps}
/>
))}
{canLoadOlderPosts && (
<Box
alignItems="Center"
justifyContent="Center"
style={{ paddingTop: config.space.S300 }}
>
<Button
size="300"
variant="Secondary"
fill="Soft"
radii="300"
disabled={loadingOlderPosts}
onClick={handleLoadOlderPosts}
>
<Text size="B300">
{loadingOlderPosts ? 'Loading older posts…' : 'Load older posts'}
</Text>
</Button>
</Box>
)}
{posts.length === 0 && (
<Box
direction="Column"
+20 -8
View File
@@ -10,10 +10,18 @@ import { mDirectAtom } from '../state/mDirectList';
import { useSyncState } from './useSyncState';
import { useMatrixClient } from './useMatrixClient';
import { getCanonicalAliasOrRoomId } from '../utils/matrix';
import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '../pages/pathUtils';
import {
getDirectForumPath,
getDirectRoomPath,
getHomeForumPath,
getHomeRoomPath,
getSpaceForumPath,
getSpaceRoomPath,
} from '../pages/pathUtils';
import { getOrphanParents, guessPerfectParent } from '../utils/room/hierarchy';
import { roomToParentsAtom } from '../state/room/roomToParents';
import { createLogger } from '../utils/debug';
import { CustomRoomType } from '$types/matrix/room';
const SUBSCRIPTION_WAIT_TIMEOUT_MS = 10000;
@@ -80,9 +88,12 @@ export function NotificationJumper() {
// Navigate directly to home or direct path — bypasses space routing which
// on mobile shows the space-nav panel first instead of the room timeline.
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, pending.roomId);
const isForum = room?.getType?.() === CustomRoomType.Forum;
let path: string;
if (mDirects.has(pending.roomId)) {
path = getDirectRoomPath(roomIdOrAlias, pending.eventId);
path = isForum
? getDirectForumPath(roomIdOrAlias, pending.eventId)
: getDirectRoomPath(roomIdOrAlias, pending.eventId);
} else {
// If the room lives inside a space, route through the space path so
// SpaceRouteRoomProvider can resolve it — HomeRouteRoomProvider only
@@ -94,13 +105,14 @@ export function NotificationJumper() {
if (orphanParents.length > 0) {
const parentSpace =
guessPerfectParent(mx, pending.roomId, orphanParents) ?? orphanParents[0];
path = getSpaceRoomPath(
getCanonicalAliasOrRoomId(mx, parentSpace ?? pending.roomId),
roomIdOrAlias,
pending.eventId
);
const spaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace ?? pending.roomId);
path = isForum
? getSpaceForumPath(spaceIdOrAlias, roomIdOrAlias, pending.eventId)
: getSpaceRoomPath(spaceIdOrAlias, roomIdOrAlias, pending.eventId);
} else {
path = getHomeRoomPath(roomIdOrAlias, pending.eventId);
path = isForum
? getHomeForumPath(roomIdOrAlias, pending.eventId)
: getHomeRoomPath(roomIdOrAlias, pending.eventId);
}
}
+14 -3
View File
@@ -4,9 +4,12 @@ import { useNavigate } from 'react-router-dom';
import { useAtomValue, useSetAtom } from 'jotai';
import { getCanonicalAliasOrRoomId } from '$utils/matrix';
import {
getDirectForumPath,
getDirectRoomPath,
getHomeForumPath,
getHomeRoomPath,
getSpacePath,
getSpaceForumPath,
getSpaceRoomPath,
resolveSection,
} from '$pages/pathUtils';
@@ -18,6 +21,7 @@ import { settingsAtom } from '$state/settings';
import { useSetting } from '$state/hooks/settings';
import { useSelectedSpace } from './router/useSelectedSpace';
import { useMatrixClient } from './useMatrixClient';
import { CustomRoomType } from '$types/matrix/room';
export const useRoomNavigate = () => {
const navigate = useNavigate();
@@ -40,6 +44,7 @@ export const useRoomNavigate = () => {
(roomId: string, eventId?: string, opts?: NavigateOptions) => {
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, roomId);
const openSpaceTimeline = developerTools && spaceSelectedId === roomId;
const isForum = mx.getRoom(roomId)?.getType() === CustomRoomType.Forum;
const orphanParents = openSpaceTimeline ? [roomId] : getOrphanParents(roomToParents, roomId);
let destPath: string;
@@ -54,13 +59,19 @@ export const useRoomNavigate = () => {
const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace);
roomPart = openSpaceTimeline ? roomId : roomIdOrAlias;
destPath = getSpaceRoomPath(pSpaceIdOrAlias, roomPart, eventId);
destPath = isForum
? getSpaceForumPath(pSpaceIdOrAlias, roomPart, eventId)
: getSpaceRoomPath(pSpaceIdOrAlias, roomPart, eventId);
} else if (mDirects.has(roomId)) {
roomPart = roomIdOrAlias;
destPath = getDirectRoomPath(roomPart, eventId);
destPath = isForum
? getDirectForumPath(roomPart, eventId)
: getDirectRoomPath(roomPart, eventId);
} else {
roomPart = roomIdOrAlias;
destPath = getHomeRoomPath(roomPart, eventId);
destPath = isForum
? getHomeForumPath(roomPart, eventId)
: getHomeRoomPath(roomPart, eventId);
}
const section = resolveSection(destPath);
+9 -3
View File
@@ -11,10 +11,13 @@ import { ClientEvent } from '$types/matrix-sdk';
import { CustomAccountDataEvent } from '$types/matrix/accountData';
import {
DIRECT_ROOM_PATH,
DIRECT_ROOM_FORUM_PATH,
HOME_ROOM_PATH,
HOME_ROOM_FORUM_PATH,
SPACE_LOBBY_PATH,
SPACE_PATH,
SPACE_ROOM_PATH,
SPACE_ROOM_FORUM_PATH,
SPACE_SEARCH_PATH,
} from '$pages/paths';
import { isRoomAlias, isRoomId } from '$utils/matrix';
@@ -31,14 +34,17 @@ const decodeRoomRef = (value: string | undefined): string | undefined => {
};
const getRouteRoomRefs = (pathname: string): RouteRoomRefs => {
const homeRoomMatch = matchPath(HOME_ROOM_PATH, pathname);
const directRoomMatch = matchPath(DIRECT_ROOM_PATH, pathname);
const homeRoomMatch =
matchPath(HOME_ROOM_FORUM_PATH, pathname) ?? matchPath(HOME_ROOM_PATH, pathname);
const directRoomMatch =
matchPath(DIRECT_ROOM_FORUM_PATH, pathname) ?? matchPath(DIRECT_ROOM_PATH, pathname);
const nonSpaceRoomMatch = homeRoomMatch ?? directRoomMatch;
if (nonSpaceRoomMatch) {
return { roomIdOrAlias: decodeRoomRef(nonSpaceRoomMatch.params.roomIdOrAlias) };
}
const spaceRoomMatch = matchPath(SPACE_ROOM_PATH, pathname);
const spaceRoomMatch =
matchPath(SPACE_ROOM_FORUM_PATH, pathname) ?? matchPath(SPACE_ROOM_PATH, pathname);
if (spaceRoomMatch) {
return {
roomIdOrAlias: decodeRoomRef(spaceRoomMatch.params.roomIdOrAlias),
+7 -8
View File
@@ -11,9 +11,7 @@ import * as Sentry from '@sentry/react';
import type { ClientConfig } from '$hooks/useClientConfig';
import { ErrorPage } from '$components/DefaultErrorPage';
import { Room } from '$features/room';
import { Lobby } from '$features/lobby';
import { ForumView } from '$features/forum';
import { PageRoot } from '$components/page';
import { ScreenSize } from '$hooks/useScreenSize';
import { ReceiveSelfDeviceVerification } from '$components/DeviceVerification';
@@ -71,6 +69,7 @@ import {
import { ClientBindAtoms, ClientLayout, ClientRoot, ClientRouteOutlet } from './client';
import { ShallowRouteRenderer } from './client/ShallowRouteRenderer';
import { HandleNotificationClick, ClientNonUIFeatures } from './client/ClientNonUIFeatures';
import { RoomRoute } from './client/RoomRoute';
import { Home, HomeRouteRoomProvider, HomeSearch } from './client/home';
import { Direct, DirectCreate, DirectRouteRoomProvider } from './client/direct';
import { RouteSpaceProvider, Space, SpaceRouteRoomProvider, SpaceSearch } from './client/space';
@@ -315,7 +314,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_PATH_SEGMENT}
element={
<HomeRouteRoomProvider>
<Room />
<RoomRoute section="home" forum={false} />
</HomeRouteRoomProvider>
}
/>
@@ -323,7 +322,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_FORUM_PATH_SEGMENT}
element={
<HomeRouteRoomProvider>
<ForumView />
<RoomRoute section="home" forum />
</HomeRouteRoomProvider>
}
/>
@@ -342,7 +341,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_PATH_SEGMENT}
element={
<DirectRouteRoomProvider>
<Room />
<RoomRoute section="direct" forum={false} />
</DirectRouteRoomProvider>
}
/>
@@ -350,7 +349,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_FORUM_PATH_SEGMENT}
element={
<DirectRouteRoomProvider>
<ForumView />
<RoomRoute section="direct" forum />
</DirectRouteRoomProvider>
}
/>
@@ -391,7 +390,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_PATH_SEGMENT}
element={
<SpaceRouteRoomProvider>
<Room />
<RoomRoute section="space" forum={false} />
</SpaceRouteRoomProvider>
}
/>
@@ -399,7 +398,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
path={ROOM_FORUM_PATH_SEGMENT}
element={
<SpaceRouteRoomProvider>
<ForumView />
<RoomRoute section="space" forum />
</SpaceRouteRoomProvider>
}
/>
+57
View File
@@ -0,0 +1,57 @@
import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ForumView } from '$features/forum';
import { Room } from '$features/room';
import { useRoom } from '$hooks/useRoom';
import {
getDirectForumPath,
getDirectRoomPath,
getHomeForumPath,
getHomeRoomPath,
getSpaceForumPath,
getSpaceRoomPath,
} from '$pages/pathUtils';
import { CustomRoomType } from '$types/matrix/room';
type RoomRouteSection = 'home' | 'direct' | 'space';
type RoomRouteProps = {
section: RoomRouteSection;
forum: boolean;
};
const decodeParam = (value: string | undefined): string | undefined =>
value ? decodeURIComponent(value) : undefined;
export function RoomRoute({ section, forum }: RoomRouteProps) {
const room = useRoom();
const navigate = useNavigate();
const { roomIdOrAlias, spaceIdOrAlias, eventId } = useParams();
const isForum = room.getType() === CustomRoomType.Forum;
useEffect(() => {
if (isForum === forum) return;
const roomRef = decodeParam(roomIdOrAlias);
if (!roomRef) return;
const eventRef = decodeParam(eventId);
let path: string;
if (section === 'space') {
const spaceRef = decodeParam(spaceIdOrAlias);
if (!spaceRef) return;
path = isForum
? getSpaceForumPath(spaceRef, roomRef, eventRef)
: getSpaceRoomPath(spaceRef, roomRef, eventRef);
} else if (section === 'direct') {
path = isForum ? getDirectForumPath(roomRef, eventRef) : getDirectRoomPath(roomRef, eventRef);
} else {
path = isForum ? getHomeForumPath(roomRef, eventRef) : getHomeRoomPath(roomRef, eventRef);
}
navigate(path, { replace: true });
}, [eventId, forum, isForum, navigate, roomIdOrAlias, section, spaceIdOrAlias]);
if (isForum !== forum) return null;
return forum ? <ForumView /> : <Room />;
}
@@ -13,7 +13,9 @@ export function CreateRoomPage() {
const spaceId = searchParams.get('spaceId') ?? undefined;
const typeParam = searchParams.get('type');
const type =
typeParam === CreateRoomType.TextRoom || typeParam === CreateRoomType.VoiceRoom
typeParam === CreateRoomType.TextRoom ||
typeParam === CreateRoomType.VoiceRoom ||
typeParam === CreateRoomType.ForumRoom
? typeParam
: undefined;
+7 -2
View File
@@ -23,7 +23,7 @@ import {
NavItem,
NavItemContent,
} from '$components/nav';
import { getDirectCreatePath, getDirectRoomPath } from '$pages/pathUtils';
import { getDirectCreatePath, getDirectForumPath, getDirectRoomPath } from '$pages/pathUtils';
import { getCanonicalAliasOrRoomId } from '$utils/matrix';
import { useSelectedOrLastRoom } from '$hooks/router/useSelectedRoom';
import { VirtualTile } from '$components/virtualizer';
@@ -46,6 +46,7 @@ import { useDirectRooms } from './useDirectRooms';
import { useSidebarWidth } from '$hooks/useSidebarWidth';
import { useMenuAnchor } from '$hooks/useMenuAnchor';
import { NavMenu } from '$components/nav/NavMenu';
import { CustomRoomType } from '$types/matrix/room';
type DirectMenuProps = {
requestClose: () => void;
@@ -273,7 +274,11 @@ export function Direct() {
direct
customDMCards={customDMCards}
hideText={hideText}
linkPath={getDirectRoomPath(getCanonicalAliasOrRoomId(mx, roomId))}
linkPath={
room.getType() === CustomRoomType.Forum
? getDirectForumPath(getCanonicalAliasOrRoomId(mx, roomId))
: getDirectRoomPath(getCanonicalAliasOrRoomId(mx, roomId))
}
notificationMode={getRoomNotificationMode(
notificationPreferences,
room.roomId
+7 -1
View File
@@ -20,6 +20,7 @@ import {
getExplorePath,
getExploreServerPath,
getCreateRoomPath,
getHomeForumPath,
getHomeRoomPath,
getHomeSearchPath,
withSearchParam,
@@ -64,6 +65,7 @@ import { useClientConfig } from '$hooks/useClientConfig';
import { getMxIdServer } from '$utils/mxIdHelper';
import { NavMenu } from '$components/nav/NavMenu';
import { useMenuAnchor } from '$hooks/useMenuAnchor';
import { CustomRoomType } from '$types/matrix/room';
type HomeMenuProps = {
requestClose: () => void;
@@ -435,7 +437,11 @@ export function Home() {
selected={selected}
showAvatar={showIcons()}
hideText={hideText}
linkPath={getHomeRoomPath(canonicalName)}
linkPath={
room.getType() === CustomRoomType.Forum
? getHomeForumPath(canonicalName)
: getHomeRoomPath(canonicalName)
}
notificationMode={getRoomNotificationMode(
notificationPreferences,
room.roomId
@@ -6,7 +6,7 @@ import { useAtomValue } from 'jotai';
import type { Room } from '$types/matrix-sdk';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { roomToUnreadAtom } from '$state/room/roomToUnread';
import { getDirectRoomPath } from '$pages/pathUtils';
import { getDirectForumPath, getDirectRoomPath } from '$pages/pathUtils';
import {
SidebarAvatar,
SidebarItemLeft,
@@ -24,6 +24,7 @@ import { useGroupDMMembers } from '$hooks/useGroupDMMembers';
import { useRoomAvatar, useRoomName } from '$hooks/useRoomMeta';
import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds';
import * as css from './DirectDMsList.css';
import { CustomRoomType } from '$types/matrix/room';
const MAX_GROUP_MEMBERS = 3;
@@ -39,7 +40,12 @@ function DMItem({ room, selected }: DMItemProps) {
const roomToUnread = useAtomValue(roomToUnreadAtom);
const handleClick = () => {
navigate(getDirectRoomPath(getCanonicalAliasOrRoomId(mx, room.roomId)));
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, room.roomId);
navigate(
room.getType() === CustomRoomType.Forum
? getDirectForumPath(roomIdOrAlias)
: getDirectRoomPath(roomIdOrAlias)
);
};
const roomName = useRoomName(room);
+27
View File
@@ -1,9 +1,13 @@
import { describe, expect, it } from 'vitest';
import {
getAppPathFromHref,
getDirectForumPath,
getHomeForumPath,
getLoginPath,
getRegisterPath,
getSpaceForumPath,
getSettingsPath,
resolveSection,
withSearchParam,
} from './pathUtils';
@@ -50,6 +54,29 @@ describe('getSettingsPath', () => {
});
});
describe('forum paths', () => {
it('builds forum routes with optional event links', () => {
expect(getHomeForumPath('!room:example.org')).toBe('/home/!room%3Aexample.org/forum');
expect(getDirectForumPath('!room:example.org', '$event:example.org')).toBe(
'/direct/!room%3Aexample.org/forum/%24event%3Aexample.org'
);
expect(getSpaceForumPath('!space:example.org', '!room:example.org')).toBe(
'/!space%3Aexample.org/!room%3Aexample.org/forum'
);
});
it('preserves the forum route when resolving the active section', () => {
expect(
resolveSection('/home/!room:example.org/forum/')?.getRoomPath?.('!room:example.org')
).toBe('/home/!room%3Aexample.org/forum');
expect(
resolveSection('/!space:example.org/!room:example.org/forum/')?.getRoomPath?.(
'!room:example.org'
)
).toBe('/!space%3Aexample.org/!room%3Aexample.org/forum');
});
});
describe('getAppPathFromHref', () => {
it('extracts the app path for a matching browser-router origin', () => {
expect(getAppPathFromHref('https://app.sable.moe/', 'https://app.sable.moe/')).toBe('/');
+18 -8
View File
@@ -111,8 +111,8 @@ export const getHomeRoomPath = (roomIdOrAlias: string, eventId?: string): string
return generatePath(HOME_ROOM_PATH, params);
};
export const getHomeForumPath = (roomIdOrAlias: string): string =>
generatePath(HOME_ROOM_FORUM_PATH, { roomIdOrAlias });
export const getHomeForumPath = (roomIdOrAlias: string, eventId?: string): string =>
generatePath(HOME_ROOM_FORUM_PATH, { roomIdOrAlias, eventId: eventId ?? null });
export const getDirectPath = (): string => DIRECT_PATH;
export const getDirectCreatePath = (): string => DIRECT_CREATE_PATH;
@@ -125,8 +125,8 @@ export const getDirectRoomPath = (roomIdOrAlias: string, eventId?: string): stri
return generatePath(DIRECT_ROOM_PATH, params);
};
export const getDirectForumPath = (roomIdOrAlias: string): string =>
generatePath(DIRECT_ROOM_FORUM_PATH, { roomIdOrAlias });
export const getDirectForumPath = (roomIdOrAlias: string, eventId?: string): string =>
generatePath(DIRECT_ROOM_FORUM_PATH, { roomIdOrAlias, eventId: eventId ?? null });
export const getSpacePath = (spaceIdOrAlias: string): string => {
const params = {
@@ -160,10 +160,15 @@ export const getSpaceRoomPath = (
return generatePath(SPACE_ROOM_PATH, params);
};
export const getSpaceForumPath = (spaceIdOrAlias: string, roomIdOrAlias: string): string =>
export const getSpaceForumPath = (
spaceIdOrAlias: string,
roomIdOrAlias: string,
eventId?: string
): string =>
generatePath(SPACE_ROOM_FORUM_PATH, {
spaceIdOrAlias,
roomIdOrAlias,
eventId: eventId ?? null,
});
export const getExplorePath = (): string => EXPLORE_PATH;
@@ -205,17 +210,19 @@ export type SectionNav = {
*/
export const resolveSection = (pathname: string): SectionNav | null => {
if (matchPath({ path: HOME_PATH, end: false }, pathname)) {
const isForum = matchPath({ path: HOME_ROOM_FORUM_PATH, end: false }, pathname) !== null;
return {
key: 'home',
listPath: getHomePath(),
getRoomPath: getHomeRoomPath,
getRoomPath: isForum ? getHomeForumPath : getHomeRoomPath,
};
}
if (matchPath({ path: DIRECT_PATH, end: false }, pathname)) {
const isForum = matchPath({ path: DIRECT_ROOM_FORUM_PATH, end: false }, pathname) !== null;
return {
key: 'direct',
listPath: getDirectPath(),
getRoomPath: getDirectRoomPath,
getRoomPath: isForum ? getDirectForumPath : getDirectRoomPath,
};
}
if (matchPath({ path: EXPLORE_PATH, end: false }, pathname)) {
@@ -228,10 +235,13 @@ export const resolveSection = (pathname: string): SectionNav | null => {
const encodedSpaceId = spaceMatch?.params.spaceIdOrAlias;
if (encodedSpaceId) {
const spaceId = decodeURIComponent(encodedSpaceId);
const isForum = matchPath({ path: SPACE_ROOM_FORUM_PATH, end: false }, pathname) !== null;
return {
key: `space:${spaceId}`,
listPath: getSpacePath(spaceId),
getRoomPath: (roomIdOrAlias) => getSpaceRoomPath(spaceId, roomIdOrAlias),
getRoomPath: isForum
? (roomIdOrAlias) => getSpaceForumPath(spaceId, roomIdOrAlias)
: (roomIdOrAlias) => getSpaceRoomPath(spaceId, roomIdOrAlias),
};
}
return null;
+1 -1
View File
@@ -54,7 +54,7 @@ export type RoomSearchParams = {
viaServers?: string;
};
export const ROOM_PATH_SEGMENT = ':roomIdOrAlias/:eventId?/';
export const ROOM_FORUM_PATH_SEGMENT = ':roomIdOrAlias/forum/';
export const ROOM_FORUM_PATH_SEGMENT = ':roomIdOrAlias/forum/:eventId?/';
export const HOME_PATH = '/home/';
export const HOME_JOIN_PATH = `/home/${JOIN_PATH_SEGMENT}`;