From 664b7eb739c8b2aa184fb7ba2d087d5bfed35a18 Mon Sep 17 00:00:00 2001 From: litruv Date: Sun, 1 Nov 2026 21:05:47 +1100 Subject: [PATCH] Rewrite the restricted iterators and reorder the forward references. [skip build] --- src/app/components/title-bar/TitleBar.tsx | 3 +- src/app/features/call/useCall.ts | 3 +- src/app/features/call/useRtcConfig.ts | 3 +- src/app/features/forum/ForumNewPostModal.tsx | 6 +- src/app/features/forum/forumFeed.ts | 139 +++++----- src/app/features/forum/forumTopicHelpers.ts | 3 +- src/app/features/forum/topicSearch.ts | 4 +- src/app/features/forum/useForumBoard.ts | 3 +- .../room/emoji-confetti/burstOrigin.ts | 5 +- .../room/emoji-confetti/sendEmojiConfetti.ts | 8 +- src/app/features/settings/account/Profile.tsx | 16 +- .../notifications/SystemNotification.tsx | 150 +++++------ .../settings/plugins/PluginLoader.tsx | 203 +++++++------- src/app/features/settings/plugins/Plugins.tsx | 74 +++--- .../permissions/Permissions.tsx | 6 +- src/app/hooks/useRoomMediaEvents.ts | 4 +- src/app/hooks/useSpaceHierarchy.ts | 4 +- src/app/hooks/useUserCollectibles.ts | 7 +- src/app/paarrot-api.ts | 247 +++++++++--------- src/app/pages/client/ClientNonUIFeatures.tsx | 3 +- src/app/utils/collectibleAssets.ts | 3 +- src/app/utils/discordCollectibles.ts | 3 +- src/app/utils/emoticonConverter.ts | 3 +- src/app/utils/room.ts | 3 +- src/client/initMatrix.ts | 6 +- 25 files changed, 472 insertions(+), 437 deletions(-) diff --git a/src/app/components/title-bar/TitleBar.tsx b/src/app/components/title-bar/TitleBar.tsx index 6f27b863..851de6e4 100644 --- a/src/app/components/title-bar/TitleBar.tsx +++ b/src/app/components/title-bar/TitleBar.tsx @@ -205,7 +205,8 @@ export function TitleBar({ mx, children }: TitleBarProps) { } // Check if body contains any of the user's keywords - for (const keyword of notificationData.keywordPatterns) { + for (let i = 0; i < notificationData.keywordPatterns.length; i += 1) { + const keyword = notificationData.keywordPatterns[i]; if (body.includes(keyword.toLowerCase())) { return true; } diff --git a/src/app/features/call/useCall.ts b/src/app/features/call/useCall.ts index 18d003f3..b7190cec 100644 --- a/src/app/features/call/useCall.ts +++ b/src/app/features/call/useCall.ts @@ -276,7 +276,8 @@ export function useRoomCall(roomId: string) { ); // Check each homeserver in priority order - for (const homeserver of homeserverPriority) { + for (let i = 0; i < homeserverPriority.length; i += 1) { + const homeserver = homeserverPriority[i]; try { console.log(`Fetching well-known from ${homeserver}...`); const wellKnown = await fetchWellKnownWithRTC(homeserver); diff --git a/src/app/features/call/useRtcConfig.ts b/src/app/features/call/useRtcConfig.ts index 7782d87b..9c3b1f26 100644 --- a/src/app/features/call/useRtcConfig.ts +++ b/src/app/features/call/useRtcConfig.ts @@ -283,7 +283,8 @@ export async function fetchLiveKitJWTFromServers( deviceId: string, accessToken: string, ): Promise<{ jwt: LiveKitJWTResponse; homeserver: string } | null> { - for (const homeserver of homeservers) { + for (let i = 0; i < homeservers.length; i += 1) { + const homeserver = homeservers[i]; try { console.log(`Trying LiveKit JWT from homeserver: ${homeserver}`); diff --git a/src/app/features/forum/ForumNewPostModal.tsx b/src/app/features/forum/ForumNewPostModal.tsx index 7a1f0df9..0d4ef097 100644 --- a/src/app/features/forum/ForumNewPostModal.tsx +++ b/src/app/features/forum/ForumNewPostModal.tsx @@ -149,13 +149,15 @@ export function ForumNewPostModal({ eventId = await sendForumMediaRoot(mx, topicRoomId, trimmedTitle, first); publishedPlainText = typeof first.body === 'string' ? first.body : trimmedTitle; publishedHtml = ''; - for (const content of rest) { + for (let i = 0; i < rest.length; i += 1) { + const content = rest[i]; await sendForumThreadAttachment(mx, topicRoomId, eventId, content); } } if (hasText) { - for (const content of attachmentContents) { + for (let i = 0; i < attachmentContents.length; i += 1) { + const content = attachmentContents[i]; await sendForumThreadAttachment(mx, topicRoomId, eventId, content); } } diff --git a/src/app/features/forum/forumFeed.ts b/src/app/features/forum/forumFeed.ts index c9edcfc9..2cbde1aa 100644 --- a/src/app/features/forum/forumFeed.ts +++ b/src/app/features/forum/forumFeed.ts @@ -357,6 +357,74 @@ export async function listForumTopics( return topics.sort((a, b) => a.name.localeCompare(b.name)); } +function isSecondaryMatrixEvent(mEvent: MatrixEvent): boolean { + const relation = mEvent.getRelation(); + if ( + relation?.rel_type === RelationType.Replace || + relation?.rel_type === RelationType.Annotation + ) { + return true; + } + return isAnnotationRoomMessage(mEvent.getContent()); +} + +function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent { + return mEvent.event as IRoomEvent; +} + +function collectLocalReplaceEdits(room: Room, targetIds: Set): IRoomEvent[] { + const events: IRoomEvent[] = []; + const seen = new Set(); + + 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; +} + +function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] { + const room = mx.getRoom(roomId); + if (!room) return []; + + const seen = new Set(); + const events: IRoomEvent[] = []; + + 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)); + + return events; +} + export async function listTopicFeedPosts( mx: MatrixClient, roomId: string, @@ -402,17 +470,6 @@ function mergeUniqueRoomEvents(...lists: IRoomEvent[][]): IRoomEvent[] { return unique; } -function isSecondaryMatrixEvent(mEvent: MatrixEvent): boolean { - const relation = mEvent.getRelation(); - if ( - relation?.rel_type === RelationType.Replace || - relation?.rel_type === RelationType.Annotation - ) { - return true; - } - return isAnnotationRoomMessage(mEvent.getContent()); -} - function eventBelongsToThread(mEvent: MatrixEvent, rootEventId: string): boolean { if (mEvent.getId() === rootEventId) return true; @@ -432,33 +489,6 @@ function eventBelongsToThread(mEvent: MatrixEvent, rootEventId: string): boolean return false; } -function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent { - return mEvent.event as IRoomEvent; -} - -function collectLocalReplaceEdits(room: Room, targetIds: Set): IRoomEvent[] { - const events: IRoomEvent[] = []; - const seen = new Set(); - - 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, @@ -506,36 +536,6 @@ export function collectLocalThreadEvents( return events; } -function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] { - const room = mx.getRoom(roomId); - if (!room) return []; - - const seen = new Set(); - const events: IRoomEvent[] = []; - - 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)); - - return events; -} - export function loadPostThreadLocal( mx: MatrixClient, roomId: string, @@ -628,7 +628,8 @@ export async function loadAggregatedTopicFeed( scopes: Array<{ roomId: string; sectionTitle?: string; topicName?: string }>, ): Promise { const allPosts: ForumPost[] = []; - for (const scope of scopes) { + for (let i = 0; i < scopes.length; i += 1) { + const scope = scopes[i]; const { posts } = await listTopicFeedPosts(mx, scope.roomId, { minRoots: 5 }); annotatePostsWithRoomScope(posts, scope.roomId, scope); allPosts.push(...posts); diff --git a/src/app/features/forum/forumTopicHelpers.ts b/src/app/features/forum/forumTopicHelpers.ts index e20c86a8..521fd2cb 100644 --- a/src/app/features/forum/forumTopicHelpers.ts +++ b/src/app/features/forum/forumTopicHelpers.ts @@ -114,7 +114,8 @@ export function annotatePostsWithRoomScope( const sectionTitle = scope?.sectionTitle ? String(scope.sectionTitle) : ''; const topicName = scope?.topicName ? String(scope.topicName) : ''; - for (const post of posts) { + for (let i = 0; i < posts.length; i += 1) { + const post = posts[i]; post.topicRoomId = roomId; if (sectionTitle) post.sectionTitle = sectionTitle; if (topicName) post.topicName = topicName; diff --git a/src/app/features/forum/topicSearch.ts b/src/app/features/forum/topicSearch.ts index b731a778..facc52db 100644 --- a/src/app/features/forum/topicSearch.ts +++ b/src/app/features/forum/topicSearch.ts @@ -265,7 +265,9 @@ export function parseTopicSearchQuery(raw: string): ParsedTopicSearch { } let remainder = input; - for (const match of input.matchAll(QUALIFIER_RE)) { + const matches = Array.from(input.matchAll(QUALIFIER_RE)); + for (let i = 0; i < matches.length; i += 1) { + const match = matches[i]; const key = String(match[1] || '').toLowerCase(); const value = String(match[3] || match[4] || '').trim(); if (value) { diff --git a/src/app/features/forum/useForumBoard.ts b/src/app/features/forum/useForumBoard.ts index 58c4e7a7..b3c6ff4a 100644 --- a/src/app/features/forum/useForumBoard.ts +++ b/src/app/features/forum/useForumBoard.ts @@ -38,7 +38,8 @@ function scopesFromSelection( topic?: string, ): Array<{ roomId: string; sectionTitle?: string; topicName?: string }> { if (topic) { - for (const section of sections) { + for (let i = 0; i < sections.length; i += 1) { + const section = sections[i]; const match = section.topics.find((t) => t.roomId === topic); if (match) { return [{ roomId: match.roomId, sectionTitle: section.title, topicName: match.name }]; diff --git a/src/app/features/room/emoji-confetti/burstOrigin.ts b/src/app/features/room/emoji-confetti/burstOrigin.ts index b5273e88..2d551615 100644 --- a/src/app/features/room/emoji-confetti/burstOrigin.ts +++ b/src/app/features/room/emoji-confetti/burstOrigin.ts @@ -24,8 +24,9 @@ export function findEmojiOriginInMessage( const message = document.querySelector(`[data-message-id="${CSS.escape(targetEventId)}"]`); if (!message) return undefined; - const matches = message.querySelectorAll('[data-emoticon]'); - for (const element of matches) { + const matches = Array.from(message.querySelectorAll('[data-emoticon]')); + for (let i = 0; i < matches.length; i += 1) { + const element = matches[i]; if (element.getAttribute('data-emoticon') === emoji) { return getBurstPointFromElement(element); } diff --git a/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts b/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts index 5341d6c5..94580518 100644 --- a/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts +++ b/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts @@ -12,12 +12,16 @@ export function extractJumboEmojis(body: string): string[] { const found: string[] = []; - for (const match of trimmedBody.matchAll(EMOJI_REG_G)) { + const emojiMatches = Array.from(trimmedBody.matchAll(EMOJI_REG_G)); + for (let i = 0; i < emojiMatches.length; i += 1) { + const match = emojiMatches[i]; const emoji = match[1]; if (emoji) found.push(emoji); } - for (const match of trimmedBody.matchAll(SHORTCODE_PATTERN)) { + const shortcodeMatches = Array.from(trimmedBody.matchAll(SHORTCODE_PATTERN)); + for (let i = 0; i < shortcodeMatches.length; i += 1) { + const match = shortcodeMatches[i]; const shortcode = match[1]; const resolved = emojis.find((emoji) => emoji.shortcode === shortcode); if (resolved) found.push(resolved.unicode); diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 16f1d4db..f7307f00 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -196,6 +196,14 @@ function ProfileBanner({ } }, [presence?.status, isEditingStatus]); + // Avatar-specific upload + const [avatarFile, setAvatarFile] = useState(); + const avatarUploadAtom = useMemo(() => { + if (avatarFile) return createUploadAtom(avatarFile); + return undefined; + }, [avatarFile]); + const pickAvatarFile = useFilePicker(setAvatarFile, false); + const handleAvatarClick = () => { pickAvatarFile('image/*'); }; @@ -336,14 +344,6 @@ function ProfileBanner({ const pickFile = useFilePicker(setImageFile, false); - // Avatar-specific upload - const [avatarFile, setAvatarFile] = useState(); - const avatarUploadAtom = useMemo(() => { - if (avatarFile) return createUploadAtom(avatarFile); - return undefined; - }, [avatarFile]); - const pickAvatarFile = useFilePicker(setAvatarFile, false); - // Warn before leaving when an upload or save is in progress useEffect(() => { if (!imageFile && !avatarFile && !saving) return undefined; diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 84dc4559..85709702 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -91,81 +91,6 @@ function EmailNotification() { ); } -export function SystemNotification() { - const notifPermission = usePermissionState('notifications', getNotificationState()); - const capacitorNative = isCapacitorNative(); - const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications'); - const [isNotificationSounds, setIsNotificationSounds] = useSetting( - settingsAtom, - 'isNotificationSounds', - ); - - const requestNotificationPermission = async () => { - await requestSystemNotificationPermission(); - }; - - return ( - - System - - - {'Notification' in window - ? 'Notification permission is blocked. Please allow notification permission from browser address bar.' - : 'Notifications are not supported by the system.'} - - ) : ( - Show desktop notifications when message arrive. - ) - } - after={ - notifPermission === 'prompt' ? ( - - ) : ( - - ) - } - /> - - - } - /> - - {isBackgroundSyncSupported() && } - - - - - ); -} - type PushStatus = { registered: boolean; distributor: string; @@ -352,3 +277,78 @@ function AndroidPushNotifications() { ); } + +export function SystemNotification() { + const notifPermission = usePermissionState('notifications', getNotificationState()); + const capacitorNative = isCapacitorNative(); + const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications'); + const [isNotificationSounds, setIsNotificationSounds] = useSetting( + settingsAtom, + 'isNotificationSounds', + ); + + const requestNotificationPermission = async () => { + await requestSystemNotificationPermission(); + }; + + return ( + + System + + + {'Notification' in window + ? 'Notification permission is blocked. Please allow notification permission from browser address bar.' + : 'Notifications are not supported by the system.'} + + ) : ( + Show desktop notifications when message arrive. + ) + } + after={ + notifPermission === 'prompt' ? ( + + ) : ( + + ) + } + /> + + + } + /> + + {isBackgroundSyncSupported() && } + + + + + ); +} diff --git a/src/app/features/settings/plugins/PluginLoader.tsx b/src/app/features/settings/plugins/PluginLoader.tsx index f991b767..6bf61ac9 100644 --- a/src/app/features/settings/plugins/PluginLoader.tsx +++ b/src/app/features/settings/plugins/PluginLoader.tsx @@ -11,107 +11,6 @@ interface PluginLoaderProps { children: React.ReactNode; } -/** - * Component that loads and initializes enabled plugins. - * Should be placed high in the component tree after MatrixClient is available. - */ -export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { - console.log('[PluginLoader] Component rendering, matrixClient:', !!matrixClient); - - useEffect(() => { - const loadPlugins = async () => { - try { - console.log('[PluginLoader] Loading plugins...'); - console.log('[PluginLoader] window.electron:', !!window.electron); - console.log('[PluginLoader] window.electron.plugins:', !!window.electron?.plugins); - - if (!window.electron?.plugins) { - console.log('[PluginLoader] Running in web mode, plugins not supported'); - return; - } - - const pluginsToLoad = await pluginMarketplaceManager.listEnabledPlugins(); - - console.log('[PluginLoader] Plugins to load:', pluginsToLoad.length); - console.log( - '[PluginLoader] Plugin list:', - pluginsToLoad.map((p) => p.id), - ); - - for (const installedPlugin of pluginsToLoad) { - try { - console.log(`[PluginLoader] Loading plugin: ${installedPlugin.id}`); - - const pluginModule = await loadPluginModule(installedPlugin.id); - const plugin = normalisePlugin(pluginModule); - - if (!plugin || typeof plugin !== 'object') { - console.error( - `[PluginLoader] Plugin ${installedPlugin.id} does not export a valid plugin object`, - ); - } else if (typeof plugin.onLoad !== 'function') { - console.error( - `[PluginLoader] Plugin ${installedPlugin.id} does not have an onLoad function`, - ); - } 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, - ); - - const compatContext = Object.assign(context as Record, { - 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...'); - - 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]); - } - } - } catch (error) { - console.error('[PluginLoader] Error loading plugins:', error); - } - }; - - loadPlugins(); - - return () => { - console.log('[PluginLoader] Cleaning up plugins'); - pluginRegistry.clear(); - dispatchPluginButtonsChanged(); - }; - }, [matrixClient]); - - return children; -} - /** * Reads and evaluates a plugin's JS module from the Electron filesystem. * Supports both CommonJS and ESM-style exports. @@ -187,3 +86,105 @@ function normalisePlugin(raw: Record): Plugin { return raw as unknown as Plugin; } + +/** + * Component that loads and initializes enabled plugins. + * Should be placed high in the component tree after MatrixClient is available. + */ +export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { + console.log('[PluginLoader] Component rendering, matrixClient:', !!matrixClient); + + useEffect(() => { + const loadPlugins = async () => { + try { + console.log('[PluginLoader] Loading plugins...'); + console.log('[PluginLoader] window.electron:', !!window.electron); + console.log('[PluginLoader] window.electron.plugins:', !!window.electron?.plugins); + + if (!window.electron?.plugins) { + console.log('[PluginLoader] Running in web mode, plugins not supported'); + return; + } + + const pluginsToLoad = await pluginMarketplaceManager.listEnabledPlugins(); + + console.log('[PluginLoader] Plugins to load:', pluginsToLoad.length); + console.log( + '[PluginLoader] Plugin list:', + pluginsToLoad.map((p) => p.id), + ); + + for (let i = 0; i < pluginsToLoad.length; i += 1) { + const installedPlugin = pluginsToLoad[i]; + try { + console.log(`[PluginLoader] Loading plugin: ${installedPlugin.id}`); + + const pluginModule = await loadPluginModule(installedPlugin.id); + const plugin = normalisePlugin(pluginModule); + + if (!plugin || typeof plugin !== 'object') { + console.error( + `[PluginLoader] Plugin ${installedPlugin.id} does not export a valid plugin object`, + ); + } else if (typeof plugin.onLoad !== 'function') { + console.error( + `[PluginLoader] Plugin ${installedPlugin.id} does not have an onLoad function`, + ); + } 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, + ); + + const compatContext = Object.assign(context as Record, { + 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...'); + + 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]); + } + } + } catch (error) { + console.error('[PluginLoader] Error loading plugins:', error); + } + }; + + loadPlugins(); + + return () => { + console.log('[PluginLoader] Cleaning up plugins'); + pluginRegistry.clear(); + dispatchPluginButtonsChanged(); + }; + }, [matrixClient]); + + return children; +} diff --git a/src/app/features/settings/plugins/Plugins.tsx b/src/app/features/settings/plugins/Plugins.tsx index 9742c471..19ab75a7 100644 --- a/src/app/features/settings/plugins/Plugins.tsx +++ b/src/app/features/settings/plugins/Plugins.tsx @@ -31,43 +31,6 @@ import { pluginMarketplaceManager, pluginRegistry, SettingDefinition } from './P import { stopPropagation } from '../../../utils/keyboard'; import { fuzzyFilter } from '../../../utils/fuzzy'; -/** - * Renders settings UI for a plugin based on its settings schema - */ -function PluginSettingsRenderer({ pluginId }: { pluginId: string }) { - const schema = pluginRegistry.getPluginSettingsSchema(pluginId); - const [, forceUpdate] = useState({}); - - if (!schema || Object.keys(schema).length === 0) { - return ( - - - No settings available for this plugin. - - - ); - } - - const handleChange = (key: string, value: any) => { - pluginRegistry.setPluginSetting(pluginId, key, value); - forceUpdate({}); - }; - - return ( - - {Object.entries(schema).map(([key, def]) => ( - handleChange(key, value)} - /> - ))} - - ); -} - /** * Renders a single setting based on its type */ @@ -242,6 +205,43 @@ function SettingRenderer({ return null; } +/** + * Renders settings UI for a plugin based on its settings schema + */ +function PluginSettingsRenderer({ pluginId }: { pluginId: string }) { + const schema = pluginRegistry.getPluginSettingsSchema(pluginId); + const [, forceUpdate] = useState({}); + + if (!schema || Object.keys(schema).length === 0) { + return ( + + + No settings available for this plugin. + + + ); + } + + const handleChange = (key: string, value: any) => { + pluginRegistry.setPluginSetting(pluginId, key, value); + forceUpdate({}); + }; + + return ( + + {Object.entries(schema).map(([key, def]) => ( + handleChange(key, value)} + /> + ))} + + ); +} + function PluginAvatar({ thumbnail, name }: { thumbnail: string; name: string }) { const [imageError, setImageError] = useState(false); diff --git a/src/app/features/space-settings/permissions/Permissions.tsx b/src/app/features/space-settings/permissions/Permissions.tsx index 7d14ecb5..089060ef 100644 --- a/src/app/features/space-settings/permissions/Permissions.tsx +++ b/src/app/features/space-settings/permissions/Permissions.tsx @@ -112,7 +112,8 @@ export function Permissions({ requestClose }: PermissionsProps) { const total = syncableChildren.length; const myUserId = mx.getSafeUserId(); - for (const childId of syncableChildren) { + for (let i = 0; i < syncableChildren.length; i += 1) { + const childId = syncableChildren[i]; try { const childRoom = mx.getRoom(childId); if (childRoom) { @@ -220,7 +221,8 @@ export function Permissions({ requestClose }: PermissionsProps) { const total = syncableChildren.length; const myUserId = mx.getSafeUserId(); - for (const childId of syncableChildren) { + for (let i = 0; i < syncableChildren.length; i += 1) { + const childId = syncableChildren[i]; try { const childRoom = mx.getRoom(childId); if (childRoom) { diff --git a/src/app/hooks/useRoomMediaEvents.ts b/src/app/hooks/useRoomMediaEvents.ts index 217e462f..48caccab 100644 --- a/src/app/hooks/useRoomMediaEvents.ts +++ b/src/app/hooks/useRoomMediaEvents.ts @@ -147,7 +147,9 @@ export const useRoomMediaEvents = (room: Room) => { setHasMore(false); } - for (const raw of response.chunk ?? []) { + const chunk = response.chunk ?? []; + for (let i = 0; i < chunk.length; i += 1) { + const raw = chunk[i]; const mEvent = await decryptEvent(raw); const item = toMediaItem(mEvent); if (item && !cache.seenIds.has(item.eventId)) { diff --git a/src/app/hooks/useSpaceHierarchy.ts b/src/app/hooks/useSpaceHierarchy.ts index 9962c78a..8a2f18a3 100644 --- a/src/app/hooks/useSpaceHierarchy.ts +++ b/src/app/hooks/useSpaceHierarchy.ts @@ -41,7 +41,9 @@ const MAX_AUTO_PAGE_COUNT = 50; export function buildParentByRoomId(rooms: Iterable): Map { const parentByRoomId = new Map(); - for (const room of rooms) { + const roomList = Array.from(rooms); + for (let i = 0; i < roomList.length; i += 1) { + const room = roomList[i]; if (room?.room_id && Array.isArray(room.children_state)) { room.children_state.forEach((childState) => { if (childState?.type !== StateEvent.SpaceChild) return; diff --git a/src/app/hooks/useUserCollectibles.ts b/src/app/hooks/useUserCollectibles.ts index a4c98e53..97426f26 100644 --- a/src/app/hooks/useUserCollectibles.ts +++ b/src/app/hooks/useUserCollectibles.ts @@ -109,9 +109,12 @@ export function useOtherUserCollectibles(userId: string): CollectibleProfileFiel ['avatar_decoration', data.avatar_decoration], ] as const; - for (const [kind, collectible] of entries) { + for (let i = 0; i < entries.length; i += 1) { + const [kind, collectible] = entries[i]; if (collectible) { - for (const [role, mxc] of Object.entries(collectible.assets)) { + const assetEntries = Object.entries(collectible.assets); + for (let j = 0; j < assetEntries.length; j += 1) { + const [role, mxc] = assetEntries[j]; const blobUrl = await getProfileAssetUrl(mx, mxc, useAuthentication); if (blobUrl) urls[`${kind}:${role}`] = blobUrl; } diff --git a/src/app/paarrot-api.ts b/src/app/paarrot-api.ts index d1fbc8bd..d342bf3d 100644 --- a/src/app/paarrot-api.ts +++ b/src/app/paarrot-api.ts @@ -55,125 +55,6 @@ export function setPaarrotNavigate(navigate: (path: string) => void) { console.log('Paarrot API: Navigate function registered'); } -/** - * Initialize the Paarrot API handler - * This should be called once during app startup - */ -export function initPaarrotAPI(matrixClient: MatrixClient) { - // Check if we're running in Electron - if (!(window as any).electron?.api?.onAction) { - console.log('Paarrot API: Not running in Electron, skipping API initialization'); - return; - } - - // Prevent duplicate registrations - if (isInitialized) { - console.log('Paarrot API: Already initialized, skipping'); - return; - } - isInitialized = true; - - console.log('Paarrot API: Initializing API handler'); - - // Listen for API actions from the Electron API server - (window as any).electron.api.onAction( - async (action: { action: string; params: any; responseChannel: string }) => { - console.log('Paarrot API: Received action:', action.action, action.params); - - try { - let result; - - switch (action.action) { - case 'get-status': - result = await getStatus(matrixClient); - break; - - case 'toggle-mute': - result = await toggleMute(matrixClient); - break; - - case 'set-mute': - result = await setMute(matrixClient, action.params.muted); - break; - - case 'toggle-deafen': - result = await toggleDeafen(matrixClient); - break; - - case 'set-deafen': - result = await setDeafen(matrixClient, action.params.deafened); - break; - - case 'change-channel': - result = await changeChannel(matrixClient, action.params.roomId); - break; - - case 'get-channels': - result = await getChannels(matrixClient); - break; - - case 'send-message': - result = await sendMessage(matrixClient, action.params.roomId, action.params.message); - break; - - case 'send-message-current': - result = await sendMessageCurrent(matrixClient, action.params.message); - break; - - case 'get-current-room': - result = await getCurrentRoom(matrixClient); - break; - - case 'get-messages-groups': - result = await getMessagesByScope(matrixClient, 'groups', action.params.limit); - break; - - case 'get-messages-dms': - result = await getMessagesByScope(matrixClient, 'dms', action.params.limit); - break; - - case 'get-messages-combined': - result = await getMessagesByScope(matrixClient, 'combined', action.params.limit); - break; - - case 'get-unreads-groups': - result = await getUnreadsByScope(matrixClient, 'groups'); - break; - - case 'get-unreads-dms': - result = await getUnreadsByScope(matrixClient, 'dms'); - break; - - case 'get-unreads-combined': - result = await getUnreadsByScope(matrixClient, 'combined'); - break; - - default: - throw new Error(`Unknown action: ${action.action}`); - } - - // Send success response back - (window as any).electron.api.sendResponse(action.responseChannel, { - success: true, - data: result, - }); - - console.log('Paarrot API: Action completed successfully:', action.action); - } catch (error: any) { - console.error('Paarrot API: Action failed:', action.action, error); - - // Send error response back - (window as any).electron.api.sendResponse(action.responseChannel, { - success: false, - error: error.message || 'Unknown error', - }); - } - }, - ); - - console.log('Paarrot API: Handler initialized'); -} - /** * Get the currently active room ID * Extracts room ID from the current URL pathname @@ -198,7 +79,8 @@ function getCurrentRoomId(): string | null { /^\/[^/]+\/([^/]+)/, // /:spaceIdOrAlias/:roomIdOrAlias (space rooms) ]; - for (const pattern of patterns) { + for (let i = 0; i < patterns.length; i += 1) { + const pattern = patterns[i]; const match = pathname.match(pattern); if (match && match[1]) { // Decode URI component in case the room ID was encoded @@ -591,7 +473,8 @@ async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit? const rooms = getRoomsForScope(matrixClient, scope); const candidates: ApiMessage[] = []; - for (const room of rooms) { + for (let i = 0; i < rooms.length; i += 1) { + const room = rooms[i]; candidates.push(...collectRecentMessages(room, limitNum)); } @@ -629,7 +512,8 @@ async function getUnreadsByScope(matrixClient: any, scope: MessageScope) { }; }> = []; - for (const room of rooms) { + for (let i = 0; i < rooms.length; i += 1) { + const room = rooms[i]; if ( getNotificationType(matrixClient, room.roomId) !== NotificationType.Mute && (roomHaveNotification(room) || roomHaveUnread(matrixClient, room)) @@ -674,4 +558,123 @@ async function getUnreadsByScope(matrixClient: any, scope: MessageScope) { }; } +/** + * Initialize the Paarrot API handler + * This should be called once during app startup + */ +export function initPaarrotAPI(matrixClient: MatrixClient) { + // Check if we're running in Electron + if (!(window as any).electron?.api?.onAction) { + console.log('Paarrot API: Not running in Electron, skipping API initialization'); + return; + } + + // Prevent duplicate registrations + if (isInitialized) { + console.log('Paarrot API: Already initialized, skipping'); + return; + } + isInitialized = true; + + console.log('Paarrot API: Initializing API handler'); + + // Listen for API actions from the Electron API server + (window as any).electron.api.onAction( + async (action: { action: string; params: any; responseChannel: string }) => { + console.log('Paarrot API: Received action:', action.action, action.params); + + try { + let result; + + switch (action.action) { + case 'get-status': + result = await getStatus(matrixClient); + break; + + case 'toggle-mute': + result = await toggleMute(matrixClient); + break; + + case 'set-mute': + result = await setMute(matrixClient, action.params.muted); + break; + + case 'toggle-deafen': + result = await toggleDeafen(matrixClient); + break; + + case 'set-deafen': + result = await setDeafen(matrixClient, action.params.deafened); + break; + + case 'change-channel': + result = await changeChannel(matrixClient, action.params.roomId); + break; + + case 'get-channels': + result = await getChannels(matrixClient); + break; + + case 'send-message': + result = await sendMessage(matrixClient, action.params.roomId, action.params.message); + break; + + case 'send-message-current': + result = await sendMessageCurrent(matrixClient, action.params.message); + break; + + case 'get-current-room': + result = await getCurrentRoom(matrixClient); + break; + + case 'get-messages-groups': + result = await getMessagesByScope(matrixClient, 'groups', action.params.limit); + break; + + case 'get-messages-dms': + result = await getMessagesByScope(matrixClient, 'dms', action.params.limit); + break; + + case 'get-messages-combined': + result = await getMessagesByScope(matrixClient, 'combined', action.params.limit); + break; + + case 'get-unreads-groups': + result = await getUnreadsByScope(matrixClient, 'groups'); + break; + + case 'get-unreads-dms': + result = await getUnreadsByScope(matrixClient, 'dms'); + break; + + case 'get-unreads-combined': + result = await getUnreadsByScope(matrixClient, 'combined'); + break; + + default: + throw new Error(`Unknown action: ${action.action}`); + } + + // Send success response back + (window as any).electron.api.sendResponse(action.responseChannel, { + success: true, + data: result, + }); + + console.log('Paarrot API: Action completed successfully:', action.action); + } catch (error: any) { + console.error('Paarrot API: Action failed:', action.action, error); + + // Send error response back + (window as any).electron.api.sendResponse(action.responseChannel, { + success: false, + error: error.message || 'Unknown error', + }); + } + }, + ); + + console.log('Paarrot API: Handler initialized'); +} + export default { initPaarrotAPI }; diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 99776117..ca73f49c 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -553,7 +553,8 @@ function AndroidShareIntentHandler() { // Upload and send files if present if (share.files.length > 0) { - for (const sharedFile of share.files) { + for (let i = 0; i < share.files.length; i += 1) { + const sharedFile = share.files[i]; const originalFile = await materializeSharedFile(sharedFile, share.receivedAt); let fileToUpload = originalFile; diff --git a/src/app/utils/collectibleAssets.ts b/src/app/utils/collectibleAssets.ts index 079ee515..8bb58ff9 100644 --- a/src/app/utils/collectibleAssets.ts +++ b/src/app/utils/collectibleAssets.ts @@ -10,7 +10,8 @@ function introDurationFromEffectMeta( } function catalogAssetUrl(item: DiscordCollectibleItem, ...roles: string[]): string | undefined { - for (const role of roles) { + for (let i = 0; i < roles.length; i += 1) { + const role = roles[i]; const asset = item.assets.find((entry) => entry.role === role); if (asset?.url) return asset.url; } diff --git a/src/app/utils/discordCollectibles.ts b/src/app/utils/discordCollectibles.ts index 1cb2f9dc..35d49808 100644 --- a/src/app/utils/discordCollectibles.ts +++ b/src/app/utils/discordCollectibles.ts @@ -192,7 +192,8 @@ export async function uploadCollectibleToMatrix( const urlToMxc = new Map(); const assets: Record = {}; - for (const asset of downloaded) { + for (let i = 0; i < downloaded.length; i += 1) { + const asset = downloaded[i]; onProgress?.(`Uploading ${asset.filename}…`); const blob = new Blob([asset.data], { type: asset.mimeType }); const file = new File([blob], asset.filename, { type: asset.mimeType }); diff --git a/src/app/utils/emoticonConverter.ts b/src/app/utils/emoticonConverter.ts index 142fb39a..c2475b04 100644 --- a/src/app/utils/emoticonConverter.ts +++ b/src/app/utils/emoticonConverter.ts @@ -143,7 +143,8 @@ export function convertEmoticonsInHtml(html: string): string { export function containsEmoticons(text: string): boolean { const emoticons = Object.keys(EMOTICON_MAP); - for (const emoticon of emoticons) { + for (let i = 0; i < emoticons.length; i += 1) { + const emoticon = emoticons[i]; const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&'); const regex = new RegExp(`(^|\\s)(${escapedEmoticon})(?=\\s|$)`); diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index f9f80389..0b303649 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -209,7 +209,8 @@ export const findForumRootSpace = ( roomToParents: RoomToParents, ): string | undefined => { const ordered = [roomId, ...Array.from(getAllParents(roomToParents, roomId))]; - for (const id of ordered) { + for (let i = 0; i < ordered.length; i += 1) { + const id = ordered[i]; const room = mx.getRoom(id); if (room && shouldShowForumLobby(room)) return id; } diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 0b14a952..bce8d941 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -153,7 +153,8 @@ const deleteRustCryptoDatabase = async (session: Session): Promise => { console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - for (const dbName of cryptoDbNames) { + for (let i = 0; i < cryptoDbNames.length; i += 1) { + const dbName = cryptoDbNames[i]; try { await deleteIndexedDB(dbName); console.log(`[initMatrix] ✅ Deleted: ${dbName}`); @@ -395,7 +396,8 @@ export const fixKeyConflict = async (mx: MatrixClient): Promise => { console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - for (const dbName of cryptoDbNames) { + for (let i = 0; i < cryptoDbNames.length; i += 1) { + const dbName = cryptoDbNames[i]; try { await deleteIndexedDB(dbName); console.log(`[initMatrix] ✅ Deleted: ${dbName}`);