From 726129f9ddd3d7bfcbe82e304ebcfe0de8c8fc8b Mon Sep 17 00:00:00 2001 From: melogale Date: Tue, 10 Mar 2026 02:08:52 -0400 Subject: [PATCH 01/79] sable call and avatar fix --- knip.json | 2 +- package-lock.json | 30 +++++++++++++++--------------- package.json | 2 +- src/app/plugins/call/utils.ts | 2 ++ src/sw.ts | 14 ++++++++++++++ vite.config.ts | 2 +- 6 files changed, 34 insertions(+), 18 deletions(-) diff --git a/knip.json b/knip.json index 8fec7f863..bdecc79c6 100644 --- a/knip.json +++ b/knip.json @@ -5,7 +5,7 @@ "interface": true, "type": true }, - "ignoreDependencies": ["buffer", "@element-hq/element-call-embedded", "workbox-precaching"], + "ignoreDependencies": ["buffer", "@sableclient/sable-call-embedded", "workbox-precaching"], "ignoreBinaries": ["knope"], "rules": { "exports": "off", diff --git a/package-lock.json b/package-lock.json index 5683a6d19..cb788db94 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,12 +71,12 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@element-hq/element-call-embedded": "0.16.3", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", "@rollup/plugin-inject": "^5.0.5", "@rollup/plugin-wasm": "^6.2.2", + "@sableclient/sable-call-embedded": "1.0.2", "@types/chroma-js": "^3.1.2", "@types/file-saver": "^2.0.7", "@types/is-hotkey": "^0.1.10", @@ -1911,12 +1911,6 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/@element-hq/element-call-embedded": { - "version": "0.16.3", - "resolved": "https://registry.npmjs.org/@element-hq/element-call-embedded/-/element-call-embedded-0.16.3.tgz", - "integrity": "sha512-OViKJonDaDNVBUW9WdV9mk78/Ruh34C7XsEgt3O8D9z+64C39elbIgllHSoH5S12IRlv9RYrrV37FZLo6QWsDQ==", - "dev": true - }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -6270,6 +6264,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@sableclient/sable-call-embedded": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@sableclient/sable-call-embedded/-/sable-call-embedded-1.0.2.tgz", + "integrity": "sha512-pvf2BxMx/57EnOs7NWf1/2UtchiBoMGdkzDH4Ivl0D0HSXIMO5z9DuHizk2bnHDJxcSSLY0wEl0XMl7ro0zqDA==", + "dev": true + }, "node_modules/@sindresorhus/is": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", @@ -17883,12 +17883,6 @@ } } }, - "@element-hq/element-call-embedded": { - "version": "0.16.3", - "resolved": "https://registry.npmjs.org/@element-hq/element-call-embedded/-/element-call-embedded-0.16.3.tgz", - "integrity": "sha512-OViKJonDaDNVBUW9WdV9mk78/Ruh34C7XsEgt3O8D9z+64C39elbIgllHSoH5S12IRlv9RYrrV37FZLo6QWsDQ==", - "dev": true - }, "@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -20486,6 +20480,12 @@ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", "dev": true }, + "@sableclient/sable-call-embedded": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@sableclient/sable-call-embedded/-/sable-call-embedded-1.0.2.tgz", + "integrity": "sha512-pvf2BxMx/57EnOs7NWf1/2UtchiBoMGdkzDH4Ivl0D0HSXIMO5z9DuHizk2bnHDJxcSSLY0wEl0XMl7ro0zqDA==", + "dev": true + }, "@sindresorhus/is": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", @@ -24408,7 +24408,7 @@ "jwt-decode": "^4.0.0", "loglevel": "^1.9.2", "matrix-events-sdk": "0.0.1", - "matrix-widget-api": "^1.10.0", + "matrix-widget-api": "1.13.0", "oidc-client-ts": "^3.0.1", "p-retry": "7", "sdp-transform": "^2.14.1", @@ -26905,4 +26905,4 @@ "dev": true } } -} \ No newline at end of file +} diff --git a/package.json b/package.json index 2667d1481..7850f3de7 100644 --- a/package.json +++ b/package.json @@ -87,7 +87,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@element-hq/element-call-embedded": "0.16.3", + "@sableclient/sable-call-embedded": "1.0.2", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", diff --git a/src/app/plugins/call/utils.ts b/src/app/plugins/call/utils.ts index 0ea72b3c8..8c4955b4e 100644 --- a/src/app/plugins/call/utils.ts +++ b/src/app/plugins/call/utils.ts @@ -18,6 +18,8 @@ export function getCallCapabilities( capabilities.add(MatrixCapabilities.MSC3846TurnServers); capabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent); capabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent); + capabilities.add('moe.sable.thumbnails'); + capabilities.add('moe.sable.media_proxy'); capabilities.add(`org.matrix.msc2762.timeline:${roomId}`); capabilities.add(`org.matrix.msc2762.state:${roomId}`); diff --git a/src/sw.ts b/src/sw.ts index a7fd738ec..4d7e0a037 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -269,6 +269,20 @@ self.addEventListener('fetch', (event: FetchEvent) => { return; } + // Since widgets like element call have their own client ids, + // we need this logic. We just go through the sessions list and get a session + // with the right base url. Media requests to a homeserver simply are fine with any account + // on the homeserver authenticating it, so this is fine. But it can be technically wrong. + // If you have two tabs for different users on the same homeserver, it might authenticate + // as the wrong one. + // Thus any logic in the future which cares about which user is authenticating the request + // might break this. Also, again, it is technically wrong. + const byBaseUrl = [...sessions.values()].find((s) => validMediaRequest(url, s.baseUrl)); + if (byBaseUrl) { + event.respondWith(fetch(url, { ...fetchConfig(byBaseUrl.accessToken), redirect })); + return; + } + event.respondWith( requestSessionWithTimeout(clientId).then((s) => { if (s && validMediaRequest(url, s.baseUrl)) { diff --git a/vite.config.ts b/vite.config.ts index 907f330d2..c4e5fa3e5 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -62,7 +62,7 @@ const isReleaseTag = (() => { const copyFiles = { targets: [ { - src: 'node_modules/@element-hq/element-call-embedded/dist/*', + src: 'node_modules/@sableclient/sable-call-embedded/dist/*', dest: 'public/element-call', }, { From 882c6d55cc8666e145b268461b52e4a46ad8b181 Mon Sep 17 00:00:00 2001 From: melogale Date: Tue, 10 Mar 2026 02:09:03 -0400 Subject: [PATCH 02/79] gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1c1104414..5cc8aa47a 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ devAssets *.tfbackend !*.tfbackend.example crash.log +build.sh From 1c5314dd5511e31ae216fc082ee5c23ef672c391 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 16:37:02 +0100 Subject: [PATCH 03/79] fix maintainability issues raised by sonarqube fixed sonarqube issues: - React props should be read-only (typescript:S6759) - Spacing between inline elements should be explicit (typescript:S6772) --- src/app/features/settings/experimental/Experimental.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index d8375271c..5f29102e4 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -7,7 +7,7 @@ import { Sync } from '../general'; type ExperimentalProps = { requestClose: () => void; }; -export function Experimental({ requestClose }: ExperimentalProps) { +export function Experimental({ requestClose }: Readonly) { return ( @@ -32,8 +32,8 @@ export function Experimental({ requestClose }: ExperimentalProps) { variant="Warning" description={ <> - The features listed below may be unstable or incomplete, - use at your own risk. + The features listed below may be unstable or incomplete,{' '} + use at your own risk.
Please report any new issues potentially caused by these features! From 7c4decd4e90d6997a48ff939d8daa8437f96b331 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 16:41:44 +0100 Subject: [PATCH 04/79] fix reliability/maintainability issues raised by sonarqube fixed issues: - typescript:S7781 - typescript:S6759 --- src/app/components/DeviceVerificationSetup.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/components/DeviceVerificationSetup.tsx b/src/app/components/DeviceVerificationSetup.tsx index 83c7187c1..78fe8ded2 100644 --- a/src/app/components/DeviceVerificationSetup.tsx +++ b/src/app/components/DeviceVerificationSetup.tsx @@ -70,7 +70,7 @@ function makeUIAAction( type SetupVerificationProps = { onComplete: (recoveryKey: string) => void; }; -function SetupVerification({ onComplete }: SetupVerificationProps) { +function SetupVerification({ onComplete }: Readonly) { const mx = useMatrixClient(); const alive = useAlive(); @@ -227,7 +227,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { type RecoveryKeyDisplayProps = { recoveryKey: string; }; -function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) { +function RecoveryKeyDisplay({ recoveryKey }: Readonly) { const [show, setShow] = useState(false); const handleCopy = () => { @@ -241,7 +241,7 @@ function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) { FileSaver.saveAs(blob, 'recovery-key.txt'); }; - const safeToDisplayKey = show ? recoveryKey : recoveryKey.replace(/[^\s]/g, '*'); + const safeToDisplayKey = show ? recoveryKey : recoveryKey.replaceAll(/[^\s]/g, '*'); return ( From b5b1766bd6ce518946a2d373d5fd072f3c0d8143 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:12:15 +0100 Subject: [PATCH 05/79] fix sonarqube maintainability/reliability issues - typescript:S7773 - typescript:S4158 --- src/app/components/Pdf-viewer/PdfViewer.tsx | 2 +- .../editor/autocomplete/EmoticonAutocomplete.tsx | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index e3072e6ff..71ab77efb 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -85,7 +85,7 @@ export const PdfViewer = as<'div', PdfViewerProps>( if (docState.status !== AsyncStatus.Success) return; const jumpInput = evt.currentTarget.jumpInput as HTMLInputElement; if (!jumpInput) return; - const jumpTo = parseInt(jumpInput.value, 10); + const jumpTo = Number.parseInt(jumpInput.value, 10); setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo))); setJumpAnchor(undefined); }; diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index c8466ae98..71dac4900 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -57,13 +57,10 @@ export function EmoticonAutocomplete({ const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold'); - const searchList = useMemo(() => { - const list: Array = []; - return list.concat( - imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), - emojis - ); - }, [imagePacks]); + const searchList = useMemo>( + () => [...imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), ...emojis], + [imagePacks] + ); const [result, search, resetSearch] = useAsyncSearch( searchList, @@ -94,7 +91,7 @@ export function EmoticonAutocomplete({ requestClose(); }); - useKeyDown(window, (evt: KeyboardEvent) => { + useKeyDown(globalThis as Window, (evt: KeyboardEvent) => { onTabPress(evt, () => { if (autoCompleteEmoticon.length === 0) return; const emoticon = autoCompleteEmoticon[0]; From 9363bee20805ad1f6f97b8beacde85d8130e5b4b Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:12:30 +0100 Subject: [PATCH 06/79] replace globalThis with window in useKeyDown for consistency --- src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index 71dac4900..1f590235c 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -91,7 +91,7 @@ export function EmoticonAutocomplete({ requestClose(); }); - useKeyDown(globalThis as Window, (evt: KeyboardEvent) => { + useKeyDown(window, (evt: KeyboardEvent) => { onTabPress(evt, () => { if (autoCompleteEmoticon.length === 0) return; const emoticon = autoCompleteEmoticon[0]; From 7b3ea2b9c003187f4b7e21d22f0972a28c75eb72 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:32:19 +0100 Subject: [PATCH 07/79] fix sonarqube maintainability issues - Number static methods and properties should be preferred over global equivalents (typescript:S7773) - Function references should not be passed directly to iterator methods (typescript:S7727) - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - "RegExp.exec()" should be preferred over "String.match()" (typescript:S6594) - React props should be read-only (typescript:S6759) - Prefer `Math.min()` to simplify ternary expressions (typescript:S7766) - Optional property declarations should not use both '?' and 'undefined' syntax (typescript:S4782) - Built-in constructors should be called consistently with or without "new" (typescript:S7723) --- src/app/components/RenderMessageContent.tsx | 2 +- src/app/components/editor/input.ts | 4 ++-- src/app/components/editor/output.ts | 12 +++++++----- src/app/components/emoji-board/EmojiBoard.tsx | 10 +++++----- .../components/event-history/EventHistory.tsx | 4 ++-- src/app/components/message/RenderBody.tsx | 2 +- src/app/components/message/Reply.tsx | 16 ++++++++-------- src/app/components/time-date/DatePicker.tsx | 8 ++++---- .../upload-card/UploadCardRenderer.tsx | 6 +++--- .../upload-card/UploadDescriptionEditor.tsx | 2 +- .../components/user-profile/UserRoomProfile.tsx | 12 ++++++------ 11 files changed, 40 insertions(+), 38 deletions(-) diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 1a1a5376f..502799249 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -71,7 +71,7 @@ function RenderMessageContentInternal({ htmlReactParserOptions, linkifyOpts, outlineAttachment, -}: RenderMessageContentProps) { +}: Readonly) { const content = useMemo(() => getContent(), [getContent]); const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); diff --git a/src/app/components/editor/input.ts b/src/app/components/editor/input.ts index 017c33b8d..27a6b68fc 100644 --- a/src/app/components/editor/input.ts +++ b/src/app/components/editor/input.ts @@ -322,7 +322,7 @@ const parseHeadingNode = ( const headingMatch = node.name.match(/^h([123456])$/); const [, g1AsLevel] = headingMatch ?? ['h3', '3']; - const level = parseInt(g1AsLevel, 10); + const level = Number.parseInt(g1AsLevel, 10); const mdSequence = node.attribs['data-md']; if (mdSequence !== undefined) { @@ -334,7 +334,7 @@ const parseHeadingNode = ( return { type: BlockType.Heading, - level: (level <= 3 ? level : 3) as HeadingLevel, + level: Math.min(level, 3) as HeadingLevel, children, }; }; diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 2f797e04f..6ded4b229 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -128,10 +128,12 @@ export const toMatrixCustomHTML = ( return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`; }; - if (Array.isArray(node)) return node.map(parseNode).join(''); + if (Array.isArray(node)) return node.map((element, index, array) => parseNode(element, index, array)).join(''); if (Text.isText(node)) return textToCustomHtml(node, opts); - const children = node.children.map(parseNode).join(''); + const children = node.children + .map((element, index, array) => parseNode(element, index, array)) + .join(''); return elementToCustomHtml(node, children); }; @@ -193,14 +195,14 @@ export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean * @returns boolean */ export const customHtmlEqualsPlainText = (customHtml: string, plain: string): boolean => - customHtml.replace(//g, '\n') === sanitizeText(plain); + customHtml.replaceAll('
', '\n') === sanitizeText(plain); -export const trimCustomHtml = (customHtml: string) => customHtml.replace(/$/g, '').trim(); +export const trimCustomHtml = (customHtml: string) => customHtml.replaceAll(/$/g, '').trim(); export const trimCommand = (cmdName: string, str: string) => { const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`); - const match = str.match(cmdRegX); + const match = new RegExp(cmdRegX).exec(str); if (!match) return str; return str.slice(match[0].length); }; diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 83804b968..bebb6ef29 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -169,7 +169,7 @@ type EmojiSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarProps) { +function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -245,7 +245,7 @@ type StickerSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: StickerSidebarProps) { +function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -294,7 +294,7 @@ function EmojiGroupHolder({ previewAtom, onGroupItemClick, children, -}: EmojiGroupHolderProps) { +}: Readonly) { const setPreviewData = useSetAtom(previewAtom); const handleEmojiPreview = useCallback( @@ -375,7 +375,7 @@ export function EmojiBoard({ onStickerSelect, allowTextCustomEmoji, addToRecentEmoji = true, -}: EmojiBoardProps) { +}: Readonly) { const mx = useMatrixClient(); const emojiTab = tab === EmojiBoardTab.Emoji; @@ -543,7 +543,7 @@ export function EmojiBoard({ id={SEARCH_GROUP_ID} label={searchedItems.length ? 'Search Results' : 'No Results found'} > - {searchedItems.map(renderItem)} + {searchedItems.map((element, index) => renderItem(element, index))} )}
( [room, setReplyDraft] ); - function MenuOptions({ mEvent }: { mEvent: MatrixEvent }) { + function MenuOptions({ mEvent }: Readonly<{ mEvent: MatrixEvent }>) { const setModal = useSetAtom(modalAtom); return ( @@ -177,7 +177,7 @@ export const EventHistory = as<'div', EventHistoryProps>( ); } - function EventItem({ mEvent, EventContent }: { mEvent: MatrixEvent; EventContent: IContent }) { + function EventItem({ mEvent, EventContent }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { const [isHovered, setIsHovered] = useState(false); return ( ) { if (body === '') return ; if (customBody) { if (customBody === '') return ; diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index eddc13e27..2afd2aae3 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -68,10 +68,10 @@ export const ThreadIndicator = as<'div'>(({ ...props }, ref) => ( type ReplyProps = { room: Room; - timelineSet?: EventTimelineSet | undefined; + timelineSet?: EventTimelineSet; replyEventId: string; - threadRootId?: string | undefined; - onClick?: MouseEventHandler | undefined; + threadRootId?: string; + onClick?: MouseEventHandler; }; export const Reply = as<'div', ReplyProps>( @@ -119,10 +119,10 @@ export const Reply = as<'div', ReplyProps>( if (format === 'org.matrix.custom.html' && formattedBody) { const strippedHtml = trimReplyFromFormattedBody(formattedBody) - .replace(//gi, ' ') - .replace(/<\/p>\s*]*>/gi, ' ') - .replace(/<\/?p[^>]*>/gi, '') - .replace(/(?:\r\n|\r|\n)/g, ' '); + .replaceAll(//gi, ' ') + .replaceAll(/<\/p>\s*]*>/gi, ' ') + .replaceAll(/<\/?p[^>]*>/gi, '') + .replaceAll(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, useAuthentication, @@ -130,7 +130,7 @@ export const Reply = as<'div', ReplyProps>( }); bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element; } else if (body) { - const strippedBody = trimReplyFromBody(body).replace(/(?:\r\n|\r|\n)/g, ' '); + const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' '); bodyJSX = scaleSystemEmoji(strippedBody); } diff --git a/src/app/components/time-date/DatePicker.tsx b/src/app/components/time-date/DatePicker.tsx index c2daca427..078d91d8e 100644 --- a/src/app/components/time-date/DatePicker.tsx +++ b/src/app/components/time-date/DatePicker.tsx @@ -33,7 +33,7 @@ export const DatePicker = forwardRef( const currentDate = dateFor(selectedYear, selectedMonth, selectedDay); const time = value - currentDate; - const newDate = dateFor(year, month, mDays < selectedDay ? mDays : selectedDay); + const newDate = dateFor(year, month, Math.min(mDays, selectedDay)); const newValue = newDate + time; handleSubmit(newValue); @@ -60,7 +60,7 @@ export const DatePicker = forwardRef( - {Array.from(Array(daysInMonth(selectedMonth, selectedYear)).keys()) + {Array.from(new Array(daysInMonth(selectedMonth, selectedYear)).keys()) .map((i) => i + 1) .map((day) => ( ( ))} - {Array.from(Array(12).keys()) + {Array.from(new Array(12).keys()) .map((i) => i + 1) .map((month) => ( ( ))} - {Array.from(Array(yearsRange).keys()) + {Array.from(new Array(yearsRange).keys()) .map((i) => minYear + i) .map((year) => ( ) { const { originalFile, metadata } = fileItem; const fileUrl = useObjectURL(originalFile); @@ -53,7 +53,7 @@ function PreviewImage({ fileItem }: PreviewImageProps) { type PreviewVideoProps = { fileItem: TUploadItem; }; -function PreviewVideo({ fileItem }: PreviewVideoProps) { +function PreviewVideo({ fileItem }: Readonly) { const { originalFile, metadata } = fileItem; const fileUrl = useObjectURL(originalFile); @@ -131,7 +131,7 @@ export function UploadCardRenderer({ onRemove, onComplete, roomId, -}: UploadCardRendererProps) { +}: Readonly) { const mx = useMatrixClient(); const mediaConfig = useMediaConfig(); const allowSize = mediaConfig['m.upload.size'] || Infinity; diff --git a/src/app/components/upload-card/UploadDescriptionEditor.tsx b/src/app/components/upload-card/UploadDescriptionEditor.tsx index 447f02437..563f06eda 100644 --- a/src/app/components/upload-card/UploadDescriptionEditor.tsx +++ b/src/app/components/upload-card/UploadDescriptionEditor.tsx @@ -53,7 +53,7 @@ export function DescriptionEditor({ imagePackRooms, onSave, onCancel, -}: DescriptionEditorProps) { +}: Readonly) { const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index 09e2ab970..5d0f9e7e3 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -65,7 +65,7 @@ function UserExtendedSection({ profile, htmlReactParserOptions, linkifyOpts, -}: UserExtendedSectionProps) { +}: Readonly) { const clamp = (str: any, len: number) => { const stringified = String(str ?? ''); return stringified.length > len ? `${stringified.slice(0, len)}...` : stringified; @@ -108,7 +108,7 @@ function UserExtendedSection({ return new Intl.DateTimeFormat([], { hour: 'numeric', minute: '2-digit', - timeZone: profile.timezone.replace(/^["']|["']$/g, ''), + timeZone: profile.timezone.replaceAll(/^["']|["']$/g, ''), }).format(new Date()); } catch { return null; @@ -133,7 +133,7 @@ function UserExtendedSection({ const safetyTrim = rawBio.length > 2048 ? rawBio.slice(0, 2048) : rawBio; - const visibleText = safetyTrim.replace(/<[^>]*>?/gm, ''); + const visibleText = safetyTrim.replaceAll(/<[^>]*>?/gm, ''); const VISIBLE_LIMIT = 1024; if (visibleText.length <= VISIBLE_LIMIT) { @@ -163,7 +163,7 @@ function UserExtendedSection({ - {localTime} ({profile.timezone.replace(/^["']|["']$/g, '')}) + {localTime} ({profile.timezone.replaceAll(/^["']|["']$/g, '')}) )} @@ -252,7 +252,7 @@ type UserRoomProfileProps = { userId: string; initialProfile?: Partial; }; -export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps) { +export function UserRoomProfile({ userId, initialProfile }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const navigate = useNavigate(); @@ -296,7 +296,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps const parsedBanner = typeof extendedProfile.bannerUrl === 'string' - ? extendedProfile.bannerUrl.replace(/^"|"$/g, '') + ? extendedProfile.bannerUrl.replaceAll(/^"|"$/g, '') : undefined; const bannerHttpUrl = parsedBanner From 412c5284beb9ae02f50349c9f049b0f01f7f4868 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:14:24 +0100 Subject: [PATCH 08/79] fix maintainability issues raised by sonarqube - Built-in constructors should be called consistently with or without "new" (typescript:S7723) - Negated conditions should be avoided when an else clause is present (typescript:S7735) - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - Use ".some()" instead of ".filter().length" checks or ".find()" for existence testing (typescript:S7754) - React props should be read-only (typescript:S6759) - Number static methods and properties should be preferred over global equivalents (typescript:S7773) - The return value of "useState" should be destructured and named symmetrically (typescript:S6754) - Optional chaining should be preferred (typescript:S6582) - Arrays used only for existence checks should be Sets (typescript:S7776) - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/components/time-date/TimePicker.tsx | 8 +++---- .../emojis-stickers/RoomPacks.tsx | 10 ++++----- .../permissions/PowersEditor.tsx | 6 ++--- src/app/features/lobby/DnD.tsx | 14 ++++++------ src/app/features/lobby/Lobby.tsx | 7 +++--- .../features/message-search/MessageSearch.tsx | 6 ++--- src/app/features/room/RoomTimeline.tsx | 16 ++++++++++---- src/app/features/room/RoomViewHeader.tsx | 12 +++++----- src/app/features/settings/about/About.tsx | 6 ++--- .../settings/account/NameColorEditor.tsx | 4 ++-- src/app/features/settings/account/Profile.tsx | 16 +++++++------- .../features/settings/cosmetics/Themes.tsx | 8 +++---- src/app/features/settings/general/General.tsx | 20 ++++++++--------- src/app/hooks/useCommands.ts | 17 +++++++------- src/app/hooks/useRoomWidgets.ts | 22 +++++++++---------- src/app/hooks/useUserProfile.ts | 10 ++++----- src/app/pages/client/explore/Server.tsx | 16 +++++++------- src/app/pages/client/inbox/Notifications.tsx | 10 ++++----- src/app/pages/client/sidebar/SpaceTabs.tsx | 20 ++++++++--------- src/app/utils/ASCIILexicalTable.ts | 4 ++-- 20 files changed, 119 insertions(+), 113 deletions(-) diff --git a/src/app/components/time-date/TimePicker.tsx b/src/app/components/time-date/TimePicker.tsx index b90b78347..c16ad7caa 100644 --- a/src/app/components/time-date/TimePicker.tsx +++ b/src/app/components/time-date/TimePicker.tsx @@ -64,7 +64,7 @@ export const TimePicker = forwardRef( {hour24Clock - ? Array.from(Array(24).keys()).map((hour) => ( + ? Array.from(new Array(24).keys()).map((hour) => ( ( {hour < 10 ? `0${hour}` : hour} )) - : Array.from(Array(12).keys()) + : Array.from(new Array(12).keys()) .map((i) => { if (i === 0) return 12; return i; @@ -102,7 +102,7 @@ export const TimePicker = forwardRef( ))} - {Array.from(Array(60).keys()).map((minute) => ( + {Array.from(new Array(60).keys()).map((minute) => ( ( ) { const mx = useMatrixClient(); const alive = useAlive(); @@ -75,9 +75,9 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) { const name = nameInput?.value.trim(); if (!name) return; - let packKey = name.replace(/\s/g, '-'); + let packKey = name.replaceAll(/\s/g, '-'); - const hasPack = (k: string): boolean => !!packs.find((pack) => pack.address?.stateKey === k); + const hasPack = (k: string): boolean => packs.some((pack) => pack.address?.stateKey === k); if (hasPack(packKey)) { packKey = suffixRename(packKey, hasPack); } @@ -141,7 +141,7 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) { type RoomPacksProps = { onViewPack: (imagePack: ImagePack) => void; }; -export function RoomPacks({ onViewPack }: RoomPacksProps) { +export function RoomPacks({ onViewPack }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const room = useRoom(); @@ -193,7 +193,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) { const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined; const { address } = pack; if (!address) return null; - const removed = !!removedPacks.find((addr) => packAddressEqual(addr, address)); + const removed = removedPacks.some((addr) => packAddressEqual(addr, address)); return ( void; onClose: () => void; }; -function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) { +function EditPower({ maxPower, power, tag, onSave, onClose }: Readonly) { const mx = useMatrixClient(); const room = useRoom(); const roomToParents = useAtomValue(roomToParentsAtom); @@ -103,7 +103,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) { const nameInput = target?.nameInput as HTMLInputElement | undefined; if (!powerInput || !nameInput) return; - const tagPower = parseInt(powerInput.value, 10); + const tagPower = Number.parseInt(powerInput.value, 10); if (Number.isNaN(tagPower)) return; const tagName = nameInput.value.trim(); @@ -307,7 +307,7 @@ type PowersEditorProps = { powerLevels: IPowerLevels; requestClose: () => void; }; -export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { +export function PowersEditor({ powerLevels, requestClose }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const room = useRoom(); diff --git a/src/app/features/lobby/DnD.tsx b/src/app/features/lobby/DnD.tsx index 71c6bf8e3..fa4584a40 100644 --- a/src/app/features/lobby/DnD.tsx +++ b/src/app/features/lobby/DnD.tsx @@ -29,9 +29,8 @@ export const useDraggableItem = ( const target = targetRef.current; const dragHandle = dragHandleRef?.current ?? undefined; - return !target - ? undefined - : draggable({ + return target + ? draggable({ element: target, dragHandle, getInitialData: () => item, @@ -43,7 +42,8 @@ export const useDraggableItem = ( setDragging(false); onDragging(undefined); }, - }); + }) + : undefined; }, [targetRef, dragHandleRef, item, onDragging]); return dragging; @@ -72,14 +72,14 @@ export function AfterItemDropTarget({ afterSpace, nextRoomId, canDrop, -}: AfterItemDropTargetProps) { +}: Readonly) { const targetRef = useRef(null); const [dropState, setDropState] = useState<'idle' | 'allow' | 'not-allow'>('idle'); useEffect(() => { const target = targetRef.current; if (!target) { - throw Error('drop target ref is not set properly'); + throw new Error('drop target ref is not set properly'); } return dropTargetForElements({ @@ -126,7 +126,7 @@ export const useDnDMonitor = ( useEffect(() => { const scrollElement = scrollRef.current; if (!scrollElement) { - throw Error('Scroll element ref not configured'); + throw new Error('Scroll element ref not configured'); } return combine( diff --git a/src/app/features/lobby/Lobby.tsx b/src/app/features/lobby/Lobby.tsx index 0bc474260..180e0d81f 100644 --- a/src/app/features/lobby/Lobby.tsx +++ b/src/app/features/lobby/Lobby.tsx @@ -179,7 +179,7 @@ export function Lobby() { return new Set(sideSpaces); }, [sidebarItems]); - const [spacesItems, setSpacesItem] = useState>(() => new Map()); + const [spacesItems, setSpacesItems] = useState>(() => new Map()); useElementSizeObserver( useCallback(() => heroSectionRef.current, []), @@ -302,8 +302,7 @@ export function Lobby() { } if ( - itemRoom && - itemRoom.getJoinRule() === JoinRule.Restricted && + itemRoom?.getJoinRule() === JoinRule.Restricted && item.parentId !== containerParentId ) { // change join rule allow parameter when dragging @@ -394,7 +393,7 @@ export function Lobby() { const handleSpacesFound = useCallback( (sItems: IHierarchyRoom[]) => { setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) }); - setSpacesItem((current) => { + setSpacesItems((current) => { const newItems = produce(current, (draft) => { sItems.forEach((item) => draft.set(item.room_id, item)); }); diff --git a/src/app/features/message-search/MessageSearch.tsx b/src/app/features/message-search/MessageSearch.tsx index 46c948f67..db9191725 100644 --- a/src/app/features/message-search/MessageSearch.tsx +++ b/src/app/features/message-search/MessageSearch.tsx @@ -49,7 +49,7 @@ export function MessageSearch({ rooms, senders, scrollRef, -}: MessageSearchProps) { +}: Readonly) { const mx = useMatrixClient(); const mDirects = useAtomValue(mDirectAtom); const allRooms = useRooms(mx, allRoomsAtom, mDirects); @@ -175,7 +175,7 @@ export function MessageSearch({ }); }; - const lastVItem = vItems[vItems.length - 1]; + const lastVItem = vItems.at(-1); const lastVItemIndex: number | undefined = lastVItem?.index; const lastGroupIndex = groups.length - 1; useEffect(() => { @@ -253,7 +253,7 @@ export function MessageSearch({ {((msgSearchParams.term && status === 'pending') || (groups.length > 0 && vItems.length === 0)) && ( - {[...Array(8).keys()].map((key) => ( + {[...new Array(8).keys()].map((key) => ( ))} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 6365f851f..495cdd57c 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -205,7 +205,9 @@ export const timelineToEventsCount = (t: EventTimeline) => { export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => { const timelineEventCountReducer = (count: number, tm: EventTimeline) => count + timelineToEventsCount(tm); - return (timelines || []).filter(Boolean).reduce(timelineEventCountReducer, 0); + return (timelines || []) + .filter(Boolean) + .reduce((accumulator, element) => timelineEventCountReducer(accumulator, element), 0); }; export const getTimelineAndBaseIndex = ( @@ -576,7 +578,12 @@ type ThreadReplyChipProps = { onToggle: () => void; }; -function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReplyChipProps) { +function ThreadReplyChip({ + room, + mEventId, + openThreadId, + onToggle, +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const nicknames = useAtomValue(nicknamesAtom); @@ -602,7 +609,7 @@ function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReply } }); - const latestReply = replyEvents[replyEvents.length - 1]; + const latestReply = replyEvents.at(-1); const latestSenderId = latestReply?.getSender() ?? ''; const latestSenderName = getMemberDisplayName(room, latestSenderId, nicknames) ?? @@ -706,7 +713,7 @@ export function RoomTimeline({ roomInputRef, editor, onEditorReset, -}: RoomTimelineProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); @@ -772,6 +779,7 @@ export function RoomTimeline({ const atBottomAnchorRef = useRef(null); + // TODO: The return value of "useState" should be destructured and named symmetrically (typescript:S6754) const [atBottom, setAtBottomState] = useState(true); const atBottomRef = useRef(atBottom); const setAtBottom = useCallback((val: boolean) => { diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index a73df7871..55719e42a 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -340,7 +340,7 @@ const RoomMenu = forwardRef(({ room, requestClose }); RoomMenu.displayName = 'RoomMenu'; -export function RoomViewHeader({ callView }: { callView?: boolean }) { +export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { const navigate = useNavigate(); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -408,14 +408,14 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { } const lastSeenIndex = pinnedIds.indexOf(pinMarker?.last_seen_id); - if (lastSeenIndex !== -1) { - const newPins = pinnedIds.slice(lastSeenIndex + 1); - setUnreadPinsCount(newPins.length); - } else { + if (lastSeenIndex === -1) { const oldCount = pinMarker?.count ?? 0; const startIndex = Math.max(0, oldCount - 1); const newCount = pinnedIds.length > 0 ? pinnedIds.length - startIndex : 0; setUnreadPinsCount(Math.max(0, newCount)); + } else { + const newPins = pinnedIds.slice(lastSeenIndex + 1); + setUnreadPinsCount(newPins.length); } }; checkUnreads().catch((err) => { @@ -557,7 +557,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { await mx.setRoomAccountData(room.roomId, AccountDataEvent.SablePinStatus, { hash, count: pinnedIds.length, - last_seen_id: pinnedIds[pinnedIds.length - 1], + last_seen_id: pinnedIds.at(-1), }); }; diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index be5418159..1f399991c 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -35,7 +35,7 @@ export function HomeserverInfo() { setFederationUrl(newUrl); } }) - .catch((error2) => setVersion({ error: error2 })); + .catch((error_) => setVersion({ error: error_ })); } else { setVersion({ error }); } @@ -144,7 +144,7 @@ export function HomeserverInfo() { type AboutProps = { requestClose: () => void; }; -export function About({ requestClose }: AboutProps) { +export function About({ requestClose }: Readonly) { const mx = useMatrixClient(); const devLabel = IS_RELEASE_TAG ? '' : '-dev'; const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : ''; @@ -293,7 +293,7 @@ export function About({ requestClose }: AboutProps) { target="_blank" > Cinny - {' '} + is ©{' '} ) { const stripQuotes = (str?: string) => { if (!str) return ''; // to solve the silly tuwunel - return str.replace(/^["']|["']$/g, ''); + return str.replaceAll(/^["']|["']$/g, ''); }; const [tempColor, setTempColor] = useState(stripQuotes(current) || '#FFFFFF'); diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 42204d177..68daf9bf8 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -64,7 +64,7 @@ type ProfileProps = { profile: UserProfile; userId: string; }; -function ProfileAvatar({ profile, userId }: ProfileProps) { +function ProfileAvatar({ profile, userId }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const capabilities = useCapabilities(); @@ -218,7 +218,7 @@ function ProfileAvatar({ profile, userId }: ProfileProps) { } // eslint-disable-next-line @typescript-eslint/no-unused-vars -function ProfileBanner({ profile, userId }: ProfileProps) { +function ProfileBanner({ profile, userId }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [alertRemove, setAlertRemove] = useState(false); @@ -387,7 +387,7 @@ function ProfileBanner({ profile, userId }: ProfileProps) { ); } -function ProfileDisplayName({ profile, userId }: ProfileProps) { +function ProfileDisplayName({ profile, userId }: Readonly) { const mx = useMatrixClient(); const capabilities = useCapabilities(); const disableSetDisplayname = capabilities['m.set_displayname']?.enabled === false; @@ -479,7 +479,7 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) { ); } -function ProfileExtended({ profile, userId }: ProfileProps) { +function ProfileExtended({ profile, userId }: Readonly) { const mx = useMatrixClient(); const setGlobalProfiles = useSetAtom(profilesCacheAtom); @@ -488,12 +488,12 @@ function ProfileExtended({ profile, userId }: ProfileProps) { const currentStatus = presence?.status || ''; // Keys we don't render here nor handle seperately but still need to exclude - const EXCLUDED_KEYS = ['kitty.meow.is_cat', 'kitty.meow.has_cats']; + const EXCLUDED_KEYS = new Set(['kitty.meow.is_cat', 'kitty.meow.has_cats']); // Unknown fields / unimplemented non-matrix-spec fields // Only renders them, can't edit or set const extendedFields = Object.entries(profile.extended || {}).filter( - ([key]) => !EXCLUDED_KEYS.includes(key) + ([key]) => !EXCLUDED_KEYS.has(key) ); const handleSaveField = useCallback( @@ -585,7 +585,7 @@ function ProfileExtended({ profile, userId }: ProfileProps) { onSave={(htmlBio) => { handleSaveField('moe.sable.app.bio', htmlBio); - const cleanedHtml = htmlBio.replace(/<\/blockquote>/g, ''); + const cleanedHtml = htmlBio.replaceAll('
', ''); handleSaveField('chat.commet.profile_bio', { format: 'org.matrix.custom.html', formatted_body: cleanedHtml, @@ -642,7 +642,7 @@ type AnimalCosmeticsProps = { profile: UserProfile; userId: string; }; -function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) { +function AnimalCosmetics({ profile, userId }: Readonly) { const mx = useMatrixClient(); const setGlobalProfiles = useSetAtom(profilesCacheAtom); const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals'); diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index a57af34a0..8d0f75e7e 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -60,7 +60,7 @@ export const ThemeSelector = as<'div', ThemeSelectorProps>( ) ); -function SelectTheme({ disabled }: { disabled?: boolean }) { +function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) { const themes = useThemes(); const themeNames = useThemeNames(); const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); @@ -288,7 +288,7 @@ function ThemeSettings() { max="100" step="1" value={saturation} - onChange={(e) => setSaturation(parseInt(e.target.value, 10))} + onChange={(e) => setSaturation(Number.parseInt(e.target.value, 10))} style={{ width: toRem(160), cursor: 'pointer', @@ -361,7 +361,7 @@ function PageZoomInput() { 'value' in evt.target && typeof evt.target.value === 'string' ) { - const newZoom = parseInt(evt.target.value, 10); + const newZoom = Number.parseInt(evt.target.value, 10); if (Number.isNaN(newZoom)) return; const safeZoom = Math.max(Math.min(newZoom, 150), 75); setPageZoom(safeZoom); @@ -372,7 +372,7 @@ function PageZoomInput() { return ( void; }; -function DateHint({ hasChanges, handleReset }: DateHintProps) { +function DateHint({ hasChanges, handleReset }: Readonly) { const [anchor, setAnchor] = useState(); const categoryPadding = { padding: config.space.S200, paddingTop: 0 }; @@ -223,7 +223,7 @@ type CustomDateFormatProps = { value: string; onChange: (format: string) => void; }; -function CustomDateFormat({ value, onChange }: CustomDateFormatProps) { +function CustomDateFormat({ value, onChange }: Readonly) { const [dateFormatCustom, setDateFormatCustom] = useState(value); useEffect(() => { @@ -288,12 +288,12 @@ type PresetDateFormatProps = { value: string; onChange: (format: string) => void; }; -function PresetDateFormat({ value, onChange }: PresetDateFormatProps) { +function PresetDateFormat({ value, onChange }: Readonly) { const [menuCords, setMenuCords] = useState(); const dateFormatItems = useDateFormatItems(); const getDisplayDate = (format: string): string => - format !== '' ? dayjs().format(format) : 'Custom'; + format === '' ? 'Custom' : dayjs().format(format); const handleMenu: MouseEventHandler = (evt) => { setMenuCords(evt.currentTarget.getBoundingClientRect()); @@ -415,7 +415,7 @@ function DateAndTime() { ); } -function Editor({ isMobile }: { isMobile: boolean }) { +function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { const [enterForNewline, setEnterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown'); const [hideActivity, setHideActivity] = useSetting(settingsAtom, 'hideActivity'); @@ -681,7 +681,7 @@ function SelectMessageSpacing() { ); } -function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) { +function SelectRightSwipeAction({ disabled }: Readonly<{ disabled?: boolean }>) { const [menuCords, setMenuCords] = useState(); const [action, setAction] = useSetting(settingsAtom, 'rightSwipeAction'); @@ -749,7 +749,7 @@ function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) { ); } -function Gestures({ isMobile }: { isMobile: boolean }) { +function Gestures({ isMobile }: Readonly<{ isMobile: boolean }>) { const [mobileGestures, setMobileGestures] = useSetting(settingsAtom, 'mobileGestures'); return ( @@ -788,7 +788,7 @@ function EmojiSelectorThresholdInput() { const val = evt.target.value; setInputValue(val); - const parsed = parseInt(val, 10); + const parsed = Number.parseInt(val, 10); if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) { setEmojiThreshold(parsed); } @@ -809,7 +809,7 @@ function EmojiSelectorThresholdInput() { return ( void; }; -export function General({ requestClose }: GeneralProps) { +export function General({ requestClose }: Readonly) { return ( diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 0c2008c01..3a9b2a1ca 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -36,16 +36,16 @@ import { useRoomNavigate } from './useRoomNavigate'; import { enrichWidgetUrl } from './useRoomWidgets'; import { useUserProfile } from './useUserProfile'; -export const SHRUG = '¯\\_(ツ)_/¯'; +export const SHRUG = String.raw`¯\_(ツ)_/¯`; export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻'; export const UNFLIP = '┬─┬ノ( º_ºノ)'; -const FLAG_PAT = '(?:^|\\s)-(\\w+)\\b'; +const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`; const FLAG_REG = new RegExp(FLAG_PAT); const FLAG_REG_G = new RegExp(FLAG_PAT, 'g'); export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => { - const flagMatch = payload.match(FLAG_REG); + const flagMatch = new RegExp(FLAG_REG).exec(payload); if (!flagMatch) { return [payload, undefined]; @@ -116,7 +116,7 @@ export const parseTimestampFlag = (input: string): number | undefined => { return undefined; } - const value = parseFloat(match[1]); // supports decimal values + const value = Number.parseFloat(match[1]); // supports decimal values const unit = match[2]; const now = Date.now(); // in milliseconds @@ -282,7 +282,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }, [Command.Shrug]: { name: Command.Shrug, - description: 'Send ¯\\_(ツ)_/¯ as message', + description: String.raw`Send ¯\_(ツ)_/¯ as message`, exe: async () => undefined, }, [Command.TableFlip]: { @@ -559,8 +559,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { room.roomId, token, 20, - Direction.Forward, - undefined + Direction.Forward ); const { end, chunk } = response; // remove until the latest event; @@ -749,7 +748,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const input = payload .trim() - .replace(/[;{}<>]/g, '') + .replaceAll(/[;{}<>]/g, '') .slice(0, 32); const userId = mx.getSafeUserId(); @@ -793,7 +792,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const input = payload .trim() - .replace(/[;{}<>]/g, '') + .replaceAll(/[;{}<>]/g, '') .slice(0, 32); const userId = mx.getSafeUserId(); diff --git a/src/app/hooks/useRoomWidgets.ts b/src/app/hooks/useRoomWidgets.ts index a424e2eca..65381ddd3 100644 --- a/src/app/hooks/useRoomWidgets.ts +++ b/src/app/hooks/useRoomWidgets.ts @@ -27,16 +27,16 @@ export const resolveWidgetUrl = ( const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light'; let resolved = url - .replace(/\$matrix_user_id/g, encodeURIComponent(userId)) - .replace(/\$matrix_room_id/g, encodeURIComponent(roomId)) - .replace(/\$matrix_display_name/g, encodeURIComponent(displayName)) - .replace(/\$matrix_avatar_url/g, encodeURIComponent(avatarUrl)) - .replace(/\$matrix_widget_id/g, encodeURIComponent(widgetId)) - .replace(/\$org\.matrix\.msc2873\.client_id/g, encodeURIComponent(clientId)) - .replace(/\$org\.matrix\.msc2873\.client_theme/g, encodeURIComponent(theme)) - .replace(/\$org\.matrix\.msc2873\.client_language/g, encodeURIComponent(lang)) - .replace(/\$org\.matrix\.msc3819\.matrix_device_id/g, encodeURIComponent(deviceId)) - .replace(/\$org\.matrix\.msc4039\.matrix_base_url/g, encodeURIComponent(baseUrl)); + .replaceAll('$matrix_user_id', encodeURIComponent(userId)) + .replaceAll('$matrix_room_id', encodeURIComponent(roomId)) + .replaceAll('$matrix_display_name', encodeURIComponent(displayName)) + .replaceAll('$matrix_avatar_url', encodeURIComponent(avatarUrl)) + .replaceAll('$matrix_widget_id', encodeURIComponent(widgetId)) + .replaceAll('$org.matrix.msc2873.client_id', encodeURIComponent(clientId)) + .replaceAll('$org.matrix.msc2873.client_theme', encodeURIComponent(theme)) + .replaceAll('$org.matrix.msc2873.client_language', encodeURIComponent(lang)) + .replaceAll('$org.matrix.msc3819.matrix_device_id', encodeURIComponent(deviceId)) + .replaceAll('$org.matrix.msc4039.matrix_base_url', encodeURIComponent(baseUrl)); try { const u = new URL(resolved); @@ -112,7 +112,7 @@ export const useRoomWidgets = (room: Room): RoomWidget[] => { return events.reduce((widgets, event) => { const content = event.getContent(); - if (!content || !content.url || Object.keys(content).length === 0) return widgets; + if (!content?.url || Object.keys(content).length === 0) return widgets; const stateKey = event.getStateKey(); if (!stateKey) return widgets; diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index e5f1a013a..22ffa5b2a 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -27,7 +27,7 @@ export type UserProfile = { }; const normalizeInfo = (info: any): UserProfile => { - const knownKeys = [ + const knownKeys = new Set([ 'avatar_url', 'displayname', 'io.fsky.nyx.pronouns', @@ -40,11 +40,11 @@ const normalizeInfo = (info: any): UserProfile => { 'moe.sable.app.name_color', 'kitty.meow.has_cats', 'kitty.meow.is_cat', - ]; + ]); const extended: Record = {}; Object.entries(info).forEach(([key, value]) => { - if (!knownKeys.includes(key)) { + if (!knownKeys.has(key)) { extended[key] = value; } }); @@ -68,10 +68,10 @@ const normalizeInfo = (info: any): UserProfile => { const isValidHex = (c: any): string | undefined => { if (typeof c !== 'string') return undefined; // silly tuwunel smh - const cleaned = c.replace(/["']/g, '').trim(); + const cleaned = c.replaceAll(/["']/g, '').trim(); return /^#([0-9A-F]{3,6})$/i.test(cleaned) ? cleaned : undefined; }; -const sanitizeFont = (f: string) => f.replace(/[;{}<>]/g, '').slice(0, 32); +const sanitizeFont = (f: string) => f.replaceAll(/[;{}<>]/g, '').slice(0, 32); export const useUserProfile = ( userId: string, diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index 84fd8f36f..0ff06dd54 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -90,7 +90,7 @@ type SearchProps = { onSearch: (term: string) => void; onReset: () => void; }; -function Search({ active, loading, searchInputRef, onSearch, onReset }: SearchProps) { +function Search({ active, loading, searchInputRef, onSearch, onReset }: Readonly) { const handleSearchSubmit: FormEventHandler = (evt) => { evt.preventDefault(); const { searchInput } = evt.target as HTMLFormElement & { @@ -149,10 +149,10 @@ const DEFAULT_INSTANCE_NAME = 'Matrix'; function ThirdPartyProtocolsSelector({ instanceId, onChange, -}: { +}: Readonly<{ instanceId?: string; onChange: (instanceId?: string) => void; -}) { +}>) { const mx = useMatrixClient(); const [menuAnchor, setMenuAnchor] = useState(); @@ -251,7 +251,7 @@ type LimitButtonProps = { limit: number; onLimitChange: (limit: string) => void; }; -function LimitButton({ limit, onLimitChange }: LimitButtonProps) { +function LimitButton({ limit, onLimitChange }: Readonly) { const [menuAnchor, setMenuAnchor] = useState(); const handleLimitSubmit: FormEventHandler = (evt) => { @@ -360,7 +360,7 @@ export function PublicRooms() { const currentLimit: number = useMemo(() => { const limitParam = serverSearchParams.limit; if (!limitParam) return FALLBACK_ROOMS_LIMIT; - return parseInt(limitParam, 10) || FALLBACK_ROOMS_LIMIT; + return Number.parseInt(limitParam, 10) || FALLBACK_ROOMS_LIMIT; }, [serverSearchParams.limit]); const resetScroll = useCallback(() => { @@ -371,7 +371,7 @@ export function PublicRooms() { const fetchPublicRooms = useCallback(() => { const limit = typeof serverSearchParams.limit === 'string' - ? parseInt(serverSearchParams.limit, 10) + ? Number.parseInt(serverSearchParams.limit, 10) : FALLBACK_ROOMS_LIMIT; const roomType: string | null | undefined = serverSearchParams.type === 'null' ? null : serverSearchParams.type; @@ -387,7 +387,7 @@ export function PublicRooms() { since: serverSearchParams.since, filter: { generic_search_term: serverSearchParams.term, - room_types: roomType !== undefined ? [roomType] : undefined, + room_types: roomType === undefined ? undefined : [roomType], }, third_party_instance_id: serverSearchParams.instance, } @@ -574,7 +574,7 @@ export function PublicRooms() {
{isLoading && ( - {[...Array(currentLimit).keys()].map((item) => ( + {[...new Array(currentLimit).keys()].map((item) => ( ))} diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index adc79ed2b..7543720d0 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -121,7 +121,7 @@ const groupNotifications = ( const groupIndex = groups.length - 1; const lastAddedGroup: RoomNotificationsGroup | undefined = groups[groupIndex]; - if (lastAddedGroup && notification.room_id === lastAddedGroup.roomId) { + if (notification.room_id === lastAddedGroup?.roomId) { lastAddedGroup.notifications.push(notification); return; } @@ -223,7 +223,7 @@ function RoomNotificationsGroupComp({ legacyUsernameColor, hour24Clock, dateFormatString, -}: RoomNotificationsGroupProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const unread = useRoomUnread(room.roomId, roomToUnreadAtom); @@ -623,7 +623,7 @@ export function Notifications() { loadTimeline(); }, [loadTimeline]); - const lastVItem = vItems[vItems.length - 1]; + const lastVItem = vItems.at(-1); const lastVItemIndex: number | undefined = lastVItem?.index; useEffect(() => { if ( @@ -671,7 +671,7 @@ export function Notifications() { setOnlyHighlighted(false)} - variant={!onlyHighlight ? 'Success' : 'Surface'} + variant={onlyHighlight ? 'Surface' : 'Success'} aria-pressed={!onlyHighlight} before={!onlyHighlight && } outlined @@ -758,7 +758,7 @@ export function Notifications() { {timelineState.status === AsyncStatus.Loading && ( - {[...Array(8).keys()].map((key) => ( + {[...new Array(8).keys()].map((key) => ( ({ item }), @@ -258,7 +257,8 @@ const useDraggableItem = ( setDragging(false); onDragging?.(undefined); }, - }); + }) + : undefined; }, [targetRef, dragHandleRef, item, onDragging]); return dragging; @@ -357,7 +357,7 @@ const useDnDMonitor = ( useEffect(() => { const scrollElement = scrollRef.current; if (!scrollElement) { - throw Error('Scroll element ref not configured'); + throw new Error('Scroll element ref not configured'); } return combine( @@ -399,7 +399,7 @@ function SpaceTab({ onDragging, disabled, onUnpin, -}: SpaceTabProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const targetRef = useRef(null); @@ -515,7 +515,7 @@ type OpenedSpaceFolderProps = { onClose: MouseEventHandler; children?: ReactNode; }; -function OpenedSpaceFolder({ folder, onClose, children }: OpenedSpaceFolderProps) { +function OpenedSpaceFolder({ folder, onClose, children }: Readonly) { const aboveTargetRef = useRef(null); const belowTargetRef = useRef(null); @@ -555,7 +555,7 @@ function ClosedSpaceFolder({ onOpen, onDragging, disabled, -}: ClosedSpaceFolderProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const handlerRef = useRef(null); @@ -628,7 +628,7 @@ function ClosedSpaceFolder({ type SpaceTabsProps = { scrollRef: RefObject; }; -export function SpaceTabs({ scrollRef }: SpaceTabsProps) { +export function SpaceTabs({ scrollRef }: Readonly) { const navigate = useNavigate(); const mx = useMatrixClient(); const screenSize = useScreenSizeContext(); @@ -786,7 +786,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) { } const activePath = navToActivePath.get(targetSpaceId); - if (activePath && activePath.pathname.startsWith(spacePath)) { + if (activePath?.pathname.startsWith(spacePath)) { navigate(joinPathComponent(activePath)); return; } diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index 3dcd43d05..dc97b4127 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -61,13 +61,13 @@ export class ASCIILexicalTable { } first(): string { - return String.fromCharCode(this.startCode); + return String.fromCodePoint(this.startCode); } last(): string { let str = ''; for (let i = 0; i < this.maxStrWidth; i += 1) { - str += String.fromCharCode(this.endCode); + str += String.fromCodePoint(this.endCode); } return str; } From aa6a764732f56158eef52be8187bedaef1d0bc4c Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:18:57 +0100 Subject: [PATCH 09/79] fix maintainability issues raised by sonarqube - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/ASCIILexicalTable.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index dc97b4127..46c35c393 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -164,7 +164,7 @@ export class ASCIILexicalTable { prev += String.fromCharCode(lastCode - 1); while (prev.length < this.maxStrWidth) { - prev += String.fromCharCode(this.endCode); + prev += String.fromCodePoint(this.endCode); } return prev; } From b44796ad0c5448327c738a563b13d4b1f73e747d Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:20:55 +0100 Subject: [PATCH 10/79] fix maintainability issues raised by sonarqube - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - Existence checks should use ".includes()" instead of ".indexOf()" or ".lastIndexOf()" (typescript:S7765) - Use "globalThis" instead of "window", "self", or "global" (typescript:S7764) --- src/app/utils/AsyncSearch.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app/utils/AsyncSearch.ts b/src/app/utils/AsyncSearch.ts index 26dd92047..c799c60bb 100644 --- a/src/app/utils/AsyncSearch.ts +++ b/src/app/utils/AsyncSearch.ts @@ -27,12 +27,12 @@ export type TerminateAsyncSearch = () => void; export const normalize = (str: string, options?: NormalizeOption) => { let nStr = str.normalize((options?.normalizeUnicode ?? true) ? 'NFKC' : 'NFC'); if (!options?.caseSensitive) nStr = nStr.toLocaleLowerCase(); - if (options?.ignoreWhitespace ?? true) nStr = nStr.replace(/\s/g, ''); + if (options?.ignoreWhitespace ?? true) nStr = nStr.replaceAll(/\s/g, ''); return nStr; }; export const matchQuery = (item: string, query: string, options?: MatchQueryOption): boolean => { - if (options?.contain) return item.indexOf(query) !== -1; + if (options?.contain) return item.includes(query); return item.startsWith(query); }; @@ -46,7 +46,7 @@ export const AsyncSearch = ( let searchIndex = 0; let sessionStartTimestamp = 0; - let sessionScheduleId: number | undefined; + let sessionScheduleId: ReturnType | undefined; const terminateSearch: TerminateAsyncSearch = () => { resultList = []; @@ -62,7 +62,7 @@ export const AsyncSearch = ( // return if find session got reset if (sessionTimestamp !== sessionStartTimestamp) return; - sessionStartTimestamp = window.performance.now(); + sessionStartTimestamp = globalThis.performance.now(); for (; searchIndex < list.length; searchIndex += 1) { if (match(list[searchIndex], query)) { resultList.push(list[searchIndex]); @@ -71,14 +71,14 @@ export const AsyncSearch = ( } } - const matchFinishTime = window.performance.now(); + const matchFinishTime = globalThis.performance.now(); if (matchFinishTime - sessionStartTimestamp > 8) { const currentFindingCount = resultList.length; const thisSessionTimestamp = sessionStartTimestamp; if (findingCount !== currentFindingCount) onResult(resultList, query); searchIndex += 1; - sessionScheduleId = window.setTimeout(() => find(query, thisSessionTimestamp), 1); + sessionScheduleId = globalThis.setTimeout(() => find(query, thisSessionTimestamp), 1); return; } } From c7ebd49e107539e15602ff94548d6bc16b0fe16e Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:22:32 +0100 Subject: [PATCH 11/79] fix maintainability issues raised by sonarqube - Use "globalThis" instead of "window", "self", or "global" (typescript:S7764) - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/MegolmExportEncryption.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app/utils/MegolmExportEncryption.ts b/src/app/utils/MegolmExportEncryption.ts index 896a8d9d4..96250e5bd 100644 --- a/src/app/utils/MegolmExportEncryption.ts +++ b/src/app/utils/MegolmExportEncryption.ts @@ -5,7 +5,7 @@ import { createLogger } from './debug'; const logger = createLogger('MegolmExportEncryption'); -const subtleCrypto = window.crypto.subtle; +const subtleCrypto = globalThis.crypto.subtle; export type FriendlyError = { message: string; @@ -43,9 +43,9 @@ function toArrayBufferView(data: Uint8Array): Uint8Array { function encodeBase64(uint8Array: Uint8Array): string { // Misinterpt the Uint8Array as Latin-1. // window.btoa expects a unicode string with codepoints in the range 0-255. - const latin1String = String.fromCharCode.apply(null, Array.from(uint8Array)); + const latin1String = String.fromCodePoint.apply(null, Array.from(uint8Array)); // Use the builtin base64 encoder. - return window.btoa(latin1String); + return globalThis.btoa(latin1String); } /** @@ -55,7 +55,7 @@ function encodeBase64(uint8Array: Uint8Array): string { */ function decodeBase64(base64: string): Uint8Array { // window.atob returns a unicode string with codepoints in the range 0-255. - const latin1String = window.atob(base64); + const latin1String = globalThis.atob(base64); // Encode the string as a Uint8Array const uint8Array = new Uint8Array(new ArrayBuffer(latin1String.length)); for (let i = 0; i < latin1String.length; i += 1) { @@ -303,10 +303,10 @@ export async function encryptMegolmKeyFile( const kdfRounds = normalizedOptions.kdf_rounds || 500000; const salt = new Uint8Array(new ArrayBuffer(16)); - window.crypto.getRandomValues(salt); + globalThis.crypto.getRandomValues(salt); const iv = new Uint8Array(new ArrayBuffer(16)); - window.crypto.getRandomValues(iv); + globalThis.crypto.getRandomValues(iv); // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary // (which would mean we wouldn't be able to decrypt on Android). The loss From afd5a5d488bb793e1c545b5411988056fb7e9445 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:23:46 +0100 Subject: [PATCH 12/79] fix maintainability issues raised by sonarqube - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/colorMXID.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/utils/colorMXID.ts b/src/app/utils/colorMXID.ts index 6b40b9596..c94a19d48 100644 --- a/src/app/utils/colorMXID.ts +++ b/src/app/utils/colorMXID.ts @@ -6,11 +6,11 @@ function hashCode(str?: string): number { return hash; } for (let i = 0; i < str.length; i += 1) { - const chr = str.charCodeAt(i); + const chr = str.codePointAt(i) ?? 0; // eslint-disable-next-line no-bitwise hash = (hash << 5) - hash + chr; // eslint-disable-next-line no-bitwise - hash |= 0; + hash = Math.trunc(hash); } return Math.abs(hash); } From c5d194576f202278485e6b12c38fd56f969a913b Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:45:04 +0100 Subject: [PATCH 13/79] fix formatting --- src/app/components/editor/output.ts | 3 ++- src/app/components/emoji-board/EmojiBoard.tsx | 6 +++++- src/app/components/event-history/EventHistory.tsx | 5 ++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 6ded4b229..9e3901925 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -128,7 +128,8 @@ export const toMatrixCustomHTML = ( return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`; }; - if (Array.isArray(node)) return node.map((element, index, array) => parseNode(element, index, array)).join(''); + if (Array.isArray(node)) + return node.map((element, index, array) => parseNode(element, index, array)).join(''); if (Text.isText(node)) return textToCustomHtml(node, opts); const children = node.children diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index bebb6ef29..ff407fdd2 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -245,7 +245,11 @@ type StickerSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { +function StickerSidebar({ + activeGroupAtom, + packs, + onScrollToGroup, +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); diff --git a/src/app/components/event-history/EventHistory.tsx b/src/app/components/event-history/EventHistory.tsx index 29f9ca16c..955a2846f 100644 --- a/src/app/components/event-history/EventHistory.tsx +++ b/src/app/components/event-history/EventHistory.tsx @@ -177,7 +177,10 @@ export const EventHistory = as<'div', EventHistoryProps>( ); } - function EventItem({ mEvent, EventContent }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { + function EventItem({ + mEvent, + EventContent, + }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { const [isHovered, setIsHovered] = useState(false); return ( Date: Sun, 15 Mar 2026 05:56:17 +0200 Subject: [PATCH 14/79] improved image loading logic --- .../message/content/ImageContent.tsx | 110 +++++++++++++----- 1 file changed, 79 insertions(+), 31 deletions(-) diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 017569662..f618d434d 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -6,6 +6,8 @@ import { Chip, Icon, Icons, + Menu, + MenuItem, Modal, Overlay, OverlayBackdrop, @@ -15,6 +17,7 @@ import { Tooltip, TooltipProvider, as, + config, } from 'folds'; import classNames from 'classnames'; import { BlurhashCanvas } from 'react-blurhash'; @@ -84,6 +87,7 @@ export const ImageContent = as<'div', ImageContentProps>( const [error, setError] = useState(false); const [viewer, setViewer] = useState(false); const [blurred, setBlurred] = useState(markedAsSpoiler ?? false); + const [isHovered, setIsHovered] = useState(false); const [srcState, loadSrc] = useAsyncCallback( useCallback(async () => { @@ -119,7 +123,14 @@ export const ImageContent = as<'div', ImageContentProps>( }, [autoPlay, loadSrc]); return ( - + setIsHovered(true)} + onPointerLeave={() => setIsHovered(false)} + > + {' '} {srcState.status === AsyncStatus.Success && ( }> @@ -156,7 +167,12 @@ export const ImageContent = as<'div', ImageContentProps>( /> )} {!autoPlay && !markedAsSpoiler && srcState.status === AsyncStatus.Idle && ( - + + +
+ + + + )} ); } diff --git a/src/app/plugins/matrix-to.ts b/src/app/plugins/matrix-to.ts index 03a7d2c17..35afe11d7 100644 --- a/src/app/plugins/matrix-to.ts +++ b/src/app/plugins/matrix-to.ts @@ -1,4 +1,12 @@ -const MATRIX_TO_BASE = 'https://matrix.to'; +let MATRIX_TO_BASE = 'https://matrix.to'; + +/** + * Override the default matrix.to base URL (configurable per deployment). + * Must be called before any getMatrixTo* functions are used. + */ +export const setMatrixToBase = (baseUrl?: string): void => { + if (baseUrl) MATRIX_TO_BASE = baseUrl.replace(/\/$/, ''); +}; export const getMatrixToUser = (userId: string): string => `${MATRIX_TO_BASE}/#/${userId}`; diff --git a/src/app/plugins/voice-recorder-kit/supportedCodec.ts b/src/app/plugins/voice-recorder-kit/supportedCodec.ts index 99481bde8..445147cda 100644 --- a/src/app/plugins/voice-recorder-kit/supportedCodec.ts +++ b/src/app/plugins/voice-recorder-kit/supportedCodec.ts @@ -46,7 +46,6 @@ export function getSupportedAudioCodec(): string | null { const userAgent = globalThis.navigator?.userAgent ?? ''; const isIOS = /iPad|iPhone|iPod/.test(userAgent) || - // eslint-disable-next-line @typescript-eslint/no-deprecated (globalThis.navigator?.platform === 'MacIntel' && globalThis.navigator?.maxTouchPoints > 1); const isSafari = /^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(userAgent) || isIOS; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 350f8e128..c7de24591 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -97,6 +97,7 @@ export interface Settings { autoplayEmojis: boolean; saveStickerEmojiBandwidth: boolean; alwaysShowCallButton: boolean; + faviconForMentionsOnly: boolean; // furry stuff renderAnimals: boolean; @@ -178,6 +179,7 @@ const defaultSettings: Settings = { autoplayEmojis: true, saveStickerEmojiBandwidth: false, alwaysShowCallButton: false, + faviconForMentionsOnly: false, // furry stuff renderAnimals: true, diff --git a/src/app/utils/sanitize.test.ts b/src/app/utils/sanitize.test.ts index f957b56ec..52c668e6b 100644 --- a/src/app/utils/sanitize.test.ts +++ b/src/app/utils/sanitize.test.ts @@ -37,7 +37,6 @@ describe('sanitizeCustomHtml – XSS prevention', () => { }); it('strips javascript: href on anchor tags', () => { - // eslint-disable-next-line no-script-url const result = sanitizeCustomHtml('link'); expect(result).not.toMatch(/javascript:/); }); diff --git a/src/index.css b/src/index.css index 453dc7f00..1c32c9170 100755 --- a/src/index.css +++ b/src/index.css @@ -187,6 +187,7 @@ pre { body.reduced-motion * { animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; } From e252a1242bc4dad4bff01e1c599b23ce0186ebf8 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 17:29:49 -0400 Subject: [PATCH 67/79] fix: highlight first autocomplete item to indicate Enter selection --- .../editor/autocomplete/AutocompleteMenu.css.tsx | 8 +++++++- .../components/editor/autocomplete/AutocompleteMenu.tsx | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index a160b6001..96a7dc16b 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -38,3 +38,9 @@ export const AutocompleteNotice = style([ AutocompleteMenuHeader, { color: color.SurfaceVariant.OnContainer }, ]); + +export const AutocompleteMenuItems = style({}); + +globalStyle(`${AutocompleteMenuItems} button:first-child`, { + backgroundColor: color.SurfaceVariant.ContainerHover, +}); diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index cda3b5e16..545437924 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -42,7 +42,9 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
{children}
+
+ {children} +
From ee01f9a9522294c205e63d3710e5bd3125cf401b Mon Sep 17 00:00:00 2001 From: 7w1 Date: Mon, 16 Mar 2026 17:14:49 -0500 Subject: [PATCH 68/79] add codeowners --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..696e96793 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @7w1 @Just-Insane @hazre From abf0848aa6af644dca42179923890abf04d89e44 Mon Sep 17 00:00:00 2001 From: melogale Date: Mon, 16 Mar 2026 19:23:46 -0400 Subject: [PATCH 69/79] fix delayed events --- src/app/features/widgets/GenericWidgetDriver.ts | 12 ++++++++++++ src/app/plugins/call/CallEmbed.ts | 10 ++++++++++ src/app/plugins/call/CallWidgetDriver.ts | 14 +++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/app/features/widgets/GenericWidgetDriver.ts b/src/app/features/widgets/GenericWidgetDriver.ts index d6f1ec71f..ee143b4f3 100644 --- a/src/app/features/widgets/GenericWidgetDriver.ts +++ b/src/app/features/widgets/GenericWidgetDriver.ts @@ -164,6 +164,18 @@ export class GenericWidgetDriver extends WidgetDriver { await this.mxClient._unstable_updateDelayedEvent(delayId, action); } + public async cancelScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel); + } + + public async restartScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart); + } + + public async sendScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Send); + } + public async sendToDevice( eventType: string, encrypted: boolean, diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index 960f21ced..61aef8684 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -9,9 +9,11 @@ import { } from 'matrix-js-sdk'; import { ClientWidgetApi, + type IWidgetApiRequest, IRoomEvent, IWidget, Widget, + WidgetApiFromWidgetAction, WidgetApiToWidgetAction, WidgetDriver, } from 'matrix-widget-api'; @@ -149,6 +151,14 @@ export class CallEmbed { const controlState = initialControlState ?? new CallControlState(true, false, true); this.control = new CallControl(controlState, call, iframe); + // acknowledge always on screen request to silence error + this.disposables.push( + this.listenAction(WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, (evt) => { + evt.preventDefault(); + this.call.transport.reply(evt.detail as IWidgetApiRequest, { success: true }); + }) + ); + let initialMediaEvent = true; this.disposables.push( this.listenAction(ElementWidgetActions.DeviceMute, (evt) => { diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index ba1b170ec..6d94891f8 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -8,7 +8,7 @@ import { type IWidgetApiErrorResponseDataDetails, type ISearchUserDirectoryResult, type IGetMediaConfigResult, - type UpdateDelayedEventAction, + UpdateDelayedEventAction, OpenIDRequestState, SimpleObservable, IOpenIDUpdate, @@ -165,6 +165,18 @@ export class CallWidgetDriver extends WidgetDriver { await client._unstable_updateDelayedEvent(delayId, action); } + public async cancelScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel); + } + + public async restartScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart); + } + + public async sendScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Send); + } + public async sendToDevice( eventType: string, encrypted: boolean, From c7063690f00049a67ea8e01a9aa9f99b6196363a Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 19:52:20 -0400 Subject: [PATCH 70/79] fix: focus first autocomplete item on menu open --- .../editor/autocomplete/AutocompleteMenu.css.tsx | 6 +----- .../components/editor/autocomplete/AutocompleteMenu.tsx | 7 ++++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 96a7dc16b..149f10108 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { globalStyle, style } from '@vanilla-extract/css'; +import { style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -39,8 +39,4 @@ export const AutocompleteNotice = style([ { color: color.SurfaceVariant.OnContainer }, ]); -export const AutocompleteMenuItems = style({}); -globalStyle(`${AutocompleteMenuItems} button:first-child`, { - backgroundColor: color.SurfaceVariant.ContainerHover, -}); diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 545437924..73e36f6e0 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -1,4 +1,4 @@ -import { ReactNode } from 'react'; +import { ReactNode, useRef } from 'react'; import FocusTrap from 'focus-trap-react'; import { isKeyHotkey } from 'is-hotkey'; import { Header, Menu, Scroll, config } from 'folds'; @@ -15,6 +15,7 @@ type AutocompleteMenuProps = { }; export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) { const alive = useAlive(); + const itemsRef = useRef(null); const handleDeactivate = () => { if (alive()) { @@ -27,7 +28,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto itemsRef.current?.querySelector('button') ?? false, onPostDeactivate: handleDeactivate, returnFocusOnDeactivate: false, clickOutsideDeactivates: true, @@ -42,7 +43,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
From b6db65c33b8aa70fd9e14b04014f56c268b7eb0c Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:14:46 -0400 Subject: [PATCH 71/79] =?UTF-8?q?fix:=20virtual=20autocomplete=20selection?= =?UTF-8?q?=20=E2=80=94=20typing=20preserved,=20arrow=20keys=20navigate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../autocomplete/AutocompleteMenu.css.tsx | 10 +++- .../editor/autocomplete/AutocompleteMenu.tsx | 50 ++++++++++++++++--- src/app/features/room/RoomInput.tsx | 23 +++++++-- 3 files changed, 72 insertions(+), 11 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 149f10108..821fd65dd 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -39,4 +39,12 @@ export const AutocompleteNotice = style([ { color: color.SurfaceVariant.OnContainer }, ]); +export const AutocompleteMenuItems = style({}); + +globalStyle(`${AutocompleteMenuItems} button[data-selected]`, { + backgroundColor: color.SurfaceVariant.ContainerHover, + outline: `2px solid ${color.Primary.Main}`, + outlineOffset: -2, +}); + diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 73e36f6e0..ef30e4971 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -1,6 +1,5 @@ -import { ReactNode, useRef } from 'react'; +import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { isKeyHotkey } from 'is-hotkey'; import { Header, Menu, Scroll, config } from 'folds'; import { preventScrollWithArrowKey, stopPropagation } from '$utils/keyboard'; @@ -8,6 +7,9 @@ import { useAlive } from '$hooks/useAlive'; import * as css from './AutocompleteMenu.css'; import { BaseAutocompleteMenu } from './BaseAutocompleteMenu'; +export const AUTOCOMPLETE_NAVIGATE_EVENT = 'autocomplete-navigate'; +export type AutocompleteNavigateDetail = { direction: 1 | -1 }; + type AutocompleteMenuProps = { requestClose: () => void; headerContent: ReactNode; @@ -16,6 +18,8 @@ type AutocompleteMenuProps = { export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) { const alive = useAlive(); const itemsRef = useRef(null); + const [selectedIndex, setSelectedIndex] = useState(0); + const prevButtonCountRef = useRef(-1); const handleDeactivate = () => { if (alive()) { @@ -24,17 +28,51 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto } }; + // Sync data-selected to DOM; reset to index 0 when the item list changes + useLayoutEffect(() => { + const buttons = Array.from( + itemsRef.current?.querySelectorAll('button') ?? [] + ); + const count = buttons.length; + + let idx = selectedIndex; + if (count !== prevButtonCountRef.current) { + prevButtonCountRef.current = count; + idx = 0; + if (selectedIndex !== 0) setSelectedIndex(0); + } + + const safeIdx = Math.max(0, Math.min(idx, count - 1)); + buttons.forEach((btn, i) => { + if (i === safeIdx) btn.dataset.selected = 'true'; + else delete btn.dataset.selected; + }); + }); + + // Listen for navigation events dispatched by the editor key handler + useEffect(() => { + const container = itemsRef.current?.closest('[data-autocomplete-menu]'); + if (!container) return; + const handler = (e: Event) => { + const { direction } = (e as CustomEvent).detail; + setSelectedIndex((prev) => { + const buttons = itemsRef.current?.querySelectorAll('button') ?? []; + return Math.max(0, Math.min(prev + direction, buttons.length - 1)); + }); + }; + container.addEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler); + return () => container.removeEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler); + }, []); + return ( itemsRef.current?.querySelector('button') ?? false, + initialFocus: false, onPostDeactivate: handleDeactivate, returnFocusOnDeactivate: false, clickOutsideDeactivates: true, allowOutsideClick: true, - isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt), - isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt), escapeDeactivates: stopPropagation, }} > @@ -43,7 +81,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index c55f0e321..193f48c28 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -742,16 +742,31 @@ export const RoomInput = forwardRef( const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { + if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) { + evt.preventDefault(); + document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }) + ); + return; + } + if (autocompleteQuery && isKeyHotkey('arrowup', evt)) { + evt.preventDefault(); + document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) + ); + return; + } if ( (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) && !isComposing(evt) ) { evt.preventDefault(); if (autocompleteQuery) { - const firstItem = document.querySelector( - '[data-autocomplete-menu] button' - ); - firstItem?.click(); + const selectedItem = + document.querySelector( + '[data-autocomplete-menu] button[data-selected]' + ) ?? document.querySelector('[data-autocomplete-menu] button'); + selectedItem?.click(); return; } submit().catch((error) => { From d33776869331cd478766e1f6a2d20d4383a3767f Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:27:08 -0400 Subject: [PATCH 72/79] Update quick-issues-batch-1.md to remove closed issues Removed closed issue references from the changeset. --- .changeset/quick-issues-batch-1.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md index 783ae7843..38065fca3 100644 --- a/.changeset/quick-issues-batch-1.md +++ b/.changeset/quick-issues-batch-1.md @@ -15,5 +15,3 @@ Fix several small UI/UX issues: - **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags - **#120**: Video messages: volume is persisted across page loads via `localStorage` - **#168**: Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon only changes for mentions/keywords, not plain unreads - -Closes #2, #44, #45, #52, #66, #67, #79, #35, #69, #103, #120, #168 From d7ede9532cdfaab63a1b98e9a7ee57d604670647 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:30:21 -0400 Subject: [PATCH 73/79] fix: resolve lint/format errors in autocomplete virtual selection --- .changeset/quick-issues-batch-1.md | 2 +- .../editor/autocomplete/AutocompleteMenu.css.tsx | 4 +--- .../editor/autocomplete/AutocompleteMenu.tsx | 13 ++++++++----- src/app/features/room/RoomInput.tsx | 14 ++++++++------ 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md index 38065fca3..3a0a5ab5c 100644 --- a/.changeset/quick-issues-batch-1.md +++ b/.changeset/quick-issues-batch-1.md @@ -10,7 +10,7 @@ Fix several small UI/UX issues: - **#52**: Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard setting on mobile - **#66**: Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow - **#67**: Support `matrixToBaseUrl` in `config.json` to override the default matrix.to link base -- **#79/#35**: Autocomplete: pressing Enter now selects the top item instead of sending the message +- **#79/#35**: Autocomplete: pressing Enter now selects the highlighted item instead of sending the message; the first item is highlighted on open and Arrow Up/Down navigate the list while keeping typing focus in the editor - **#69**: Autocomplete: focus returns to the message editor after completing a mention or emoji - **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags - **#120**: Video messages: volume is persisted across page loads via `localStorage` diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 821fd65dd..fb36858cf 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -41,10 +41,8 @@ export const AutocompleteNotice = style([ export const AutocompleteMenuItems = style({}); -globalStyle(`${AutocompleteMenuItems} button[data-selected]`, { +globalStyle(`${AutocompleteMenuItems} button[data-selected='true']`, { backgroundColor: color.SurfaceVariant.ContainerHover, outline: `2px solid ${color.Primary.Main}`, outlineOffset: -2, }); - - diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index ef30e4971..0b82001b5 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -44,15 +44,14 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto const safeIdx = Math.max(0, Math.min(idx, count - 1)); buttons.forEach((btn, i) => { - if (i === safeIdx) btn.dataset.selected = 'true'; - else delete btn.dataset.selected; + btn.setAttribute('data-selected', String(i === safeIdx)); }); - }); + }, [selectedIndex]); // Listen for navigation events dispatched by the editor key handler useEffect(() => { const container = itemsRef.current?.closest('[data-autocomplete-menu]'); - if (!container) return; + if (!container) return undefined; const handler = (e: Event) => { const { direction } = (e as CustomEvent).detail; setSelectedIndex((prev) => { @@ -81,7 +80,11 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 193f48c28..1be4b84f7 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -744,16 +744,18 @@ export const RoomInput = forwardRef( (evt) => { if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) { evt.preventDefault(); - document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( - new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }) - ); + document + .querySelector('[data-autocomplete-menu]') + ?.dispatchEvent(new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } })); return; } if (autocompleteQuery && isKeyHotkey('arrowup', evt)) { evt.preventDefault(); - document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( - new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) - ); + document + .querySelector('[data-autocomplete-menu]') + ?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) + ); return; } if ( From 1a4af27d4910b7801f315b2d79c8ef4d4a771308 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:51:22 -0400 Subject: [PATCH 74/79] fix: persist volume for audio+video; split changesets; revert matrix.to (#120) --- .changeset/fix-account-signout-confirm.md | 7 ++++++ .changeset/fix-autocomplete-selection.md | 7 ++++++ .changeset/fix-cancel-add-account.md | 7 ++++++ .changeset/fix-editor-autocapitalize.md | 7 ++++++ .changeset/fix-favicon-mentions-only.md | 7 ++++++ .changeset/fix-media-volume-persist.md | 7 ++++++ .changeset/fix-reduced-motion-animation.md | 7 ++++++ .changeset/fix-server-picker-ios-autofill.md | 7 ++++++ .changeset/fix-theme-color-meta.md | 7 ++++++ .changeset/quick-issues-batch-1.md | 17 ------------- src/app/components/media/Video.tsx | 4 ++-- .../message/content/AudioContent.tsx | 18 +++++++++++++- src/app/hooks/useClientConfig.ts | 2 -- src/app/pages/App.tsx | 24 ++++++++----------- src/app/plugins/matrix-to.ts | 10 +------- 15 files changed, 93 insertions(+), 45 deletions(-) create mode 100644 .changeset/fix-account-signout-confirm.md create mode 100644 .changeset/fix-autocomplete-selection.md create mode 100644 .changeset/fix-cancel-add-account.md create mode 100644 .changeset/fix-editor-autocapitalize.md create mode 100644 .changeset/fix-favicon-mentions-only.md create mode 100644 .changeset/fix-media-volume-persist.md create mode 100644 .changeset/fix-reduced-motion-animation.md create mode 100644 .changeset/fix-server-picker-ios-autofill.md create mode 100644 .changeset/fix-theme-color-meta.md delete mode 100644 .changeset/quick-issues-batch-1.md diff --git a/.changeset/fix-account-signout-confirm.md b/.changeset/fix-account-signout-confirm.md new file mode 100644 index 000000000..52a09d178 --- /dev/null +++ b/.changeset/fix-account-signout-confirm.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Account switcher: show a confirmation dialog before signing out of an account. + +Closes #44 diff --git a/.changeset/fix-autocomplete-selection.md b/.changeset/fix-autocomplete-selection.md new file mode 100644 index 000000000..ffacbd70c --- /dev/null +++ b/.changeset/fix-autocomplete-selection.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Autocomplete: pressing Enter now selects the highlighted item instead of sending the message. The first item is highlighted on open and ArrowUp/Down navigate the list while keeping typing focus in the editor. Focus returns to the message editor after completing a mention or emoji. + +Closes #35, #69, #79 diff --git a/.changeset/fix-cancel-add-account.md b/.changeset/fix-cancel-add-account.md new file mode 100644 index 000000000..ef027e098 --- /dev/null +++ b/.changeset/fix-cancel-add-account.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow. + +Closes #66 diff --git a/.changeset/fix-editor-autocapitalize.md b/.changeset/fix-editor-autocapitalize.md new file mode 100644 index 000000000..b122b49ca --- /dev/null +++ b/.changeset/fix-editor-autocapitalize.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard capitalisation setting on mobile. + +Closes #52 diff --git a/.changeset/fix-favicon-mentions-only.md b/.changeset/fix-favicon-mentions-only.md new file mode 100644 index 000000000..ba8ce5d93 --- /dev/null +++ b/.changeset/fix-favicon-mentions-only.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon badge only changes for mentions/keywords, not plain unreads. + +Closes #168 diff --git a/.changeset/fix-media-volume-persist.md b/.changeset/fix-media-volume-persist.md new file mode 100644 index 000000000..00790b8d4 --- /dev/null +++ b/.changeset/fix-media-volume-persist.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Video and audio messages: volume level is now persisted across page loads via `localStorage` and shared between all media players. + +Closes #120 diff --git a/.changeset/fix-reduced-motion-animation.md b/.changeset/fix-reduced-motion-animation.md new file mode 100644 index 000000000..804c456cb --- /dev/null +++ b/.changeset/fix-reduced-motion-animation.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed. + +Closes #2 diff --git a/.changeset/fix-server-picker-ios-autofill.md b/.changeset/fix-server-picker-ios-autofill.md new file mode 100644 index 000000000..52f8df4c2 --- /dev/null +++ b/.changeset/fix-server-picker-ios-autofill.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Server picker: prevent iOS from restoring the old server name while the user is actively editing the input. + +Closes #45 diff --git a/.changeset/fix-theme-color-meta.md b/.changeset/fix-theme-color-meta.md new file mode 100644 index 000000000..ce3160794 --- /dev/null +++ b/.changeset/fix-theme-color-meta.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Browser tab/PWA: use the correct light (`#ffffff`) and dark (`#1b1a21`) theme-color values via `media` attribute on the meta tags. + +Closes #103 diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md deleted file mode 100644 index 3a0a5ab5c..000000000 --- a/.changeset/quick-issues-batch-1.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -default: patch ---- - -Fix several small UI/UX issues: - -- **#2**: Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed -- **#44**: Account switcher: show a confirmation dialog before signing out of an account -- **#45**: Server picker: prevent iOS from restoring the old server name while the user is actively editing the input -- **#52**: Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard setting on mobile -- **#66**: Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow -- **#67**: Support `matrixToBaseUrl` in `config.json` to override the default matrix.to link base -- **#79/#35**: Autocomplete: pressing Enter now selects the highlighted item instead of sending the message; the first item is highlighted on open and Arrow Up/Down navigate the list while keeping typing focus in the editor -- **#69**: Autocomplete: focus returns to the message editor after completing a mention or emoji -- **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags -- **#120**: Video messages: volume is persisted across page loads via `localStorage` -- **#168**: Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon only changes for mentions/keywords, not plain unreads diff --git a/src/app/components/media/Video.tsx b/src/app/components/media/Video.tsx index a2a371df9..6c08aca8f 100644 --- a/src/app/components/media/Video.tsx +++ b/src/app/components/media/Video.tsx @@ -9,7 +9,7 @@ export const Video = forwardRef { - localStorage.setItem(VIDEO_VOLUME_KEY, String((e.target as HTMLVideoElement).volume)); + localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLVideoElement).volume)); onVolumeChange?.(e); }} /> diff --git a/src/app/components/message/content/AudioContent.tsx b/src/app/components/message/content/AudioContent.tsx index 6ef9349ba..1153ffae7 100644 --- a/src/app/components/message/content/AudioContent.tsx +++ b/src/app/components/message/content/AudioContent.tsx @@ -18,6 +18,7 @@ import { useThrottle } from '$hooks/useThrottle'; import { secondsToMinutesAndSeconds } from '$utils/common'; import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { MEDIA_VOLUME_KEY } from '$components/media'; const PLAY_TIME_THROTTLE_OPS = { wait: 500, @@ -60,6 +61,14 @@ export function AudioContent({ const audioRef = useRef(null); + useEffect(() => { + const stored = localStorage.getItem(MEDIA_VOLUME_KEY); + if (audioRef.current && stored !== null) { + const parsed = parseFloat(stored); + if (!Number.isNaN(parsed)) audioRef.current.volume = parsed; + } + }, []); + const [currentTime, setCurrentTime] = useState(0); // duration in seconds. (NOTE: info.duration is in milliseconds) const infoDuration = info.duration ?? 0; @@ -197,7 +206,14 @@ export function AudioContent({ ), children: ( -