Fix the mechanical style rules. [skip build]
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user