Fix the mechanical style rules. [skip build]
This commit is contained in:
@@ -45,7 +45,7 @@ async function leaveRoomsSequentially(
|
||||
): Promise<void> {
|
||||
const total = roomIds.length;
|
||||
|
||||
for (let i = 0; i < roomIds.length; i++) {
|
||||
for (let i = 0; i < roomIds.length; i += 1) {
|
||||
const roomId = roomIds[i];
|
||||
onProgress?.(i, total);
|
||||
|
||||
|
||||
@@ -25,9 +25,9 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
|
||||
}, [ref]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onExpand) return;
|
||||
if (!onExpand) return undefined;
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
if (!video) return undefined;
|
||||
|
||||
const handleFullscreenRequest = (evt: Event) => {
|
||||
evt.preventDefault();
|
||||
|
||||
@@ -91,7 +91,7 @@ export async function collectInaccessibleSpaceChildren(
|
||||
if (!spaceRoom || spaceRoom.getMyMembership() !== Membership.Join) return;
|
||||
if (!canEditSpaceChildren(mx, spaceRoom)) return;
|
||||
|
||||
for (const childId of getSpaceChildren(spaceRoom)) {
|
||||
getSpaceChildren(spaceRoom).forEach((childId) => {
|
||||
childCount += 1;
|
||||
const childRoom = mx.getRoom(childId);
|
||||
// Lobby uses joined-only getRoom; left/invite rooms still render as Inaccessible.
|
||||
@@ -100,22 +100,22 @@ export async function collectInaccessibleSpaceChildren(
|
||||
if (joined && childRoom && isSpace(childRoom)) {
|
||||
joinedCount += 1;
|
||||
walk(childId);
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
if (joined) {
|
||||
joinedCount += 1;
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
const hasHierarchySummary = hierarchySummaries.has(childId);
|
||||
if (hasHierarchySummary) {
|
||||
joinableCount += 1;
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
inaccessible.push({ parentId: spaceId, roomId: childId });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
walk(rootSpaceId);
|
||||
|
||||
@@ -30,7 +30,7 @@ export function SettingTile({
|
||||
const anchorId = anchorIdProp ?? autoAnchorId;
|
||||
|
||||
useEffect(() => {
|
||||
if (!anchorId || !focusAnchorId || anchorId !== focusAnchorId) return;
|
||||
if (!anchorId || !focusAnchorId || anchorId !== focusAnchorId) return undefined;
|
||||
let cancelled = false;
|
||||
let attempts = 0;
|
||||
|
||||
@@ -57,7 +57,7 @@ export function SettingTile({
|
||||
}, [anchorId, focusAnchorId, setAnchorId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!highlighted) return;
|
||||
if (!highlighted) return undefined;
|
||||
const timer = window.setTimeout(() => setHighlighted(false), 1400);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [highlighted]);
|
||||
|
||||
@@ -316,7 +316,7 @@ export function TitleBar({ mx, children }: TitleBarProps) {
|
||||
|
||||
// Subscribe to room changes for unread updates and new messages
|
||||
useEffect(() => {
|
||||
if (!mx) return;
|
||||
if (!mx) return undefined;
|
||||
|
||||
const update = () => setUpdateCounter((c) => c + 1);
|
||||
|
||||
@@ -473,7 +473,7 @@ export function TitleBar({ mx, children }: TitleBarProps) {
|
||||
|
||||
// Clear notifications when user reads messages in a room
|
||||
useEffect(() => {
|
||||
if (!mx) return;
|
||||
if (!mx) return undefined;
|
||||
|
||||
const handleReceipt = (event: MatrixEvent, room: Room) => {
|
||||
const myUserId = mx.getUserId();
|
||||
|
||||
@@ -295,24 +295,23 @@ export async function fetchLiveKitJWTFromServers(
|
||||
|
||||
if (!livekitFocus) {
|
||||
console.log(`No LiveKit config on ${homeserver}, trying next...`);
|
||||
continue;
|
||||
} else {
|
||||
// Always get OpenID token from user's own homeserver
|
||||
// (Can't use access token on remote homeserver)
|
||||
const openIdToken = await requestOpenIdToken(userHomeserver, userId, accessToken);
|
||||
|
||||
// Exchange for LiveKit JWT
|
||||
const jwt = await fetchLiveKitJWT(
|
||||
livekitFocus.livekit_service_url,
|
||||
roomId,
|
||||
userId,
|
||||
deviceId,
|
||||
openIdToken,
|
||||
);
|
||||
|
||||
console.log(`Successfully got LiveKit JWT from ${homeserver}`);
|
||||
return { jwt, homeserver };
|
||||
}
|
||||
|
||||
// Always get OpenID token from user's own homeserver
|
||||
// (Can't use access token on remote homeserver)
|
||||
const openIdToken = await requestOpenIdToken(userHomeserver, userId, accessToken);
|
||||
|
||||
// Exchange for LiveKit JWT
|
||||
const jwt = await fetchLiveKitJWT(
|
||||
livekitFocus.livekit_service_url,
|
||||
roomId,
|
||||
userId,
|
||||
deviceId,
|
||||
openIdToken,
|
||||
);
|
||||
|
||||
console.log(`Successfully got LiveKit JWT from ${homeserver}`);
|
||||
return { jwt, homeserver };
|
||||
} catch (error) {
|
||||
console.warn(`Failed to get LiveKit JWT from ${homeserver}:`, error);
|
||||
// Continue to next homeserver
|
||||
|
||||
+119
-108
@@ -44,6 +44,34 @@ function isForumRootContent(content: Record<string, unknown>): boolean {
|
||||
return typeof formatted === 'string' && /<h1[\s>]/i.test(formatted);
|
||||
}
|
||||
|
||||
function postTitleFromContent(content: Record<string, unknown>): { title: string; body: string } {
|
||||
const rawBody = typeof content.body === 'string' ? content.body : '';
|
||||
const customTitle =
|
||||
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 || htmlTitle || firstLine || '(untitled post)').slice(0, 160);
|
||||
|
||||
let body = rawBody;
|
||||
if (customTitle && rawBody.startsWith(customTitle)) {
|
||||
body = rawBody.slice(customTitle.length).replace(/^\s+/, '');
|
||||
} else {
|
||||
const [leadingBlock, ...restBlocks] = rawBody.split(/\r?\n\r?\n/);
|
||||
if (restBlocks.length > 0 && leadingBlock.trim() === firstLine) {
|
||||
body = restBlocks.join('\n\n').trim();
|
||||
} else if (firstLine && rawBody.startsWith(firstLine)) {
|
||||
body = rawBody.slice(firstLine.length).replace(/^\s+/, '');
|
||||
}
|
||||
}
|
||||
|
||||
return { title, body: body || rawBody };
|
||||
}
|
||||
|
||||
function syncForumRootContentAfterEdit(
|
||||
merged: Record<string, unknown>,
|
||||
baseContent: Record<string, unknown>,
|
||||
@@ -109,34 +137,6 @@ function parseBundledThreadReplyCount(event: IRoomEvent): number | undefined {
|
||||
return Math.floor(count);
|
||||
}
|
||||
|
||||
function postTitleFromContent(content: Record<string, unknown>): { title: string; body: string } {
|
||||
const rawBody = typeof content.body === 'string' ? content.body : '';
|
||||
const customTitle =
|
||||
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 || htmlTitle || firstLine || '(untitled post)').slice(0, 160);
|
||||
|
||||
let body = rawBody;
|
||||
if (customTitle && rawBody.startsWith(customTitle)) {
|
||||
body = rawBody.slice(customTitle.length).replace(/^\s+/, '');
|
||||
} else {
|
||||
const [leadingBlock, ...restBlocks] = rawBody.split(/\r?\n\r?\n/);
|
||||
if (restBlocks.length > 0 && leadingBlock.trim() === firstLine) {
|
||||
body = restBlocks.join('\n\n').trim();
|
||||
} else if (firstLine && rawBody.startsWith(firstLine)) {
|
||||
body = rawBody.slice(firstLine.length).replace(/^\s+/, '');
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -144,9 +144,27 @@ export function forumPostTitleFromContent(content: Record<string, unknown>): str
|
||||
|
||||
function sortRepliesRecursively(posts: ForumPost[]) {
|
||||
posts.sort((a, b) => a.timestamp - b.timestamp);
|
||||
for (const post of posts) {
|
||||
posts.forEach((post) => {
|
||||
if (post.replies.length > 0) sortRepliesRecursively(post.replies);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function mergeRootPosts(existing: ForumPost[], incoming: ForumPost[]): ForumPost[] {
|
||||
const byId = new Map(existing.map((post) => [post.eventId, post]));
|
||||
incoming.forEach((post) => {
|
||||
const previous = byId.get(post.eventId);
|
||||
if (!previous) {
|
||||
byId.set(post.eventId, post);
|
||||
return;
|
||||
}
|
||||
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 buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent[]): ForumPost[] {
|
||||
@@ -202,7 +220,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
.sort((a, b) => a.timestamp - b.timestamp);
|
||||
|
||||
const postsById = new Map<string, ForumPost>();
|
||||
for (const event of normalized) {
|
||||
normalized.forEach((event) => {
|
||||
postsById.set(event.eventId, {
|
||||
eventId: event.eventId,
|
||||
title: event.title,
|
||||
@@ -214,14 +232,14 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
bundledReplyCount: event.bundledReplyCount,
|
||||
replies: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const roots: ForumPost[] = [];
|
||||
const placedReplyIds = new Set<string>();
|
||||
|
||||
for (const event of normalized) {
|
||||
normalized.forEach((event) => {
|
||||
const current = postsById.get(event.eventId);
|
||||
if (!current) continue;
|
||||
if (!current) return;
|
||||
|
||||
const { relation } = event;
|
||||
let threadRootId: string | null = null;
|
||||
@@ -236,10 +254,10 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
|
||||
if (!threadRootId) {
|
||||
roots.push(current);
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
if (placedReplyIds.has(event.eventId)) continue;
|
||||
if (placedReplyIds.has(event.eventId)) return;
|
||||
|
||||
if (parentEventId && parentEventId !== threadRootId) {
|
||||
const parent = postsById.get(parentEventId);
|
||||
@@ -247,7 +265,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
current.replyToEventId = parentEventId;
|
||||
parent.replies.push(current);
|
||||
placedReplyIds.add(event.eventId);
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
current.replyToEventId = parentEventId;
|
||||
@@ -257,7 +275,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
threadRoot.replies.push(current);
|
||||
placedReplyIds.add(event.eventId);
|
||||
}
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
const threadRoot = postsById.get(threadRootId);
|
||||
@@ -265,7 +283,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
|
||||
threadRoot.replies.push(current);
|
||||
placedReplyIds.add(event.eventId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
sortRepliesRecursively(roots);
|
||||
return roots.sort((a, b) => b.timestamp - a.timestamp);
|
||||
@@ -285,14 +303,13 @@ export async function listForumTopics(
|
||||
}
|
||||
|
||||
const parentByRoomId = new Map<string, string>();
|
||||
for (const room of rooms) {
|
||||
if (!room?.room_id || !Array.isArray(room.children_state)) continue;
|
||||
for (const childState of room.children_state) {
|
||||
if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string')
|
||||
continue;
|
||||
rooms.forEach((room) => {
|
||||
if (!room?.room_id || !Array.isArray(room.children_state)) return;
|
||||
room.children_state.forEach((childState) => {
|
||||
if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string') return;
|
||||
parentByRoomId.set(childState.state_key, room.room_id);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const fromHierarchy = rooms
|
||||
.filter((room) => room?.room_id && room.room_id !== spaceRoomId)
|
||||
@@ -321,8 +338,8 @@ export async function listForumTopics(
|
||||
const parentRoom = mx.getRoom(parentId);
|
||||
if (!parentRoom) return;
|
||||
|
||||
for (const childId of getSpaceChildren(parentRoom)) {
|
||||
if (childId === spaceRoomId || visited.has(childId)) continue;
|
||||
getSpaceChildren(parentRoom).forEach((childId) => {
|
||||
if (childId === spaceRoomId || visited.has(childId)) return;
|
||||
const child = mx.getRoom(childId);
|
||||
const name = child?.name || childId;
|
||||
const childIsSpace = isSpace(child ?? null);
|
||||
@@ -333,7 +350,7 @@ export async function listForumTopics(
|
||||
parentRoomId: parentId,
|
||||
});
|
||||
if (childIsSpace) collectFromSpace(childId, depth + 1);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
collectFromSpace(spaceRoomId, 0);
|
||||
@@ -371,35 +388,17 @@ export async function listTopicFeedPosts(
|
||||
return { posts: merged, nextBatch: nextBatch ?? null };
|
||||
}
|
||||
|
||||
function mergeRootPosts(existing: ForumPost[], incoming: ForumPost[]): ForumPost[] {
|
||||
const byId = new Map(existing.map((post) => [post.eventId, post]));
|
||||
for (const post of incoming) {
|
||||
const previous = byId.get(post.eventId);
|
||||
if (!previous) {
|
||||
byId.set(post.eventId, post);
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
lists.forEach((list) => {
|
||||
list.forEach((event) => {
|
||||
const id = event.event_id;
|
||||
if (!id || seen.has(id)) continue;
|
||||
if (!id || seen.has(id)) return;
|
||||
seen.add(id);
|
||||
unique.push(event);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
return unique;
|
||||
}
|
||||
|
||||
@@ -437,6 +436,29 @@ function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent {
|
||||
return mEvent.event as IRoomEvent;
|
||||
}
|
||||
|
||||
function collectLocalReplaceEdits(room: Room, targetIds: Set<string>): IRoomEvent[] {
|
||||
const events: IRoomEvent[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.forEach((mEvent) => {
|
||||
if (mEvent.isRedacted() || mEvent.getType() !== EventType.RoomMessage) return;
|
||||
const relation = mEvent.getRelation();
|
||||
if (relation?.rel_type !== RelationType.Replace) return;
|
||||
const targetId = relation.event_id;
|
||||
if (!targetId || !targetIds.has(targetId)) return;
|
||||
const id = mEvent.getId();
|
||||
if (!id || seen.has(id)) return;
|
||||
seen.add(id);
|
||||
events.push(matrixEventToRoomEvent(mEvent));
|
||||
});
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
/** Thread events already in the local room timeline (includes unsent/local echo). */
|
||||
export function collectLocalThreadEvents(
|
||||
mx: MatrixClient,
|
||||
@@ -466,13 +488,17 @@ export function collectLocalThreadEvents(
|
||||
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);
|
||||
thread.events.forEach((reply) => add(reply));
|
||||
(thread.liveTimeline?.getEvents() ?? []).forEach((reply) => add(reply));
|
||||
}
|
||||
|
||||
for (const mEvent of room.getUnfilteredTimelineSet().getLiveTimeline().getEvents()) {
|
||||
add(mEvent);
|
||||
}
|
||||
room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.forEach((mEvent) => {
|
||||
add(mEvent);
|
||||
});
|
||||
|
||||
const targetIds = new Set(seen);
|
||||
events.push(...collectLocalReplaceEdits(room, targetIds));
|
||||
@@ -480,25 +506,6 @@ export function collectLocalThreadEvents(
|
||||
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 [];
|
||||
@@ -506,18 +513,22 @@ function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] {
|
||||
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));
|
||||
}
|
||||
room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.forEach((mEvent) => {
|
||||
if (mEvent.isRedacted() || mEvent.getType() !== EventType.RoomMessage) return;
|
||||
if (isSecondaryMatrixEvent(mEvent)) return;
|
||||
const relation = threadRelationFromContent(mEvent.getContent());
|
||||
const isThreadReply =
|
||||
relation?.rel_type === RelationType.Thread || relation?.rel_type === 'm.thread';
|
||||
if (isThreadReply) return;
|
||||
const id = mEvent.getId();
|
||||
if (!id || seen.has(id)) return;
|
||||
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));
|
||||
|
||||
@@ -3,10 +3,10 @@ import { applyTopicStatusSort, filterPostsBySearch, parseTopicSearchQuery } from
|
||||
|
||||
export function countAllReplies(replies: ForumPost[] | undefined): number {
|
||||
let total = 0;
|
||||
for (const reply of replies || []) {
|
||||
(replies || []).forEach((reply) => {
|
||||
total += 1;
|
||||
total += countAllReplies(reply.replies);
|
||||
}
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
@@ -15,9 +15,10 @@ export function maxThreadTimestamp(post: ForumPost): number {
|
||||
const stack = [...(post.replies || [])];
|
||||
while (stack.length > 0) {
|
||||
const current = stack.pop();
|
||||
if (!current) continue;
|
||||
if (current.timestamp > maxValue) maxValue = current.timestamp;
|
||||
if (current.replies?.length) stack.push(...current.replies);
|
||||
if (current) {
|
||||
if (current.timestamp > maxValue) maxValue = current.timestamp;
|
||||
if (current.replies?.length) stack.push(...current.replies);
|
||||
}
|
||||
}
|
||||
return maxValue;
|
||||
}
|
||||
@@ -54,7 +55,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] {
|
||||
const postableTopics = topics.filter((topic) => !topic.isSpace);
|
||||
const sections: ForumSection[] = [];
|
||||
|
||||
for (const space of spaces) {
|
||||
spaces.forEach((space) => {
|
||||
const childTopics = postableTopics.filter((topic) => topic.parentRoomId === space.roomId);
|
||||
|
||||
sections.push({
|
||||
@@ -63,7 +64,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] {
|
||||
description: space.topic || null,
|
||||
topics: childTopics.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const coveredTopicIds = new Set(
|
||||
sections.flatMap((section) => section.topics.map((topic) => topic.roomId)),
|
||||
|
||||
@@ -142,15 +142,15 @@ export function collectAuthorHintsFromThreads(
|
||||
): TopicSearchAuthorHint[] {
|
||||
const map = new Map<string, TopicSearchAuthorHint>();
|
||||
|
||||
for (const thread of threads) {
|
||||
threads.forEach((thread) => {
|
||||
const userId = thread.sender;
|
||||
if (!userId || map.has(userId)) {
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
const localpart = userId.startsWith('@') ? userId.slice(1).split(':')[0] : userId;
|
||||
const displayName = (thread.senderDisplayName || localpart).trim() || localpart;
|
||||
map.set(userId, { userId, displayName, localpart });
|
||||
}
|
||||
});
|
||||
|
||||
return [...map.values()].sort(
|
||||
(a, b) => a.displayName.localeCompare(b.displayName) || a.localpart.localeCompare(b.localpart),
|
||||
@@ -159,12 +159,12 @@ export function collectAuthorHintsFromThreads(
|
||||
|
||||
export function collectTitleHintsFromThreads(threads: Array<{ title: string }>): string[] {
|
||||
const titles = new Set<string>();
|
||||
for (const thread of threads) {
|
||||
threads.forEach((thread) => {
|
||||
const title = String(thread.title || '').trim();
|
||||
if (title) {
|
||||
titles.add(title);
|
||||
}
|
||||
}
|
||||
});
|
||||
return [...titles].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
@@ -221,31 +221,31 @@ function escapeRegex(value: string): string {
|
||||
function collectTerms(qualifiers: ParsedTopicSearch['qualifiers'], freeText: string): string[] {
|
||||
const terms = new Set<string>();
|
||||
|
||||
for (const list of Object.values(qualifiers)) {
|
||||
for (const value of list) {
|
||||
Object.values(qualifiers).forEach((list) => {
|
||||
list.forEach((value) => {
|
||||
const trimmed = String(value || '').trim();
|
||||
if (trimmed) {
|
||||
terms.add(trimmed.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (freeText) {
|
||||
const quoted = [...freeText.matchAll(/"([^"]+)"/g)].map((match) => match[1]);
|
||||
let scratch = freeText;
|
||||
for (const phrase of quoted) {
|
||||
quoted.forEach((phrase) => {
|
||||
if (phrase.trim()) {
|
||||
terms.add(phrase.trim().toLowerCase());
|
||||
}
|
||||
scratch = scratch.replace(`"${phrase}"`, ' ');
|
||||
}
|
||||
});
|
||||
|
||||
for (const word of scratch.split(/\s+/)) {
|
||||
scratch.split(/\s+/).forEach((word) => {
|
||||
const trimmed = word.trim();
|
||||
if (trimmed) {
|
||||
terms.add(trimmed.toLowerCase());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return [...terms];
|
||||
@@ -306,10 +306,10 @@ function nodeText(node: ForumPost): string {
|
||||
}
|
||||
|
||||
function walkReplyTree(node: ForumPost, visit: (node: ForumPost) => void): void {
|
||||
for (const reply of node.replies || []) {
|
||||
(node.replies || []).forEach((reply) => {
|
||||
visit(reply);
|
||||
walkReplyTree(reply, visit);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function termsMatchAll(terms: string[], haystack: string): boolean {
|
||||
@@ -426,10 +426,10 @@ export function highlightSearchTerms(text: string, terms: string[]): string {
|
||||
);
|
||||
|
||||
let result = text;
|
||||
for (const term of usable) {
|
||||
usable.forEach((term) => {
|
||||
const re = new RegExp(`(${escapeRegex(term)})`, 'gi');
|
||||
result = result.replace(re, '<mark class="search-hit">$1</mark>');
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -152,10 +152,6 @@ const useCanDropLobbyItem = (
|
||||
return canDrop;
|
||||
};
|
||||
|
||||
export function Lobby() {
|
||||
return <SpaceCardLobby />;
|
||||
}
|
||||
|
||||
function SpaceCardLobby() {
|
||||
const navigate = useNavigate();
|
||||
const mx = useMatrixClient();
|
||||
@@ -611,3 +607,6 @@ function SpaceCardLobby() {
|
||||
</PowerLevelsContextProvider>
|
||||
);
|
||||
}
|
||||
export function Lobby() {
|
||||
return <SpaceCardLobby />;
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!showSpaceToolbar || !menuAnchor || addExisting) return;
|
||||
if (!showSpaceToolbar || !menuAnchor || addExisting) return undefined;
|
||||
|
||||
let outsideTimer: number | undefined;
|
||||
const clearOutsideTimer = () => {
|
||||
|
||||
@@ -128,16 +128,16 @@ const searchLocalRoomTimeline = (room: Room, term: string): ResultItem[] => {
|
||||
for (let i = events.length - 1; i >= 0; i -= 1) {
|
||||
const event = events[i];
|
||||
const haystack = getSearchableBody(event);
|
||||
if (!haystack || !haystack.toLowerCase().includes(needle)) continue;
|
||||
|
||||
const searchEvent = eventToSearchEvent(event, room.roomId);
|
||||
if (!searchEvent) continue;
|
||||
|
||||
matches.push({
|
||||
rank: 1,
|
||||
event: searchEvent,
|
||||
context: EMPTY_CONTEXT,
|
||||
});
|
||||
if (haystack && haystack.toLowerCase().includes(needle)) {
|
||||
const searchEvent = eventToSearchEvent(event, room.roomId);
|
||||
if (searchEvent) {
|
||||
matches.push({
|
||||
rank: 1,
|
||||
event: searchEvent,
|
||||
context: EMPTY_CONTEXT,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matches;
|
||||
|
||||
@@ -30,19 +30,6 @@ type EmojiConfettiBurstCanvasProps = {
|
||||
onComplete: (burstId: string) => void;
|
||||
};
|
||||
|
||||
export function EmojiConfettiBurstCanvas({ burst, onComplete }: EmojiConfettiBurstCanvasProps) {
|
||||
const primaryEmoji = burst.emojis[0] ?? '🎉';
|
||||
const fullscreen = isFullscreenBurstEmoji(primaryEmoji);
|
||||
|
||||
if (fullscreen) {
|
||||
return (
|
||||
<FireworkBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />
|
||||
);
|
||||
}
|
||||
|
||||
return <LocalBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />;
|
||||
}
|
||||
|
||||
type BurstCanvasProps = {
|
||||
burst: EmojiConfettiBurst;
|
||||
primaryEmoji: string;
|
||||
@@ -387,3 +374,15 @@ function LocalBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasProps)
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
export function EmojiConfettiBurstCanvas({ burst, onComplete }: EmojiConfettiBurstCanvasProps) {
|
||||
const primaryEmoji = burst.emojis[0] ?? '🎉';
|
||||
const fullscreen = isFullscreenBurstEmoji(primaryEmoji);
|
||||
|
||||
if (fullscreen) {
|
||||
return (
|
||||
<FireworkBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />
|
||||
);
|
||||
}
|
||||
|
||||
return <LocalBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />;
|
||||
}
|
||||
|
||||
@@ -239,30 +239,28 @@ export function stepBurstParticles(
|
||||
const particle = particles[i];
|
||||
const burstElapsed = now - particle.burstStartMs;
|
||||
|
||||
const ageMs = now - particle.bornAt;
|
||||
|
||||
if (burstElapsed > BURST_TOTAL_MS) {
|
||||
particles[i] = particles[particles.length - 1];
|
||||
particles.pop();
|
||||
continue;
|
||||
} else if (ageMs >= 0) {
|
||||
const dragFactor = particle.drag ** (dtSeconds * 60);
|
||||
|
||||
switch (particle.style) {
|
||||
case 'spiral':
|
||||
stepSpiralParticle(particle, dtSeconds);
|
||||
break;
|
||||
case 'bounce':
|
||||
stepBounceParticle(particle, dtSeconds, dragFactor);
|
||||
break;
|
||||
default:
|
||||
stepDefaultParticle(particle, dtSeconds, dragFactor);
|
||||
break;
|
||||
}
|
||||
|
||||
particle.phase += dtSeconds * (particle.twinkle ? 9 : 5);
|
||||
}
|
||||
|
||||
const ageMs = now - particle.bornAt;
|
||||
if (ageMs < 0) continue;
|
||||
|
||||
const dragFactor = particle.drag ** (dtSeconds * 60);
|
||||
|
||||
switch (particle.style) {
|
||||
case 'spiral':
|
||||
stepSpiralParticle(particle, dtSeconds);
|
||||
break;
|
||||
case 'bounce':
|
||||
stepBounceParticle(particle, dtSeconds, dragFactor);
|
||||
break;
|
||||
default:
|
||||
stepDefaultParticle(particle, dtSeconds, dragFactor);
|
||||
break;
|
||||
}
|
||||
|
||||
particle.phase += dtSeconds * (particle.twinkle ? 9 : 5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,9 +331,9 @@ export function drawBurstParticles(
|
||||
dpr: number,
|
||||
now: number,
|
||||
) {
|
||||
for (const particle of particles) {
|
||||
particles.forEach((particle) => {
|
||||
const state = particleDrawState(particle, now);
|
||||
if (!state) continue;
|
||||
if (!state) return;
|
||||
|
||||
context.globalAlpha = state.opacity;
|
||||
|
||||
@@ -348,7 +346,7 @@ export function drawBurstParticles(
|
||||
|
||||
context.setTransform(cos, sin, -sin, cos, state.x * dpr, state.y * dpr);
|
||||
context.drawImage(emojiCanvas, -halfSize, -halfSize, drawSize, drawSize);
|
||||
}
|
||||
});
|
||||
|
||||
context.globalAlpha = 1;
|
||||
context.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
|
||||
@@ -94,10 +94,6 @@ type EmojiBitmap = {
|
||||
canvasScale: number;
|
||||
};
|
||||
|
||||
function getEmojiCanvas(emoji: string, tintColor?: string, cssPx?: number): HTMLCanvasElement {
|
||||
return getEmojiBitmap(emoji, tintColor, cssPx, 0).canvas;
|
||||
}
|
||||
|
||||
function getEmojiBitmap(
|
||||
emoji: string,
|
||||
tintColor: string | undefined,
|
||||
@@ -138,6 +134,10 @@ function getEmojiBitmap(
|
||||
return { canvas, canvasScale: size / Math.max(fontPx, 1) };
|
||||
}
|
||||
|
||||
function getEmojiCanvas(emoji: string, tintColor?: string, cssPx?: number): HTMLCanvasElement {
|
||||
return getEmojiBitmap(emoji, tintColor, cssPx, 0).canvas;
|
||||
}
|
||||
|
||||
function setHeroEmoji(hero: HeroFace, emoji: string) {
|
||||
const bitmap = getEmojiBitmap(emoji, undefined, hero.drawSize, HERO_PAD_RATIO);
|
||||
hero.emoji = emoji;
|
||||
@@ -288,14 +288,14 @@ function settleParticle(sim: FireworkSim, p: FireworkParticle) {
|
||||
// Prefer the intended column; spill to neighbors if that stack is already tall.
|
||||
let bestCol = col;
|
||||
let bestH = sim.pileCols[col];
|
||||
for (const delta of [0, -1, 1, -2, 2]) {
|
||||
[0, -1, 1, -2, 2].forEach((delta) => {
|
||||
const c = col + delta;
|
||||
if (c < 0 || c >= cols) continue;
|
||||
if (c < 0 || c >= cols) return;
|
||||
if (sim.pileCols[c] < bestH) {
|
||||
bestH = sim.pileCols[c];
|
||||
bestCol = c;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const stack = sim.pileCols[bestCol];
|
||||
sim.pileCols[bestCol] = stack + 1;
|
||||
@@ -408,32 +408,32 @@ export function stepFireworkSim(sim: FireworkSim, now: number, dtSeconds: number
|
||||
|
||||
for (let i = 0; i < sim.particles.length; i += 1) {
|
||||
const p = sim.particles[i];
|
||||
if (p.settled) continue;
|
||||
if (!p.settled) {
|
||||
p.vy += g * dt;
|
||||
p.vx *= DRAG;
|
||||
p.vy *= DRAG;
|
||||
p.x += p.vx * dt;
|
||||
p.y += p.vy * dt;
|
||||
p.angle += p.spin * dt;
|
||||
|
||||
p.vy += g * dt;
|
||||
p.vx *= DRAG;
|
||||
p.vy *= DRAG;
|
||||
p.x += p.vx * dt;
|
||||
p.y += p.vy * dt;
|
||||
p.angle += p.spin * dt;
|
||||
if (p.x < left) {
|
||||
p.x = left;
|
||||
p.vx = Math.abs(p.vx) * BOUNCE;
|
||||
} else if (p.x > right) {
|
||||
p.x = right;
|
||||
p.vx = -Math.abs(p.vx) * BOUNCE;
|
||||
}
|
||||
|
||||
if (p.x < left) {
|
||||
p.x = left;
|
||||
p.vx = Math.abs(p.vx) * BOUNCE;
|
||||
} else if (p.x > right) {
|
||||
p.x = right;
|
||||
p.vx = -Math.abs(p.vx) * BOUNCE;
|
||||
}
|
||||
|
||||
if (p.y >= floor - p.halfSize) {
|
||||
p.y = floor - p.halfSize;
|
||||
const speed = Math.hypot(p.vx, p.vy);
|
||||
if (speed < SETTLE_SPEED || Math.abs(p.vy) < SETTLE_SPEED * 0.55) {
|
||||
settleParticle(sim, p);
|
||||
} else {
|
||||
p.vy = -Math.abs(p.vy) * BOUNCE;
|
||||
p.vx *= 0.85;
|
||||
p.spin *= 0.7;
|
||||
if (p.y >= floor - p.halfSize) {
|
||||
p.y = floor - p.halfSize;
|
||||
const speed = Math.hypot(p.vx, p.vy);
|
||||
if (speed < SETTLE_SPEED || Math.abs(p.vy) < SETTLE_SPEED * 0.55) {
|
||||
settleParticle(sim, p);
|
||||
} else {
|
||||
p.vy = -Math.abs(p.vy) * BOUNCE;
|
||||
p.vx *= 0.85;
|
||||
p.spin *= 0.7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -472,30 +472,30 @@ export function drawFireworkSim(context: CanvasRenderingContext2D, sim: Firework
|
||||
|
||||
for (let i = 0; i < sim.particles.length; i += 1) {
|
||||
const p = sim.particles[i];
|
||||
if (p.settled) continue;
|
||||
if (!p.settled) {
|
||||
const ageMs = now - p.bornAt;
|
||||
if (ageMs >= 0) {
|
||||
let opacity = fade;
|
||||
let scale = 1;
|
||||
if (ageMs < SPARKLE_IN_MS) {
|
||||
const t = ageMs / SPARKLE_IN_MS;
|
||||
const appear = t * t * (3 - 2 * t);
|
||||
scale = 0.5 + 0.65 * appear;
|
||||
opacity *= appear;
|
||||
}
|
||||
if (opacity > 0.02) {
|
||||
const rad = (p.angle * Math.PI) / 180;
|
||||
const size = p.drawSize * scale;
|
||||
const half = size / 2;
|
||||
const cos = Math.cos(rad);
|
||||
const sin = Math.sin(rad);
|
||||
|
||||
const ageMs = now - p.bornAt;
|
||||
if (ageMs < 0) continue;
|
||||
|
||||
let opacity = fade;
|
||||
let scale = 1;
|
||||
if (ageMs < SPARKLE_IN_MS) {
|
||||
const t = ageMs / SPARKLE_IN_MS;
|
||||
const appear = t * t * (3 - 2 * t);
|
||||
scale = 0.5 + 0.65 * appear;
|
||||
opacity *= appear;
|
||||
context.globalAlpha = opacity;
|
||||
context.setTransform(cos, sin, -sin, cos, p.x, p.y);
|
||||
context.drawImage(p.emojiCanvas, -half, -half, size, size);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opacity <= 0.02) continue;
|
||||
|
||||
const rad = (p.angle * Math.PI) / 180;
|
||||
const size = p.drawSize * scale;
|
||||
const half = size / 2;
|
||||
const cos = Math.cos(rad);
|
||||
const sin = Math.sin(rad);
|
||||
|
||||
context.globalAlpha = opacity;
|
||||
context.setTransform(cos, sin, -sin, cos, p.x, p.y);
|
||||
context.drawImage(p.emojiCanvas, -half, -half, size, size);
|
||||
}
|
||||
|
||||
context.globalAlpha = 1;
|
||||
|
||||
@@ -38,18 +38,6 @@ function scheduleBurstFromValues(
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleBurst(
|
||||
event: MatrixEvent,
|
||||
onBurst: (burst: EmojiConfettiBurst) => void,
|
||||
attempt = 0,
|
||||
) {
|
||||
const eventId = event.getId();
|
||||
if (!eventId) return;
|
||||
|
||||
const { emojis, targetEventId } = parseEmojiConfettiContent(event.getContent());
|
||||
scheduleBurstFromValues(eventId, emojis, targetEventId, onBurst, attempt);
|
||||
}
|
||||
|
||||
function parseEmojiConfettiContent(content: unknown): { emojis: string[]; targetEventId?: string } {
|
||||
const confettiContent = content as EmojiConfettiContent;
|
||||
const emojis = Array.isArray(confettiContent.emojis)
|
||||
@@ -67,6 +55,18 @@ function parseEmojiConfettiContent(content: unknown): { emojis: string[]; target
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBurst(
|
||||
event: MatrixEvent,
|
||||
onBurst: (burst: EmojiConfettiBurst) => void,
|
||||
attempt = 0,
|
||||
) {
|
||||
const eventId = event.getId();
|
||||
if (!eventId) return;
|
||||
|
||||
const { emojis, targetEventId } = parseEmojiConfettiContent(event.getContent());
|
||||
scheduleBurstFromValues(eventId, emojis, targetEventId, onBurst, attempt);
|
||||
}
|
||||
|
||||
export function useEmojiConfetti(room: Room) {
|
||||
const [bursts, setBursts] = useState<EmojiConfettiBurst[]>([]);
|
||||
const seenEventIdsRef = useRef(new Set<string>());
|
||||
|
||||
@@ -238,7 +238,7 @@ const formatDayLabel = (ts: number): string => {
|
||||
const groupMediaByMonthAndDay = (items: RoomMediaItem[]): MediaMonthGroup[] => {
|
||||
const months: MediaMonthGroup[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
items.forEach((item) => {
|
||||
const date = new Date(item.ts);
|
||||
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
|
||||
const dayKey = `${monthKey}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
@@ -264,7 +264,7 @@ const groupMediaByMonthAndDay = (items: RoomMediaItem[]): MediaMonthGroup[] => {
|
||||
}
|
||||
|
||||
day.items.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
return months;
|
||||
};
|
||||
@@ -295,9 +295,9 @@ export const MediaDrawer = as<'div', MediaDrawerProps>(
|
||||
|
||||
const senders = useMemo<MediaSenderChip[]>(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const item of items) {
|
||||
items.forEach((item) => {
|
||||
counts.set(item.sender, (counts.get(item.sender) ?? 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(counts.entries())
|
||||
.map(([userId, count]) => ({
|
||||
|
||||
@@ -177,7 +177,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
|
||||
|
||||
// Fallback scroll if the page just mounted and tiles need a moment to render.
|
||||
useEffect(() => {
|
||||
if (!focusAnchorId) return;
|
||||
if (!focusAnchorId) return undefined;
|
||||
let cancelled = false;
|
||||
let attempts = 0;
|
||||
|
||||
|
||||
@@ -388,11 +388,11 @@ export function CollectiblesSection({ collectibles, onApply }: CollectiblesSecti
|
||||
useEffect(() => {
|
||||
setSelectedByGroup((prev) => {
|
||||
const next = { ...prev };
|
||||
for (const group of filteredGroups) {
|
||||
filteredGroups.forEach((group) => {
|
||||
if (!next[group.id] || !group.items.some((item) => item.skuId === next[group.id])) {
|
||||
next[group.id] = group.items[0]?.skuId ?? '';
|
||||
}
|
||||
}
|
||||
});
|
||||
return next;
|
||||
});
|
||||
}, [filteredGroups]);
|
||||
|
||||
@@ -88,10 +88,10 @@ function ProfileBanner({
|
||||
const decoration = collectibles.avatar_decoration;
|
||||
if (!decoration) return undefined;
|
||||
const assetUrls: Record<string, string | undefined> = {};
|
||||
for (const [role, mxc] of Object.entries(decoration.assets)) {
|
||||
Object.entries(decoration.assets).forEach(([role, mxc]) => {
|
||||
assetUrls[`avatar_decoration:${role}`] =
|
||||
mxcUrlToHttp(mx, mxc, useAuthentication) ?? undefined;
|
||||
}
|
||||
});
|
||||
return pickAvatarDecorationUrl(assetUrls);
|
||||
}, [collectibles.avatar_decoration, mx, useAuthentication]);
|
||||
|
||||
|
||||
@@ -30,9 +30,9 @@ export function getStoreVersion(): number {
|
||||
*/
|
||||
export function dispatchPluginButtonsChanged(): void {
|
||||
storeVersion += 1;
|
||||
for (const listener of listeners) {
|
||||
listeners.forEach((listener) => {
|
||||
listener();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
interface PluginButtonSlotProps {
|
||||
|
||||
@@ -49,51 +49,47 @@ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) {
|
||||
console.error(
|
||||
`[PluginLoader] Plugin ${installedPlugin.id} does not export a valid plugin object`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof plugin.onLoad !== 'function') {
|
||||
} else if (typeof plugin.onLoad !== 'function') {
|
||||
console.error(
|
||||
`[PluginLoader] Plugin ${installedPlugin.id} does not have an onLoad function`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const context = createPluginContext(
|
||||
{
|
||||
pluginId: installedPlugin.id,
|
||||
eventClient: matrixClient as any,
|
||||
onNotify: async (opts) => {
|
||||
await sendNotification({
|
||||
title: opts.title,
|
||||
body: opts.body,
|
||||
path: undefined,
|
||||
});
|
||||
} else {
|
||||
const context = createPluginContext(
|
||||
{
|
||||
pluginId: installedPlugin.id,
|
||||
eventClient: matrixClient as any,
|
||||
onNotify: async (opts) => {
|
||||
await sendNotification({
|
||||
title: opts.title,
|
||||
body: opts.body,
|
||||
path: undefined,
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
pluginRegistry,
|
||||
);
|
||||
pluginRegistry,
|
||||
);
|
||||
|
||||
const compatContext = Object.assign(context as Record<string, unknown>, {
|
||||
matrixClient,
|
||||
matrix: {
|
||||
on: (eventType: string, handler: (...args: unknown[]) => void) =>
|
||||
matrixClient.on(eventType as any, handler as any),
|
||||
off: (eventType: string, handler: (...args: unknown[]) => void) =>
|
||||
matrixClient.off(eventType as any, handler as any),
|
||||
},
|
||||
React,
|
||||
lucide,
|
||||
});
|
||||
const compatContext = Object.assign(context as Record<string, unknown>, {
|
||||
matrixClient,
|
||||
matrix: {
|
||||
on: (eventType: string, handler: (...args: unknown[]) => void) =>
|
||||
matrixClient.on(eventType as any, handler as any),
|
||||
off: (eventType: string, handler: (...args: unknown[]) => void) =>
|
||||
matrixClient.off(eventType as any, handler as any),
|
||||
},
|
||||
React,
|
||||
lucide,
|
||||
});
|
||||
|
||||
console.log('[PluginLoader] compatContext.React:', !!compatContext.React);
|
||||
console.log('[PluginLoader] compatContext.ui:', !!compatContext.ui);
|
||||
console.log('[PluginLoader] About to register plugin and call onLoad...');
|
||||
console.log('[PluginLoader] compatContext.React:', !!compatContext.React);
|
||||
console.log('[PluginLoader] compatContext.ui:', !!compatContext.ui);
|
||||
console.log('[PluginLoader] About to register plugin and call onLoad...');
|
||||
|
||||
pluginRegistry.registerPlugin(installedPlugin.id, plugin, context);
|
||||
await plugin.onLoad(compatContext as any);
|
||||
console.log(`[PluginLoader] Successfully loaded plugin: ${installedPlugin.id}`);
|
||||
dispatchPluginButtonsChanged();
|
||||
pluginRegistry.registerPlugin(installedPlugin.id, plugin, context);
|
||||
await plugin.onLoad(compatContext as any);
|
||||
console.log(`[PluginLoader] Successfully loaded plugin: ${installedPlugin.id}`);
|
||||
dispatchPluginButtonsChanged();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to load plugin ${installedPlugin.id}:`, error);
|
||||
pluginRegistry.addLog(installedPlugin.id, 'error', ['Failed to load:', error]);
|
||||
|
||||
@@ -115,93 +115,93 @@ export function Permissions({ requestClose }: PermissionsProps) {
|
||||
for (const childId of syncableChildren) {
|
||||
try {
|
||||
const childRoom = mx.getRoom(childId);
|
||||
if (!childRoom) continue;
|
||||
|
||||
// Get current power levels in the child room
|
||||
const childPowerLevelsEvent = childRoom.currentState.getStateEvents(
|
||||
StateEvent.RoomPowerLevels,
|
||||
'',
|
||||
);
|
||||
const childPowerLevels = childPowerLevelsEvent?.getContent() || {};
|
||||
|
||||
// Get my power level in the child room
|
||||
const myPowerInChild =
|
||||
childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0;
|
||||
|
||||
// Build merged users: only sync users with power <= mine, preserve higher-powered users
|
||||
const mergedUsers: Record<string, number> = {};
|
||||
|
||||
// Copy users from parent where power <= my power in child
|
||||
if (powerLevels.users) {
|
||||
Object.entries(powerLevels.users).forEach(([userId, power]) => {
|
||||
if (power <= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Preserve all users in child room who have power >= mine
|
||||
if (childPowerLevels.users) {
|
||||
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
|
||||
if (power >= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cap all power level values at my power level
|
||||
const capPowerLevel = (value: any) => {
|
||||
if (typeof value === 'number') {
|
||||
return Math.min(value, myPowerInChild);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
// Create the merged power levels with capped values
|
||||
const mergedPowerLevels: any = {
|
||||
...powerLevels,
|
||||
users: mergedUsers,
|
||||
ban: capPowerLevel(powerLevels.ban),
|
||||
kick: capPowerLevel(powerLevels.kick),
|
||||
redact: capPowerLevel(powerLevels.redact),
|
||||
invite: capPowerLevel(powerLevels.invite),
|
||||
events_default: capPowerLevel(powerLevels.events_default),
|
||||
state_default: capPowerLevel(powerLevels.state_default),
|
||||
users_default: capPowerLevel(powerLevels.users_default),
|
||||
};
|
||||
|
||||
// Cap event-specific power levels
|
||||
if (powerLevels.events) {
|
||||
mergedPowerLevels.events = {};
|
||||
Object.entries(powerLevels.events).forEach(([eventType, power]) => {
|
||||
mergedPowerLevels.events[eventType] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
// Cap notification power levels
|
||||
if (powerLevels.notifications) {
|
||||
mergedPowerLevels.notifications = {};
|
||||
Object.entries(powerLevels.notifications).forEach(([key, power]) => {
|
||||
mergedPowerLevels.notifications[key] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels);
|
||||
|
||||
// Also copy power level tags if they exist
|
||||
if (powerLevelTags) {
|
||||
await mx.sendStateEvent(
|
||||
childId,
|
||||
'in.cinny.room.power_level_tags' as any,
|
||||
powerLevelTags,
|
||||
if (childRoom) {
|
||||
// Get current power levels in the child room
|
||||
const childPowerLevelsEvent = childRoom.currentState.getStateEvents(
|
||||
StateEvent.RoomPowerLevels,
|
||||
'',
|
||||
);
|
||||
}
|
||||
const childPowerLevels = childPowerLevelsEvent?.getContent() || {};
|
||||
|
||||
completed += 1;
|
||||
// Get my power level in the child room
|
||||
const myPowerInChild =
|
||||
childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0;
|
||||
|
||||
// Add a small delay to avoid rate limiting
|
||||
if (completed < total) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
// Build merged users: only sync users with power <= mine, preserve higher-powered users
|
||||
const mergedUsers: Record<string, number> = {};
|
||||
|
||||
// Copy users from parent where power <= my power in child
|
||||
if (powerLevels.users) {
|
||||
Object.entries(powerLevels.users).forEach(([userId, power]) => {
|
||||
if (power <= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Preserve all users in child room who have power >= mine
|
||||
if (childPowerLevels.users) {
|
||||
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
|
||||
if (power >= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cap all power level values at my power level
|
||||
const capPowerLevel = (value: any) => {
|
||||
if (typeof value === 'number') {
|
||||
return Math.min(value, myPowerInChild);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
// Create the merged power levels with capped values
|
||||
const mergedPowerLevels: any = {
|
||||
...powerLevels,
|
||||
users: mergedUsers,
|
||||
ban: capPowerLevel(powerLevels.ban),
|
||||
kick: capPowerLevel(powerLevels.kick),
|
||||
redact: capPowerLevel(powerLevels.redact),
|
||||
invite: capPowerLevel(powerLevels.invite),
|
||||
events_default: capPowerLevel(powerLevels.events_default),
|
||||
state_default: capPowerLevel(powerLevels.state_default),
|
||||
users_default: capPowerLevel(powerLevels.users_default),
|
||||
};
|
||||
|
||||
// Cap event-specific power levels
|
||||
if (powerLevels.events) {
|
||||
mergedPowerLevels.events = {};
|
||||
Object.entries(powerLevels.events).forEach(([eventType, power]) => {
|
||||
mergedPowerLevels.events[eventType] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
// Cap notification power levels
|
||||
if (powerLevels.notifications) {
|
||||
mergedPowerLevels.notifications = {};
|
||||
Object.entries(powerLevels.notifications).forEach(([key, power]) => {
|
||||
mergedPowerLevels.notifications[key] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels);
|
||||
|
||||
// Also copy power level tags if they exist
|
||||
if (powerLevelTags) {
|
||||
await mx.sendStateEvent(
|
||||
childId,
|
||||
'in.cinny.room.power_level_tags' as any,
|
||||
powerLevelTags,
|
||||
);
|
||||
}
|
||||
|
||||
completed += 1;
|
||||
|
||||
// Add a small delay to avoid rate limiting
|
||||
if (completed < total) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to sync permissions to ${childId}:`, error);
|
||||
@@ -221,84 +221,84 @@ export function Permissions({ requestClose }: PermissionsProps) {
|
||||
for (const childId of syncableChildren) {
|
||||
try {
|
||||
const childRoom = mx.getRoom(childId);
|
||||
if (!childRoom) continue;
|
||||
if (childRoom) {
|
||||
// Get current power levels in the child room
|
||||
const childPowerLevelsEvent = childRoom.currentState.getStateEvents(
|
||||
StateEvent.RoomPowerLevels,
|
||||
'',
|
||||
);
|
||||
const childPowerLevels = childPowerLevelsEvent?.getContent() || {};
|
||||
|
||||
// Get current power levels in the child room
|
||||
const childPowerLevelsEvent = childRoom.currentState.getStateEvents(
|
||||
StateEvent.RoomPowerLevels,
|
||||
'',
|
||||
);
|
||||
const childPowerLevels = childPowerLevelsEvent?.getContent() || {};
|
||||
// Get my power level in the child room
|
||||
const myPowerInChild =
|
||||
childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0;
|
||||
|
||||
// Get my power level in the child room
|
||||
const myPowerInChild =
|
||||
childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0;
|
||||
// Build merged users: only sync users with power <= mine, preserve higher-powered users
|
||||
const mergedUsers: Record<string, number> = {};
|
||||
|
||||
// Build merged users: only sync users with power <= mine, preserve higher-powered users
|
||||
const mergedUsers: Record<string, number> = {};
|
||||
|
||||
// Copy users from parent where power <= my power in child
|
||||
if (powerLevels.users) {
|
||||
Object.entries(powerLevels.users).forEach(([userId, power]) => {
|
||||
if (power <= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Preserve all users in child room who have power >= mine
|
||||
if (childPowerLevels.users) {
|
||||
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
|
||||
if (power >= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cap all power level values at my power level
|
||||
const capPowerLevel = (value: any) => {
|
||||
if (typeof value === 'number') {
|
||||
return Math.min(value, myPowerInChild);
|
||||
// Copy users from parent where power <= my power in child
|
||||
if (powerLevels.users) {
|
||||
Object.entries(powerLevels.users).forEach(([userId, power]) => {
|
||||
if (power <= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
// Create the merged power levels with capped values
|
||||
const mergedPowerLevels: any = {
|
||||
...powerLevels,
|
||||
users: mergedUsers,
|
||||
ban: capPowerLevel(powerLevels.ban),
|
||||
kick: capPowerLevel(powerLevels.kick),
|
||||
redact: capPowerLevel(powerLevels.redact),
|
||||
invite: capPowerLevel(powerLevels.invite),
|
||||
events_default: capPowerLevel(powerLevels.events_default),
|
||||
state_default: capPowerLevel(powerLevels.state_default),
|
||||
users_default: capPowerLevel(powerLevels.users_default),
|
||||
};
|
||||
// Preserve all users in child room who have power >= mine
|
||||
if (childPowerLevels.users) {
|
||||
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
|
||||
if (power >= myPowerInChild) {
|
||||
mergedUsers[userId] = power;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cap event-specific power levels
|
||||
if (powerLevels.events) {
|
||||
mergedPowerLevels.events = {};
|
||||
Object.entries(powerLevels.events).forEach(([eventType, power]) => {
|
||||
mergedPowerLevels.events[eventType] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
// Cap all power level values at my power level
|
||||
const capPowerLevel = (value: any) => {
|
||||
if (typeof value === 'number') {
|
||||
return Math.min(value, myPowerInChild);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
// Cap notification power levels
|
||||
if (powerLevels.notifications) {
|
||||
mergedPowerLevels.notifications = {};
|
||||
Object.entries(powerLevels.notifications).forEach(([key, power]) => {
|
||||
mergedPowerLevels.notifications[key] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
// Create the merged power levels with capped values
|
||||
const mergedPowerLevels: any = {
|
||||
...powerLevels,
|
||||
users: mergedUsers,
|
||||
ban: capPowerLevel(powerLevels.ban),
|
||||
kick: capPowerLevel(powerLevels.kick),
|
||||
redact: capPowerLevel(powerLevels.redact),
|
||||
invite: capPowerLevel(powerLevels.invite),
|
||||
events_default: capPowerLevel(powerLevels.events_default),
|
||||
state_default: capPowerLevel(powerLevels.state_default),
|
||||
users_default: capPowerLevel(powerLevels.users_default),
|
||||
};
|
||||
|
||||
await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels);
|
||||
// Cap event-specific power levels
|
||||
if (powerLevels.events) {
|
||||
mergedPowerLevels.events = {};
|
||||
Object.entries(powerLevels.events).forEach(([eventType, power]) => {
|
||||
mergedPowerLevels.events[eventType] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
completed += 1;
|
||||
// Cap notification power levels
|
||||
if (powerLevels.notifications) {
|
||||
mergedPowerLevels.notifications = {};
|
||||
Object.entries(powerLevels.notifications).forEach(([key, power]) => {
|
||||
mergedPowerLevels.notifications[key] = capPowerLevel(power);
|
||||
});
|
||||
}
|
||||
|
||||
// Add a small delay to avoid rate limiting
|
||||
if (completed < total) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels);
|
||||
|
||||
completed += 1;
|
||||
|
||||
// Add a small delay to avoid rate limiting
|
||||
if (completed < total) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to sync power levels to ${childId}:`, error);
|
||||
|
||||
@@ -268,13 +268,13 @@ export function useAutoJoinOnSpaceVisit(space: Room | undefined): void {
|
||||
|
||||
useEffect(() => {
|
||||
if (!space || !settings.autoJoinSpaceRooms) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
if (!isSpace(space)) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
if (space.getMyMembership() !== Membership.Join) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const spaceId = space.roomId;
|
||||
|
||||
@@ -154,9 +154,10 @@ export const useRoomMediaEvents = (room: Room) => {
|
||||
for (const raw of response.chunk ?? []) {
|
||||
const mEvent = await decryptEvent(raw);
|
||||
const item = toMediaItem(mEvent);
|
||||
if (!item || cache.seenIds.has(item.eventId)) continue;
|
||||
cache.seenIds.add(item.eventId);
|
||||
collected.push(item);
|
||||
if (item && !cache.seenIds.has(item.eventId)) {
|
||||
cache.seenIds.add(item.eventId);
|
||||
collected.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
if (collected.length >= TARGET_BATCH || !response.end) break;
|
||||
@@ -212,9 +213,10 @@ export const useRoomMediaEvents = (room: Room) => {
|
||||
for (let i = localEvents.length - 1; i >= 0; i -= 1) {
|
||||
const mEvent = await decryptEvent(localEvents[i]);
|
||||
const item = toMediaItem(mEvent);
|
||||
if (!item || cache.seenIds.has(item.eventId)) continue;
|
||||
cache.seenIds.add(item.eventId);
|
||||
localFound.push(item);
|
||||
if (item && !cache.seenIds.has(item.eventId)) {
|
||||
cache.seenIds.add(item.eventId);
|
||||
localFound.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
@@ -42,11 +42,12 @@ const MAX_AUTO_PAGE_COUNT = 50;
|
||||
export function buildParentByRoomId(rooms: Iterable<IHierarchyRoom>): Map<string, string> {
|
||||
const parentByRoomId = new Map<string, string>();
|
||||
for (const room of rooms) {
|
||||
if (!room?.room_id || !Array.isArray(room.children_state)) continue;
|
||||
for (const childState of room.children_state) {
|
||||
if (childState?.type !== StateEvent.SpaceChild) continue;
|
||||
if (typeof childState.state_key !== 'string') continue;
|
||||
parentByRoomId.set(childState.state_key, room.room_id);
|
||||
if (room?.room_id && Array.isArray(room.children_state)) {
|
||||
room.children_state.forEach((childState) => {
|
||||
if (childState?.type !== StateEvent.SpaceChild) return;
|
||||
if (typeof childState.state_key !== 'string') return;
|
||||
parentByRoomId.set(childState.state_key, room.room_id);
|
||||
});
|
||||
}
|
||||
}
|
||||
return parentByRoomId;
|
||||
|
||||
@@ -110,10 +110,11 @@ export function useOtherUserCollectibles(userId: string): CollectibleProfileFiel
|
||||
] as const;
|
||||
|
||||
for (const [kind, collectible] of entries) {
|
||||
if (!collectible) continue;
|
||||
for (const [role, mxc] of Object.entries(collectible.assets)) {
|
||||
const blobUrl = await getProfileAssetUrl(mx, mxc, useAuthentication);
|
||||
if (blobUrl) urls[`${kind}:${role}`] = blobUrl;
|
||||
if (collectible) {
|
||||
for (const [role, mxc] of Object.entries(collectible.assets)) {
|
||||
const blobUrl = await getProfileAssetUrl(mx, mxc, useAuthentication);
|
||||
if (blobUrl) urls[`${kind}:${role}`] = blobUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,12 +97,12 @@ export function useTypingVerbs(userIds: string[]): Record<string, string | undef
|
||||
if (!cancelled) setTick((tick) => tick + 1);
|
||||
};
|
||||
|
||||
for (const userId of key.split(',')) {
|
||||
if (getCachedProfileFields(userId)) continue;
|
||||
key.split(',').forEach((userId) => {
|
||||
if (getCachedProfileFields(userId)) return;
|
||||
getProfileFields(mx, userId)
|
||||
.then(rerender)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -111,6 +111,8 @@ export function useTypingVerbs(userIds: string[]): Record<string, string | undef
|
||||
}, [mx, key]);
|
||||
|
||||
const verbs: Record<string, string | undefined> = {};
|
||||
for (const userId of userIds) verbs[userId] = getCachedTypingVerb(userId);
|
||||
userIds.forEach((userId) => {
|
||||
verbs[userId] = getCachedTypingVerb(userId);
|
||||
});
|
||||
return verbs;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export const useViewTransitions = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (!supportsViewTransitions()) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Mark that we support view transitions
|
||||
|
||||
+110
-113
@@ -174,6 +174,51 @@ export function initPaarrotAPI(matrixClient: MatrixClient) {
|
||||
console.log('Paarrot API: Handler initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently active room ID
|
||||
* Extracts room ID from the current URL pathname
|
||||
*/
|
||||
function getCurrentRoomId(): string | null {
|
||||
try {
|
||||
// Get the pathname from URL
|
||||
// Support both normal routing and hash routing
|
||||
let { pathname } = window.location;
|
||||
|
||||
// If using hash router, parse from hash
|
||||
if (window.location.hash) {
|
||||
const hashMatch = window.location.hash.match(/#(.+)/);
|
||||
if (hashMatch) {
|
||||
pathname = hashMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
// URL patterns:
|
||||
// /home/:roomIdOrAlias/:eventId?/
|
||||
// /direct/:roomIdOrAlias/:eventId?/
|
||||
// /:spaceIdOrAlias/:roomIdOrAlias/:eventId?/
|
||||
|
||||
// Try to match room patterns
|
||||
const patterns = [
|
||||
/^\/home\/([^/]+)/, // /home/:roomIdOrAlias
|
||||
/^\/direct\/([^/]+)/, // /direct/:roomIdOrAlias
|
||||
/^\/[^/]+\/([^/]+)/, // /:spaceIdOrAlias/:roomIdOrAlias (space rooms)
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = pathname.match(pattern);
|
||||
if (match && match[1]) {
|
||||
// Decode URI component in case the room ID was encoded
|
||||
return decodeURIComponent(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Paarrot API: Error getting current room ID:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current app status
|
||||
*/
|
||||
@@ -483,49 +528,48 @@ function collectRecentMessages(room: any, limit: number): ApiMessage[] {
|
||||
|
||||
for (let i = liveEvents.length - 1; i >= 0 && messages.length < limit; i -= 1) {
|
||||
const evt = liveEvents[i];
|
||||
if (!evt) continue;
|
||||
if (typeof evt.isRedacted === 'function' && evt.isRedacted()) continue;
|
||||
if (reactionOrEditEvent(evt)) continue;
|
||||
|
||||
const type = evt.getType?.();
|
||||
if (
|
||||
type !== MessageEvent.RoomMessage &&
|
||||
type !== MessageEvent.RoomMessageEncrypted &&
|
||||
type !== MessageEvent.Sticker
|
||||
evt &&
|
||||
!(typeof evt.isRedacted === 'function' && evt.isRedacted()) &&
|
||||
!reactionOrEditEvent(evt)
|
||||
) {
|
||||
continue;
|
||||
const type = evt.getType?.();
|
||||
if (
|
||||
type === MessageEvent.RoomMessage ||
|
||||
type === MessageEvent.RoomMessageEncrypted ||
|
||||
type === MessageEvent.Sticker
|
||||
) {
|
||||
const content = evt.getContent?.() ?? {};
|
||||
const sender = evt.getSender?.() ?? '';
|
||||
const member = sender ? room.getMember?.(sender) : null;
|
||||
|
||||
if (type === MessageEvent.RoomMessageEncrypted && !content.msgtype) {
|
||||
messages.push({
|
||||
eventId: evt.getId?.() ?? '',
|
||||
roomId,
|
||||
roomName,
|
||||
isDirect,
|
||||
sender,
|
||||
senderName: member?.name ?? sender,
|
||||
timestamp: evt.getTs?.() ?? 0,
|
||||
msgtype: 'm.encrypted',
|
||||
body: '[encrypted]',
|
||||
});
|
||||
} else {
|
||||
messages.push({
|
||||
eventId: evt.getId?.() ?? '',
|
||||
roomId,
|
||||
roomName,
|
||||
isDirect,
|
||||
sender,
|
||||
senderName: member?.name ?? sender,
|
||||
timestamp: evt.getTs?.() ?? 0,
|
||||
msgtype: content.msgtype || (type === MessageEvent.Sticker ? 'm.sticker' : 'm.text'),
|
||||
body: content.body || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const content = evt.getContent?.() ?? {};
|
||||
const sender = evt.getSender?.() ?? '';
|
||||
const member = sender ? room.getMember?.(sender) : null;
|
||||
|
||||
if (type === MessageEvent.RoomMessageEncrypted && !content.msgtype) {
|
||||
messages.push({
|
||||
eventId: evt.getId?.() ?? '',
|
||||
roomId,
|
||||
roomName,
|
||||
isDirect,
|
||||
sender,
|
||||
senderName: member?.name ?? sender,
|
||||
timestamp: evt.getTs?.() ?? 0,
|
||||
msgtype: 'm.encrypted',
|
||||
body: '[encrypted]',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
messages.push({
|
||||
eventId: evt.getId?.() ?? '',
|
||||
roomId,
|
||||
roomName,
|
||||
isDirect,
|
||||
sender,
|
||||
senderName: member?.name ?? sender,
|
||||
timestamp: evt.getTs?.() ?? 0,
|
||||
msgtype: content.msgtype || (type === MessageEvent.Sticker ? 'm.sticker' : 'm.text'),
|
||||
body: content.body || '',
|
||||
});
|
||||
}
|
||||
|
||||
return messages.reverse();
|
||||
@@ -592,35 +636,33 @@ async function getUnreadsByScope(matrixClient: any, scope: MessageScope) {
|
||||
}> = [];
|
||||
|
||||
for (const room of rooms) {
|
||||
if (getNotificationType(matrixClient, room.roomId) === NotificationType.Mute) {
|
||||
continue;
|
||||
}
|
||||
if (!roomHaveNotification(room) && !roomHaveUnread(matrixClient, room)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
getNotificationType(matrixClient, room.roomId) !== NotificationType.Mute &&
|
||||
(roomHaveNotification(room) || roomHaveUnread(matrixClient, room))
|
||||
) {
|
||||
const unreadInfo = getUnreadInfo(room);
|
||||
const latestMessages = collectRecentMessages(room, 1);
|
||||
const latest = latestMessages[0];
|
||||
|
||||
const unreadInfo = getUnreadInfo(room);
|
||||
const latestMessages = collectRecentMessages(room, 1);
|
||||
const latest = latestMessages[0];
|
||||
|
||||
unreads.push({
|
||||
roomId: room.roomId,
|
||||
name: room.name || 'Unnamed Room',
|
||||
isDirect: isDirectRoom(room),
|
||||
avatar: room.getMxcAvatarUrl?.() || null,
|
||||
total: unreadInfo.total,
|
||||
highlight: unreadInfo.highlight,
|
||||
latest: latest
|
||||
? {
|
||||
eventId: latest.eventId,
|
||||
sender: latest.sender,
|
||||
senderName: latest.senderName,
|
||||
timestamp: latest.timestamp,
|
||||
msgtype: latest.msgtype,
|
||||
body: latest.body,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
unreads.push({
|
||||
roomId: room.roomId,
|
||||
name: room.name || 'Unnamed Room',
|
||||
isDirect: isDirectRoom(room),
|
||||
avatar: room.getMxcAvatarUrl?.() || null,
|
||||
total: unreadInfo.total,
|
||||
highlight: unreadInfo.highlight,
|
||||
latest: latest
|
||||
? {
|
||||
eventId: latest.eventId,
|
||||
sender: latest.sender,
|
||||
senderName: latest.senderName,
|
||||
timestamp: latest.timestamp,
|
||||
msgtype: latest.msgtype,
|
||||
body: latest.body,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
unreads.sort((a, b) => {
|
||||
@@ -638,49 +680,4 @@ async function getUnreadsByScope(matrixClient: any, scope: MessageScope) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently active room ID
|
||||
* Extracts room ID from the current URL pathname
|
||||
*/
|
||||
function getCurrentRoomId(): string | null {
|
||||
try {
|
||||
// Get the pathname from URL
|
||||
// Support both normal routing and hash routing
|
||||
let { pathname } = window.location;
|
||||
|
||||
// If using hash router, parse from hash
|
||||
if (window.location.hash) {
|
||||
const hashMatch = window.location.hash.match(/#(.+)/);
|
||||
if (hashMatch) {
|
||||
pathname = hashMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
// URL patterns:
|
||||
// /home/:roomIdOrAlias/:eventId?/
|
||||
// /direct/:roomIdOrAlias/:eventId?/
|
||||
// /:spaceIdOrAlias/:roomIdOrAlias/:eventId?/
|
||||
|
||||
// Try to match room patterns
|
||||
const patterns = [
|
||||
/^\/home\/([^/]+)/, // /home/:roomIdOrAlias
|
||||
/^\/direct\/([^/]+)/, // /direct/:roomIdOrAlias
|
||||
/^\/[^/]+\/([^/]+)/, // /:spaceIdOrAlias/:roomIdOrAlias (space rooms)
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = pathname.match(pattern);
|
||||
if (match && match[1]) {
|
||||
// Decode URI component in case the room ID was encoded
|
||||
return decodeURIComponent(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Paarrot API: Error getting current room ID:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default { initPaarrotAPI };
|
||||
|
||||
@@ -569,35 +569,35 @@ function AndroidShareIntentHandler() {
|
||||
// Upload file
|
||||
const uploadResult = await mx.uploadContent(fileToUpload);
|
||||
const mxc = uploadResult?.content_uri;
|
||||
if (!mxc) continue;
|
||||
if (mxc) {
|
||||
// Determine message type and send
|
||||
const fileType = originalFile.type;
|
||||
let msgtype = 'm.file' as const;
|
||||
if (fileType.startsWith('image/')) msgtype = 'm.image' as const;
|
||||
else if (fileType.startsWith('video/')) msgtype = 'm.video' as const;
|
||||
else if (fileType.startsWith('audio/')) msgtype = 'm.audio' as const;
|
||||
|
||||
// Determine message type and send
|
||||
const fileType = originalFile.type;
|
||||
let msgtype = 'm.file' as const;
|
||||
if (fileType.startsWith('image/')) msgtype = 'm.image' as const;
|
||||
else if (fileType.startsWith('video/')) msgtype = 'm.video' as const;
|
||||
else if (fileType.startsWith('audio/')) msgtype = 'm.audio' as const;
|
||||
|
||||
const fileContent: any = {
|
||||
msgtype,
|
||||
body: originalFile.name,
|
||||
filename: originalFile.name,
|
||||
info: {
|
||||
mimetype: originalFile.type,
|
||||
size: originalFile.size,
|
||||
},
|
||||
};
|
||||
|
||||
if (encInfo) {
|
||||
fileContent.file = {
|
||||
...encInfo,
|
||||
url: mxc,
|
||||
const fileContent: any = {
|
||||
msgtype,
|
||||
body: originalFile.name,
|
||||
filename: originalFile.name,
|
||||
info: {
|
||||
mimetype: originalFile.type,
|
||||
size: originalFile.size,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
fileContent.url = mxc;
|
||||
}
|
||||
|
||||
await mx.sendMessage(roomId, fileContent);
|
||||
if (encInfo) {
|
||||
fileContent.file = {
|
||||
...encInfo,
|
||||
url: mxc,
|
||||
};
|
||||
} else {
|
||||
fileContent.url = mxc;
|
||||
}
|
||||
|
||||
await mx.sendMessage(roomId, fileContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +645,7 @@ function AndroidShareIntentHandler() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAndroidShareSupported()) return;
|
||||
if (!isAndroidShareSupported()) return undefined;
|
||||
|
||||
let mounted = true;
|
||||
let listenerHandle: { remove: () => Promise<void> } | undefined;
|
||||
|
||||
@@ -51,7 +51,7 @@ const useLogoutListener = (mx?: MatrixClient) => {
|
||||
*/
|
||||
const useVisibilitySync = (mx?: MatrixClient) => {
|
||||
useEffect(() => {
|
||||
if (!mx || !isTauriMobile()) return;
|
||||
if (!mx || !isTauriMobile()) return undefined;
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
@@ -96,7 +96,7 @@ const useVisibilitySync = (mx?: MatrixClient) => {
|
||||
*/
|
||||
const useBackgroundSync = (mx?: MatrixClient) => {
|
||||
useEffect(() => {
|
||||
if (!mx || !isTauriMobile()) return;
|
||||
if (!mx || !isTauriMobile()) return undefined;
|
||||
|
||||
// Start background sync with credentials from the Matrix client
|
||||
const startSync = async () => {
|
||||
@@ -298,7 +298,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
|
||||
// Timeout if sync takes too long - nudge the client rather than immediately erroring
|
||||
useEffect(() => {
|
||||
if (!mx || !loading) return;
|
||||
if (!mx || !loading) return undefined;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
console.warn('[ClientRoot] Sync taking too long, nudging client...');
|
||||
@@ -394,7 +394,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
|
||||
// Also nudge sync when the laptop wakes / network returns
|
||||
useEffect(() => {
|
||||
if (!mx) return;
|
||||
if (!mx) return undefined;
|
||||
|
||||
const nudge = () => {
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
|
||||
@@ -21,7 +21,7 @@ export function pruneAvatarCache(): void {
|
||||
if (loadedAvatars.size > MAX_CACHE_SIZE) {
|
||||
const iterator = loadedAvatars.values();
|
||||
// Remove oldest entries (first added)
|
||||
for (let i = 0; i < loadedAvatars.size - MAX_CACHE_SIZE; i++) {
|
||||
for (let i = 0; i < loadedAvatars.size - MAX_CACHE_SIZE; i += 1) {
|
||||
const result = iterator.next();
|
||||
if (!result.done) {
|
||||
loadedAvatars.delete(result.value);
|
||||
|
||||
@@ -543,6 +543,19 @@ export const setAppForegroundState = async (foreground: boolean): Promise<void>
|
||||
}
|
||||
};
|
||||
|
||||
/** Returns the current native UnifiedPush status, or undefined if unavailable. */
|
||||
export const getBackgroundSyncStatus = async (): Promise<UnifiedPushStatus | undefined> => {
|
||||
if (!isBackgroundSyncSupported()) return undefined;
|
||||
try {
|
||||
const { registerPlugin } = await loadCapacitorCore();
|
||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
||||
return await MatrixBackgroundSync.getStatus();
|
||||
} catch (err) {
|
||||
console.warn('[BackgroundSync] getStatus failed:', err);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Re-opens the UnifiedPush distributor selection dialog.
|
||||
* Allows users to re-select or change their push notification distributor without terminal access.
|
||||
@@ -581,16 +594,3 @@ export const requestResetPushRegistration = async (): Promise<{ success: boolean
|
||||
return { success: false };
|
||||
}
|
||||
};
|
||||
|
||||
/** Returns the current native UnifiedPush status, or undefined if unavailable. */
|
||||
export const getBackgroundSyncStatus = async (): Promise<UnifiedPushStatus | undefined> => {
|
||||
if (!isBackgroundSyncSupported()) return undefined;
|
||||
try {
|
||||
const { registerPlugin } = await loadCapacitorCore();
|
||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
||||
return await MatrixBackgroundSync.getStatus();
|
||||
} catch (err) {
|
||||
console.warn('[BackgroundSync] getStatus failed:', err);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -30,6 +30,10 @@ export function pickCatalogStaticPreviewUrl(item: DiscordCollectibleItem): strin
|
||||
}
|
||||
}
|
||||
|
||||
export function pickCatalogProfileEffectLoopUrl(item: DiscordCollectibleItem): string | undefined {
|
||||
return catalogAssetUrl(item, 'effect_1', 'effect_0', 'effect_2', 'effect_3');
|
||||
}
|
||||
|
||||
export function pickCatalogAnimatedPreviewUrl(item: DiscordCollectibleItem): string | undefined {
|
||||
switch (item.type) {
|
||||
case 'nameplate':
|
||||
@@ -47,10 +51,6 @@ export function pickCatalogProfileEffectIntroUrl(item: DiscordCollectibleItem):
|
||||
return catalogAssetUrl(item, 'effect_0');
|
||||
}
|
||||
|
||||
export function pickCatalogProfileEffectLoopUrl(item: DiscordCollectibleItem): string | undefined {
|
||||
return catalogAssetUrl(item, 'effect_1', 'effect_0', 'effect_2', 'effect_3');
|
||||
}
|
||||
|
||||
export function catalogProfileEffectIntroDurationMs(
|
||||
item: DiscordCollectibleItem,
|
||||
): number | undefined {
|
||||
|
||||
@@ -141,9 +141,9 @@ function replaceCdnUrls<T>(value: T, urlToMxc: Map<string, string>): T {
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
||||
Object.entries(value as Record<string, unknown>).forEach(([key, entry]) => {
|
||||
out[key] = replaceCdnUrls(entry, urlToMxc);
|
||||
}
|
||||
});
|
||||
return out as T;
|
||||
}
|
||||
return value;
|
||||
@@ -280,12 +280,12 @@ function dedupeVariantItems(items: DiscordCollectibleItem[]): DiscordCollectible
|
||||
export function groupCollectibleItems(items: DiscordCollectibleItem[]): CollectibleVariantGroup[] {
|
||||
const map = new Map<string, DiscordCollectibleItem[]>();
|
||||
|
||||
for (const item of items) {
|
||||
items.forEach((item) => {
|
||||
const key = variantGroupKey(item);
|
||||
const list = map.get(key);
|
||||
if (list) list.push(item);
|
||||
else map.set(key, [item]);
|
||||
}
|
||||
});
|
||||
|
||||
return [...map.entries()]
|
||||
.map(([id, groupItems]) => {
|
||||
|
||||
@@ -77,7 +77,7 @@ export function convertEmoticons(text: string): string {
|
||||
// e.g., :-) before :)
|
||||
const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length);
|
||||
|
||||
for (const emoticon of emoticons) {
|
||||
emoticons.forEach((emoticon) => {
|
||||
// Escape special regex characters
|
||||
const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&');
|
||||
|
||||
@@ -93,7 +93,7 @@ export function convertEmoticons(text: string): string {
|
||||
// Otherwise convert to emoji
|
||||
return prefix + EMOTICON_MAP[emoticon];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -111,7 +111,7 @@ export function convertEmoticonsInHtml(html: string): string {
|
||||
// Sort emoticons by length (longest first) to handle overlapping patterns
|
||||
const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length);
|
||||
|
||||
for (const emoticon of emoticons) {
|
||||
emoticons.forEach((emoticon) => {
|
||||
// Convert emoticon to HTML entity version (for < and >)
|
||||
const htmlEmoticon = emoticon.replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
@@ -130,7 +130,7 @@ export function convertEmoticonsInHtml(html: string): string {
|
||||
// Otherwise convert to emoji
|
||||
return prefix + EMOTICON_MAP[emoticon];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -85,13 +85,13 @@ export function fuzzyMatchAny(
|
||||
texts: Array<string | undefined | null>,
|
||||
): FuzzyMatch | null {
|
||||
let best: FuzzyMatch | null = null;
|
||||
for (const text of texts) {
|
||||
if (!text) continue;
|
||||
texts.forEach((text) => {
|
||||
if (!text) return;
|
||||
const match = fuzzyMatch(query, text);
|
||||
if (match && (!best || match.score > best.score)) {
|
||||
best = match;
|
||||
}
|
||||
}
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
@@ -106,12 +106,12 @@ export function fuzzyFilter<T>(
|
||||
}
|
||||
|
||||
const results: Array<{ item: T; score: number }> = [];
|
||||
for (const item of items) {
|
||||
items.forEach((item) => {
|
||||
const match = fuzzyMatchAny(q, getTexts(item));
|
||||
if (match) {
|
||||
results.push({ item, score: match.score });
|
||||
}
|
||||
}
|
||||
});
|
||||
results.sort((a, b) => b.score - a.score);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -268,6 +268,34 @@ export function needsPngForMetadata(metadata: ImageMetadata): boolean {
|
||||
return Boolean(metadata.banner || metadata.avatarBorderColor || metadata.gradient);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Blob from Uint8Array without relying on BufferSource/BlobPart quirks
|
||||
* across TS DOM lib / Electron versions (avoids SharedArrayBuffer typing issues).
|
||||
*/
|
||||
export function uint8ArrayToBlob(data: Uint8Array, type: string): Blob {
|
||||
const copy = new ArrayBuffer(data.byteLength);
|
||||
new Uint8Array(copy).set(data);
|
||||
return new Blob([copy], { type });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MIME type for an image format
|
||||
*/
|
||||
export function getMimeType(format: ImageFormat): string {
|
||||
switch (format) {
|
||||
case 'png':
|
||||
return 'image/png';
|
||||
case 'webp':
|
||||
return 'image/webp';
|
||||
case 'jpeg':
|
||||
return 'image/jpeg';
|
||||
case 'gif':
|
||||
return 'image/gif';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert image data to PNG via canvas (needed for banner/border/gradient metadata).
|
||||
*/
|
||||
@@ -304,16 +332,6 @@ export async function convertImageDataToPng(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Blob from Uint8Array without relying on BufferSource/BlobPart quirks
|
||||
* across TS DOM lib / Electron versions (avoids SharedArrayBuffer typing issues).
|
||||
*/
|
||||
export function uint8ArrayToBlob(data: Uint8Array, type: string): Blob {
|
||||
const copy = new ArrayBuffer(data.byteLength);
|
||||
new Uint8Array(copy).set(data);
|
||||
return new Blob([copy], { type });
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed paarrot metadata (color and/or banner) into image data
|
||||
* Preserves existing metadata that is not being updated
|
||||
@@ -376,24 +394,6 @@ export function removeColorFromImage(imageData: ArrayBuffer | Uint8Array): Uint8
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MIME type for an image format
|
||||
*/
|
||||
export function getMimeType(format: ImageFormat): string {
|
||||
switch (format) {
|
||||
case 'png':
|
||||
return 'image/png';
|
||||
case 'webp':
|
||||
return 'image/webp';
|
||||
case 'jpeg':
|
||||
return 'image/jpeg';
|
||||
case 'gif':
|
||||
return 'image/gif';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file extension for an image format
|
||||
*/
|
||||
|
||||
@@ -134,11 +134,11 @@ function parseStoredCollectible(value: unknown): StoredCollectible | undefined {
|
||||
if (!sku_id || !name || !assets || typeof assets !== 'object') return undefined;
|
||||
|
||||
const parsedAssets: Record<string, string> = {};
|
||||
for (const [key, mxc] of Object.entries(assets as Record<string, unknown>)) {
|
||||
Object.entries(assets as Record<string, unknown>).forEach(([key, mxc]) => {
|
||||
if (typeof mxc === 'string' && mxc.startsWith('mxc://')) {
|
||||
parsedAssets[key] = mxc;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (Object.keys(parsedAssets).length === 0) return undefined;
|
||||
|
||||
return {
|
||||
|
||||
+32
-32
@@ -152,6 +152,38 @@ export const getPaarrotUiContent = (room: Room | null): PaarrotUiContent | undef
|
||||
|
||||
export const hasRoomAppUi = (room: Room | null): boolean => getPaarrotUiContent(room) !== undefined;
|
||||
|
||||
export function isValidChild(mEvent: MatrixEvent): boolean {
|
||||
if (mEvent.getType() !== StateEvent.SpaceChild) return false;
|
||||
const stateKey = mEvent.getStateKey();
|
||||
if (!stateKey || !stateKey.startsWith('!')) return false;
|
||||
// via is required; omitting it (e.g. empty {}) removes the child per Matrix spec
|
||||
return Array.isArray(mEvent.getContent<{ via?: string[] }>().via);
|
||||
}
|
||||
|
||||
export const getAllParents = (roomToParents: RoomToParents, roomId: string): Set<string> => {
|
||||
const allParents = new Set<string>();
|
||||
|
||||
const addAllParentIds = (rId: string) => {
|
||||
if (allParents.has(rId)) return;
|
||||
allParents.add(rId);
|
||||
|
||||
const parents = roomToParents.get(rId);
|
||||
parents?.forEach((id) => addAllParentIds(id));
|
||||
};
|
||||
addAllParentIds(roomId);
|
||||
allParents.delete(roomId);
|
||||
return allParents;
|
||||
};
|
||||
|
||||
export const getSpaceChildren = (room: Room) =>
|
||||
getStateEvents(room, StateEvent.SpaceChild).reduce<string[]>((filtered, mEvent) => {
|
||||
const stateKey = mEvent.getStateKey();
|
||||
if (isValidChild(mEvent) && stateKey) {
|
||||
filtered.push(stateKey);
|
||||
}
|
||||
return filtered;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* m.forum space root (forum board lobby), not a plain m.space or a lone m.forum topic channel.
|
||||
* Matrix sets create type m.forum on forum spaces but SDK isSpaceRoom() is often still false;
|
||||
@@ -201,38 +233,6 @@ export const isUnsupportedRoom = (room: Room | null): boolean => {
|
||||
return roomType !== RoomType.Space && roomType !== RoomType.Forum;
|
||||
};
|
||||
|
||||
export function isValidChild(mEvent: MatrixEvent): boolean {
|
||||
if (mEvent.getType() !== StateEvent.SpaceChild) return false;
|
||||
const stateKey = mEvent.getStateKey();
|
||||
if (!stateKey || !stateKey.startsWith('!')) return false;
|
||||
// via is required; omitting it (e.g. empty {}) removes the child per Matrix spec
|
||||
return Array.isArray(mEvent.getContent<{ via?: string[] }>().via);
|
||||
}
|
||||
|
||||
export const getAllParents = (roomToParents: RoomToParents, roomId: string): Set<string> => {
|
||||
const allParents = new Set<string>();
|
||||
|
||||
const addAllParentIds = (rId: string) => {
|
||||
if (allParents.has(rId)) return;
|
||||
allParents.add(rId);
|
||||
|
||||
const parents = roomToParents.get(rId);
|
||||
parents?.forEach((id) => addAllParentIds(id));
|
||||
};
|
||||
addAllParentIds(roomId);
|
||||
allParents.delete(roomId);
|
||||
return allParents;
|
||||
};
|
||||
|
||||
export const getSpaceChildren = (room: Room) =>
|
||||
getStateEvents(room, StateEvent.SpaceChild).reduce<string[]>((filtered, mEvent) => {
|
||||
const stateKey = mEvent.getStateKey();
|
||||
if (isValidChild(mEvent) && stateKey) {
|
||||
filtered.push(stateKey);
|
||||
}
|
||||
return filtered;
|
||||
}, []);
|
||||
|
||||
export const mapParentWithChildren = (
|
||||
roomToParents: RoomToParents,
|
||||
roomId: string,
|
||||
|
||||
+18
-18
@@ -1,3 +1,21 @@
|
||||
/**
|
||||
* Check if we're running inside Electron (not Tauri)
|
||||
*/
|
||||
export const isElectron = (): boolean => typeof window !== 'undefined' && 'electron' in window;
|
||||
|
||||
/**
|
||||
* Check if we're running inside a Capacitor native app
|
||||
*/
|
||||
export const isCapacitorNative = (): boolean => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
const cap = (window as any).Capacitor;
|
||||
return Boolean(
|
||||
cap?.isNativePlatform?.() ||
|
||||
cap?.getPlatform?.() === 'android' ||
|
||||
cap?.getPlatform?.() === 'ios',
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Open an external URL using Electron's shell.openExternal, or window.open in browser
|
||||
* @param url The URL to open
|
||||
@@ -174,24 +192,6 @@ export const setupNotificationTapListener = async (
|
||||
*/
|
||||
export const isTauri = (): boolean => '__TAURI__' in window || '__TAURI_INTERNALS__' in window;
|
||||
|
||||
/**
|
||||
* Check if we're running inside Electron (not Tauri)
|
||||
*/
|
||||
export const isElectron = (): boolean => typeof window !== 'undefined' && 'electron' in window;
|
||||
|
||||
/**
|
||||
* Check if we're running inside a Capacitor native app
|
||||
*/
|
||||
export const isCapacitorNative = (): boolean => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
const cap = (window as any).Capacitor;
|
||||
return Boolean(
|
||||
cap?.isNativePlatform?.() ||
|
||||
cap?.getPlatform?.() === 'android' ||
|
||||
cap?.getPlatform?.() === 'ios',
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if we're running on a mobile platform (Android/iOS)
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user