refactor: Consolidate icon imports across components and streamline import statements for improved readability

This commit is contained in:
2026-07-06 03:29:18 +10:00
parent 1f71fd7a51
commit 09db721b7e
221 changed files with 3472 additions and 2128 deletions
+315 -21
View File
@@ -1,16 +1,19 @@
import {
Direction,
EventType,
type IContent,
type IEventRelation,
type IRoomEvent,
type MatrixClient,
type MatrixEvent,
type Room,
RelationType,
} from 'matrix-js-sdk';
import type { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { getMemberDisplayName, getSpaceChildren, isSpace } from '../../utils/room';
import type { ForumPost, ForumTopic } from './types';
import { annotatePostsWithRoomScope } from './forumTopicHelpers';
import { bodyHtmlFromMessageContent } from './forumRichText';
import { bodyHtmlFromMessageContent, titleFromFormattedBody } from './forumRichText';
type RawRelation = {
rel_type?: string;
@@ -24,6 +27,80 @@ function threadRelationFromContent(content: Record<string, unknown>): RawRelatio
return relates as RawRelation;
}
function isAnnotationRoomMessage(content: Record<string, unknown>): boolean {
const relation = threadRelationFromContent(content);
if (!relation?.rel_type) return false;
return (
relation.rel_type === RelationType.Replace ||
relation.rel_type === 'm.replace' ||
relation.rel_type === RelationType.Annotation ||
relation.rel_type === 'm.annotation'
);
}
function isForumRootContent(content: Record<string, unknown>): boolean {
if (typeof content['com.matrixsso.title'] === 'string') return true;
const formatted = content.formatted_body;
return typeof formatted === 'string' && /<h1[\s>]/i.test(formatted);
}
function syncForumRootContentAfterEdit(
merged: Record<string, unknown>,
baseContent: Record<string, unknown>
): Record<string, unknown> {
if (!isForumRootContent(baseContent)) return merged;
const formattedTitle =
typeof merged.formatted_body === 'string'
? titleFromFormattedBody(merged.formatted_body)
: undefined;
const { title, body } = postTitleFromContent({
...merged,
// Ignore stale title so edits can rename the post.
'com.matrixsso.title': formattedTitle ?? undefined,
});
const next: Record<string, unknown> = {
...merged,
'com.matrixsso.title': title,
};
if (typeof merged.body === 'string') {
const plain = merged.body.trim();
if (body && plain !== body && !plain.startsWith(`${title}\n`)) {
next.body = `${title}\n\n${body}`;
}
}
return next;
}
function getLatestEditContent(
event: IRoomEvent,
timelineEvents: IRoomEvent[]
): Record<string, unknown> {
const baseContent = event.content as Record<string, unknown>;
const targetId = event.event_id;
if (!targetId) return baseContent;
const edits = timelineEvents
.filter((candidate) => {
if (candidate.type !== EventType.RoomMessage || !candidate.content) return false;
const rel = threadRelationFromContent(candidate.content as Record<string, unknown>);
return rel?.rel_type === RelationType.Replace && rel.event_id === targetId;
})
.sort((a, b) => (b.origin_server_ts || 0) - (a.origin_server_ts || 0));
const latestEdit = edits[0];
if (!latestEdit?.content) return baseContent;
const newContent = (latestEdit.content as Record<string, unknown>)['m.new_content'];
if (!newContent || typeof newContent !== 'object') return baseContent;
const merged = { ...baseContent, ...(newContent as Record<string, unknown>) };
return syncForumRootContentAfterEdit(merged, baseContent);
}
function parseBundledThreadReplyCount(event: IRoomEvent): number | undefined {
const relations = event.unsigned?.['m.relations'] as Record<string, unknown> | undefined;
const thread = relations?.['m.thread'] as { count?: unknown } | undefined;
@@ -38,8 +115,12 @@ function postTitleFromContent(content: Record<string, unknown>): { title: string
typeof content['com.matrixsso.title'] === 'string'
? String(content['com.matrixsso.title']).trim()
: '';
const htmlTitle =
typeof content.formatted_body === 'string'
? titleFromFormattedBody(content.formatted_body)
: undefined;
const firstLine = rawBody.split(/\r?\n/, 1)[0]?.trim() ?? '';
const title = (customTitle || firstLine || '(untitled post)').slice(0, 160);
const title = (customTitle || htmlTitle || firstLine || '(untitled post)').slice(0, 160);
let body = rawBody;
if (customTitle && rawBody.startsWith(customTitle)) {
@@ -56,6 +137,11 @@ function postTitleFromContent(content: Record<string, unknown>): { title: string
return { title, body: body || rawBody };
}
/** Title + body for a forum matrix message payload (including edits). */
export function forumPostTitleFromContent(content: Record<string, unknown>): string {
return postTitleFromContent(content).title;
}
function sortRepliesRecursively(posts: ForumPost[]) {
posts.sort((a, b) => a.timestamp - b.timestamp);
for (const post of posts) {
@@ -77,7 +163,10 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
!redactedIds.has(event.event_id)
)
.map((event) => {
const content = event.content as Record<string, unknown>;
const rawContent = event.content as Record<string, unknown>;
if (isAnnotationRoomMessage(rawContent)) return null;
const content = getLatestEditContent(event, timelineEvents);
const relation = threadRelationFromContent(content);
const isThreadReply =
relation?.rel_type === RelationType.Thread || relation?.rel_type === 'm.thread';
@@ -272,6 +361,9 @@ export async function listTopicFeedPosts(
if (!nextBatch || merged.length >= minRoots) break;
}
const localPosts = buildPosts(mx, roomId, collectLocalRootPosts(mx, roomId));
merged = mergeRootPosts(merged, localPosts);
return { posts: merged, nextBatch: nextBatch ?? null };
}
@@ -283,11 +375,164 @@ function mergeRootPosts(existing: ForumPost[], incoming: ForumPost[]): ForumPost
byId.set(post.eventId, post);
continue;
}
previous.replies = [...previous.replies, ...post.replies];
const replyIds = new Set(previous.replies.map((reply) => reply.eventId));
const mergedReplies = [
...previous.replies,
...post.replies.filter((reply) => !replyIds.has(reply.eventId)),
];
byId.set(post.eventId, { ...post, replies: mergedReplies });
}
return [...byId.values()].sort((a, b) => b.timestamp - a.timestamp);
}
function mergeUniqueRoomEvents(...lists: IRoomEvent[][]): IRoomEvent[] {
const seen = new Set<string>();
const unique: IRoomEvent[] = [];
for (const list of lists) {
for (const event of list) {
const id = event.event_id;
if (!id || seen.has(id)) continue;
seen.add(id);
unique.push(event);
}
}
return unique;
}
function isSecondaryMatrixEvent(mEvent: MatrixEvent): boolean {
const relation = mEvent.getRelation();
if (
relation?.rel_type === RelationType.Replace ||
relation?.rel_type === RelationType.Annotation
) {
return true;
}
return isAnnotationRoomMessage(mEvent.getContent());
}
function eventBelongsToThread(mEvent: MatrixEvent, rootEventId: string): boolean {
if (mEvent.getId() === rootEventId) return true;
const relation = mEvent.getRelation();
if (relation?.rel_type === RelationType.Thread && relation.event_id === rootEventId) {
return true;
}
const contentRelation = threadRelationFromContent(mEvent.getContent());
if (
contentRelation?.rel_type === RelationType.Thread &&
contentRelation.event_id === rootEventId
) {
return true;
}
return false;
}
function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent {
return mEvent.event as IRoomEvent;
}
/** Thread events already in the local room timeline (includes unsent/local echo). */
export function collectLocalThreadEvents(
mx: MatrixClient,
roomId: string,
rootEventId: string
): IRoomEvent[] {
const rootId = rootEventId.trim();
const room = mx.getRoom(roomId);
if (!rootId || !room) return [];
const seen = new Set<string>();
const events: IRoomEvent[] = [];
const add = (mEvent: MatrixEvent | undefined | null) => {
if (!mEvent || mEvent.isRedacted()) return;
if (mEvent.getType() !== EventType.RoomMessage) return;
if (isSecondaryMatrixEvent(mEvent)) return;
if (!eventBelongsToThread(mEvent, rootId)) return;
const id = mEvent.getId();
if (!id || seen.has(id)) return;
seen.add(id);
events.push(matrixEventToRoomEvent(mEvent));
};
add(room.findEventById(rootId));
const thread = room.getThread(rootId);
if (thread) {
add(thread.rootEvent);
for (const reply of thread.events) add(reply);
for (const reply of thread.liveTimeline?.getEvents() ?? []) add(reply);
}
for (const mEvent of room.getUnfilteredTimelineSet().getLiveTimeline().getEvents()) {
add(mEvent);
}
const targetIds = new Set(seen);
events.push(...collectLocalReplaceEdits(room, targetIds));
return events;
}
function collectLocalReplaceEdits(room: Room, targetIds: Set<string>): IRoomEvent[] {
const events: IRoomEvent[] = [];
const seen = new Set<string>();
for (const mEvent of room.getUnfilteredTimelineSet().getLiveTimeline().getEvents()) {
if (mEvent.isRedacted() || mEvent.getType() !== EventType.RoomMessage) continue;
const relation = mEvent.getRelation();
if (relation?.rel_type !== RelationType.Replace) continue;
const targetId = relation.event_id;
if (!targetId || !targetIds.has(targetId)) continue;
const id = mEvent.getId();
if (!id || seen.has(id)) continue;
seen.add(id);
events.push(matrixEventToRoomEvent(mEvent));
}
return events;
}
function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] {
const room = mx.getRoom(roomId);
if (!room) return [];
const seen = new Set<string>();
const events: IRoomEvent[] = [];
for (const mEvent of room.getUnfilteredTimelineSet().getLiveTimeline().getEvents()) {
if (mEvent.isRedacted() || mEvent.getType() !== EventType.RoomMessage) continue;
if (isSecondaryMatrixEvent(mEvent)) continue;
const relation = threadRelationFromContent(mEvent.getContent());
const isThreadReply =
relation?.rel_type === RelationType.Thread || relation?.rel_type === 'm.thread';
if (isThreadReply) continue;
const id = mEvent.getId();
if (!id || seen.has(id)) continue;
seen.add(id);
events.push(matrixEventToRoomEvent(mEvent));
}
const rootIds = new Set(events.map((event) => event.event_id).filter(Boolean) as string[]);
events.push(...collectLocalReplaceEdits(room, rootIds));
return events;
}
export function loadPostThreadLocal(
mx: MatrixClient,
roomId: string,
rootEventId: string
): ForumPost | null {
const rootId = rootEventId.trim();
const events = collectLocalThreadEvents(mx, roomId, rootId);
if (events.length === 0) return null;
const posts = buildPosts(mx, roomId, events);
return posts.find((post) => post.eventId === rootId) ?? posts[0] ?? null;
}
async function fetchRootEvent(
mx: MatrixClient,
roomId: string,
@@ -314,10 +559,10 @@ export async function loadPostThread(
rootEventId: string
): Promise<ForumPost | null> {
const rootId = rootEventId.trim();
const rootEvent = await fetchRootEvent(mx, roomId, rootId);
if (!rootEvent?.event_id) return null;
const localEvents = collectLocalThreadEvents(mx, roomId, rootId);
const events: IRoomEvent[] = [rootEvent];
const rootEvent = await fetchRootEvent(mx, roomId, rootId);
const apiEvents: IRoomEvent[] = rootEvent?.event_id ? [rootEvent] : [];
const collectRelations = async (
relationType: RelationType | null,
@@ -332,31 +577,32 @@ export async function loadPostThread(
recurse: true,
});
if (relPayload.chunk?.length) {
events.push(...(relPayload.chunk as IRoomEvent[]));
apiEvents.push(...(relPayload.chunk as IRoomEvent[]));
}
from = relPayload.next_batch ?? undefined;
if (!from) break;
}
};
try {
await collectRelations(RelationType.Thread, EventType.RoomMessage);
} catch {
if (rootEvent?.event_id) {
try {
await collectRelations(null, EventType.RoomMessage);
await collectRelations(RelationType.Replace, EventType.RoomMessage);
} catch {
// Still show root without replies.
// Root may have no replace relations.
}
try {
await collectRelations(RelationType.Thread, EventType.RoomMessage);
} catch {
try {
await collectRelations(null, EventType.RoomMessage);
} catch {
// Still show root without replies.
}
}
}
const seen = new Set<string>();
const unique: IRoomEvent[] = [];
for (const event of events) {
const id = event.event_id;
if (!id || seen.has(id)) continue;
seen.add(id);
unique.push(event);
}
const unique = mergeUniqueRoomEvents(localEvents, apiEvents);
if (unique.length === 0) return null;
const posts = buildPosts(mx, roomId, unique);
return posts.find((post) => post.eventId === rootId) ?? posts[0] ?? null;
@@ -423,6 +669,54 @@ export async function sendForumPost(
return res.event_id;
}
/** Image/file/video root post with a forum title. */
export async function sendForumMediaRoot(
mx: MatrixClient,
roomId: string,
title: string,
content: IContent
): Promise<string> {
const trimmedTitle = title.trim();
if (!trimmedTitle) {
throw new Error('Post title is required.');
}
if (trimmedTitle.length > 140) {
throw new Error('Post title is too long.');
}
const res = await mx.sendMessage(roomId, {
...content,
'com.matrixsso.title': trimmedTitle,
});
return res.event_id;
}
/** Thread attachment (image, file, etc.) under a forum post root. */
export async function sendForumThreadAttachment(
mx: MatrixClient,
roomId: string,
threadRootId: string,
content: IContent,
replyToEventId?: string
): Promise<string> {
const rootId = threadRootId.trim();
const parentId = replyToEventId?.trim() || rootId;
if (!rootId) {
throw new Error('Thread root event id is required.');
}
const res = await mx.sendMessage(roomId, {
...content,
'm.relates_to': {
rel_type: RelationType.Thread,
event_id: rootId,
is_falling_back: false,
'm.in_reply_to': { event_id: parentId },
} as IEventRelation,
});
return res.event_id;
}
export type ForumReplyPayload = {
plainText: string;
formattedHtml?: string;