From b1e5755c1401a895bcafb25b4a84df1f22076bcc Mon Sep 17 00:00:00 2001 From: jasonlaguidice <19523621+jasonlaguidice@users.noreply.github.com> Date: Wed, 4 Mar 2026 21:57:55 -0800 Subject: [PATCH 001/124] Add tap & hold for scheduled send instead of chevron for isMobileOrTablet() --- src/app/features/room/RoomInput.tsx | 33 +++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index e8e71606..83d5b9e6 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -210,6 +210,8 @@ export const RoomInput = forwardRef( selectedFiles.map((f) => f.file) ); const uploadBoardHandlers = useRef(); + const longPressTimer = useRef | null>(null); + const isLongPress = useRef(false); const imagePackRooms: Room[] = useImagePackRooms(roomId, roomToParents); @@ -943,8 +945,35 @@ export const RoomInput = forwardRef( /> { + if (isLongPress.current) { + isLongPress.current = false; + return; + } + submit(); + }} onMouseDown={(e: MouseEvent) => e.preventDefault()} + onPointerDown={() => { + isLongPress.current = false; + if (mobileOrTablet() && delayedEventsSupported) { + longPressTimer.current = setTimeout(() => { + isLongPress.current = true; + setShowSchedulePicker(true); + }, 1000); + } + }} + onPointerUp={() => { + if (longPressTimer.current !== null) { + clearTimeout(longPressTimer.current); + longPressTimer.current = null; + } + }} + onPointerCancel={() => { + if (longPressTimer.current !== null) { + clearTimeout(longPressTimer.current); + longPressTimer.current = null; + } + }} variant={scheduledTime ? 'Primary' : 'SurfaceVariant'} size="300" radii="0" @@ -952,7 +981,7 @@ export const RoomInput = forwardRef( > - {delayedEventsSupported && ( + {delayedEventsSupported && !mobileOrTablet() && ( ) => { setScheduleMenuAnchor(evt.currentTarget.getBoundingClientRect()); From 6c90547ce5ccd53ba8e9dcbff9173bd31cb319ee Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Thu, 5 Mar 2026 10:29:51 +0200 Subject: [PATCH 002/124] added basic plaintext image description adjacent to the text input --- .../upload-card/UploadCardRenderer.tsx | 16 ++++++++- src/app/features/room/RoomInput.tsx | 33 +++++++++++++++++-- src/app/features/room/msgContent.ts | 6 +++- src/app/state/room/roomInputDrafts.ts | 1 + 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 8ff54ff0..fabe8772 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -98,6 +98,7 @@ type UploadCardRendererProps = { isEncrypted?: boolean; fileItem: TUploadItem; setMetadata: (fileItem: TUploadItem, metadata: TUploadMetadata) => void; + setDescription: (fileContent: TUploadContent) => void; onRemove: (file: TUploadContent) => void; onComplete?: (upload: UploadSuccess) => void; }; @@ -105,6 +106,7 @@ export function UploadCardRenderer({ isEncrypted, fileItem, setMetadata, + setDescription, onRemove, onComplete, }: UploadCardRendererProps) { @@ -130,13 +132,15 @@ export function UploadCardRenderer({ cancelUpload(); onRemove(file); }; + const handleDescription = () => { + setDescription(file); + }; useEffect(() => { if (upload.status === UploadStatus.Success) { onComplete?.(upload); } }, [upload, onComplete]); - return ( Retry )} + + + + ( const [uploadBoard, setUploadBoard] = useState(true); const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(roomId)); + const [describedFile, setDescribedFile] = useState(undefined); const uploadFamilyObserverAtom = createUploadFamilyObserverAtom( roomUploadAtomFamily, selectedFiles.map((f) => f.file) @@ -214,6 +215,7 @@ export const RoomInput = forwardRef( metadata: { markedAsSpoiler: false, }, + body: 'aaa', }) ); } else { @@ -225,6 +227,7 @@ export const RoomInput = forwardRef( metadata: { markedAsSpoiler: false, }, + body: 'aaa', }) ); } @@ -303,7 +306,12 @@ export const RoomInput = forwardRef( }, [setSelectedFiles] ); - + const handleDescription = useCallback( + (fileItem: TUploadContent) => { + setDescribedFile(fileItem); + }, + [setDescribedFile] + ); const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { const uploads = Array.isArray(upload) ? upload : [upload]; @@ -331,6 +339,14 @@ export const RoomInput = forwardRef( const fileItem = selectedFiles.find((f) => f.file === upload.file); if (!fileItem) throw new Error('Broken upload'); + if (fileItem.file === describedFile) { + fileItem.body = plaintext; + resetEditor(editor); + resetEditorHistory(editor); + setInputKey((prev) => prev + 1); + sendTypingStatus(false); + setDescribedFile(undefined); + } if (fileItem.file.type.startsWith('image')) { return getImageMsgContent(mx, fileItem, upload.mxc); } @@ -364,6 +380,7 @@ export const RoomInput = forwardRef( const submit = useCallback(async () => { uploadBoardHandlers.current?.handleSend(); + if (describedFile !== undefined) return; const commandName = getBeginCommand(editor); let plainText = toPlainText(editor.children, isMarkdown).trim(); let customHtml = trimCustomHtml( @@ -436,13 +453,24 @@ export const RoomInput = forwardRef( resetEditorHistory(editor); setInputKey((prev) => prev + 1); sendTypingStatus(false); + setDescribedFile(undefined); try { await mx.sendMessage(roomId, content as any); } catch (error) { log.error('failed to send message', { roomId }, error); } - }, [mx, roomId, editor, replyDraft, sendTypingStatus, setReplyDraft, isMarkdown, commands]); + }, [ + mx, + roomId, + editor, + replyDraft, + describedFile, + sendTypingStatus, + setReplyDraft, + isMarkdown, + commands, + ]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -546,6 +574,7 @@ export const RoomInput = forwardRef( fileItem={fileItem} setMetadata={handleFileMetadata} onRemove={handleRemoveUpload} + setDescription={handleDescription} /> ))} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index fa3b94cb..61b1306c 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -77,6 +77,7 @@ export const getImageMsgContent = async ( } else { content.url = mxc; } + if (item.body?.length && item.body.length > 0) content.body = item.body; return content; }; @@ -126,6 +127,7 @@ export const getVideoMsgContent = async ( } else { content.url = mxc; } + if (item.body?.length && item.body.length > 0) content.body = item.body; return content; }; @@ -148,6 +150,7 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent => } else { content.url = mxc; } + if (item.body?.length && item.body.length > 0) content.body = item.body; return content; }; @@ -155,8 +158,8 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { const { file, encInfo } = item; const content: IContent = { msgtype: MsgType.File, - body: file.name, filename: file.name, + body: file.name, info: { mimetype: file.type, size: file.size, @@ -170,5 +173,6 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { } else { content.url = mxc; } + if (item.body?.length && item.body.length > 0) content.body = item.body; return content; }; diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index f5cdd84a..abb93d1d 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -16,6 +16,7 @@ export type TUploadItem = { originalFile: TUploadContent; metadata: TUploadMetadata; encInfo: EncryptedAttachmentInfo | undefined; + body?: string; }; export type TUploadListAtom = ReturnType>; From b82819786e1886f1da800a165245bf4eb1d9fc98 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 16:47:20 -0600 Subject: [PATCH 003/124] Remove package-lock.json from versioned files --- knope.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knope.toml b/knope.toml index d0d8bfc8..213ba414 100644 --- a/knope.toml +++ b/knope.toml @@ -1,6 +1,6 @@ [packages.sable] -versioned_files = ["package.json", "package-lock.json"] +versioned_files = ["package.json"] changelog = "CHANGELOG.md" extra_changelog_sections = [ { name = "Documentation", types = ["docs"] }, From 62502eae4bfd893b7671f226d51295755ecea96a Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 17:26:39 -0600 Subject: [PATCH 004/124] update update tag to patch --- .changeset/pr149_text_quick_react.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/pr149_text_quick_react.md b/.changeset/pr149_text_quick_react.md index 72b78270..e1dae4ad 100644 --- a/.changeset/pr149_text_quick_react.md +++ b/.changeset/pr149_text_quick_react.md @@ -1,5 +1,5 @@ --- -sable: minor +sable: patch --- Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#` From 927db3b6a63f995f346a9b9441ad70a8d9ff7eb3 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 15:11:42 -0500 Subject: [PATCH 005/124] perf(emoji-board): defer image pack cache reads to avoid blocking first render --- src/app/hooks/useImagePacks.ts | 111 +++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 39 deletions(-) diff --git a/src/app/hooks/useImagePacks.ts b/src/app/hooks/useImagePacks.ts index 39154328..7146966b 100644 --- a/src/app/hooks/useImagePacks.ts +++ b/src/app/hooks/useImagePacks.ts @@ -55,12 +55,18 @@ const imagePackListEqual = (a: ImagePack[], b: ImagePack[]): boolean => { export const useUserImagePack = (): ImagePack | undefined => { const mx = useMatrixClient(); - const [userPack, setUserPack] = useState(() => { - const live = getUserImagePack(mx); - if (live) return live; - const userId = mx.getUserId(); - return userId ? readCachedPack(userId, userPackScope()) : undefined; - }); + const [userPack, setUserPack] = useState(() => getUserImagePack(mx)); + + // Async: seed from cache after first render if no live data is available yet + useEffect(() => { + setUserPack((current) => { + if (current) return current; + const userId = mx.getUserId(); + if (!userId) return current; + return readCachedPack(userId, userPackScope()) ?? current; + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); useEffect(() => { const userId = mx.getUserId(); @@ -87,12 +93,19 @@ export const useUserImagePack = (): ImagePack | undefined => { export const useGlobalImagePacks = (): ImagePack[] => { const mx = useMatrixClient(); - const [globalPacks, setGlobalPacks] = useState(() => { - const live = getGlobalImagePacks(mx); - if (live.length > 0) return live; - const userId = mx.getUserId(); - return userId ? readCachedPacks(userId, globalPacksScope()) : []; - }); + const [globalPacks, setGlobalPacks] = useState(() => getGlobalImagePacks(mx)); + + // Async: seed from cache after first render if no live data is available yet + useEffect(() => { + setGlobalPacks((current) => { + if (current.length > 0) return current; + const userId = mx.getUserId(); + if (!userId) return current; + const cached = readCachedPacks(userId, globalPacksScope()); + return cached.length > 0 ? cached : current; + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); useEffect(() => { const userId = mx.getUserId(); @@ -142,16 +155,24 @@ export const useGlobalImagePacks = (): ImagePack[] => { export const useRoomImagePack = (room: Room, stateKey: string): ImagePack | undefined => { const mx = useMatrixClient(); - const [roomPack, setRoomPack] = useState(() => { - const live = getRoomImagePack(room, stateKey); - if (live) return live; - const userId = mx.getUserId(); - if (!userId) return undefined; - // Find a matching cached pack by roomId + stateKey - return readCachedPacks(userId, roomPacksScope(room.roomId)).find( - (p) => p.address?.stateKey === stateKey - ); - }); + const [roomPack, setRoomPack] = useState(() => + getRoomImagePack(room, stateKey) + ); + + // Async: seed from cache after first render if no live data is available yet + useEffect(() => { + setRoomPack((current) => { + if (current) return current; + const userId = mx.getUserId(); + if (!userId) return current; + return ( + readCachedPacks(userId, roomPacksScope(room.roomId)).find( + (p) => p.address?.stateKey === stateKey + ) ?? current + ); + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); useEffect(() => { const userId = mx.getUserId(); @@ -185,12 +206,19 @@ export const useRoomImagePack = (room: Room, stateKey: string): ImagePack | unde export const useRoomImagePacks = (room: Room): ImagePack[] => { const mx = useMatrixClient(); - const [roomPacks, setRoomPacks] = useState(() => { - const live = getRoomImagePacks(room); - if (live.length > 0) return live; - const userId = mx.getUserId(); - return userId ? readCachedPacks(userId, roomPacksScope(room.roomId)) : []; - }); + const [roomPacks, setRoomPacks] = useState(() => getRoomImagePacks(room)); + + // Async: seed from cache after first render if no live data is available yet + useEffect(() => { + setRoomPacks((current) => { + if (current.length > 0) return current; + const userId = mx.getUserId(); + if (!userId) return current; + const cached = readCachedPacks(userId, roomPacksScope(room.roomId)); + return cached.length > 0 ? cached : current; + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); useEffect(() => { const userId = mx.getUserId(); @@ -220,18 +248,23 @@ export const useRoomImagePacks = (room: Room): ImagePack[] => { export const useRoomsImagePacks = (rooms: Room[]) => { const mx = useMatrixClient(); - const [roomPacks, setRoomPacks] = useState(() => { - const live = rooms.flatMap(getRoomImagePacks); - if (live.length > 0) return live; - const userId = mx.getUserId(); - if (!userId) return []; - // Seed from cache for each room that has no live packs - return rooms.flatMap((room) => { - const livePacks = getRoomImagePacks(room); - if (livePacks.length > 0) return livePacks; - return readCachedPacks(userId, roomPacksScope(room.roomId)); + const [roomPacks, setRoomPacks] = useState(() => rooms.flatMap(getRoomImagePacks)); + + // Async: seed from cache after first render if no live data is available yet + useEffect(() => { + setRoomPacks((current) => { + if (current.length > 0) return current; + const userId = mx.getUserId(); + if (!userId) return current; + const cached = rooms.flatMap((room) => { + const livePacks = getRoomImagePacks(room); + if (livePacks.length > 0) return livePacks; + return readCachedPacks(userId, roomPacksScope(room.roomId)); + }); + return cached.length > 0 ? cached : current; }); - }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); useEffect(() => { const userId = mx.getUserId(); From 6ec739a89571a4e2239d3f0c09d9088b0bf7efc8 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 15:11:02 -0500 Subject: [PATCH 006/124] fix(timeline): sliding sync rendering, atBottom, phantom unread, pagination spinner --- src/app/features/room/RoomTimeline.tsx | 119 +++++++++++++++--- src/app/features/settings/general/General.tsx | 10 +- 2 files changed, 109 insertions(+), 20 deletions(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index fdd4a5a1..5e448993 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -46,6 +46,7 @@ import { Icons, Line, Scroll, + Spinner, Text, toRem, } from 'folds'; @@ -265,6 +266,8 @@ type RoomTimelineProps = { const PAGINATION_LIMIT = 60; const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000; +type PaginationStatus = 'idle' | 'loading' | 'error'; + type Timeline = { linkedTimelines: EventTimeline[]; range: ItemRange; @@ -337,8 +340,10 @@ const useTimelinePagination = ( const timelineRef = useRef(timeline); timelineRef.current = timeline; const alive = useAlive(); + const [backwardStatus, setBackwardStatus] = useState('idle'); + const [forwardStatus, setForwardStatus] = useState('idle'); - return useMemo(() => { + const paginate = useMemo(() => { let fetching = false; const recalibratePagination = ( @@ -390,6 +395,9 @@ const useTimelinePagination = ( } fetching = true; + if (alive()) { + (backwards ? setBackwardStatus : setForwardStatus)('loading'); + } try { const [err] = await to( mx.paginateEventTimeline(timelineToPaginate, { @@ -398,7 +406,9 @@ const useTimelinePagination = ( }) ); if (err) { - // TODO: handle pagination error. + if (alive()) { + (backwards ? setBackwardStatus : setForwardStatus)('error'); + } return; } const fetchedTimeline = @@ -415,16 +425,24 @@ const useTimelinePagination = ( if (alive()) { recalibratePagination(lTimelines, timelinesEventsCount, backwards); + (backwards ? setBackwardStatus : setForwardStatus)('idle'); } } finally { fetching = false; } }; - }, [mx, alive, setTimeline, limit]); + }, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]); + + return { paginate, backwardStatus, forwardStatus }; }; const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => { useEffect(() => { + // Capture the live timeline and registration time. Events appended to the + // live timeline AFTER this point can be genuinely new even when + // liveEvent=false (older sliding sync proxies that omit num_live). + const liveTimeline = getLiveTimeline(room); + const registeredAt = Date.now(); const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = ( mEvent: MatrixEvent, eventRoom: Room | undefined, @@ -432,7 +450,19 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) removed: boolean, data: IRoomTimelineData ) => { - if (eventRoom?.roomId !== room.roomId || !data.liveEvent) return; + if (eventRoom?.roomId !== room.roomId) return; + // Standard sync: liveEvent=true for real-time events. + // Sliding sync fallback: liveEvent=false on buggy proxies. Treat events + // on the live timeline as new only when their server timestamp is within + // 60 s before registration — this filters out initial-sync backfill that + // happens to fire after mount while excluding genuine reconnect messages. + const isLive = + data.liveEvent || + (!toStartOfTimeline && + !removed && + data.timeline === liveTimeline && + mEvent.getTs() >= registeredAt - 60_000); + if (!isLive) return; onArrive(mEvent); }; const handleRedaction: RoomEventHandlerMap[RoomEvent.Redaction] = ( @@ -645,12 +675,11 @@ export function RoomTimeline({ const atLiveEndRef = useRef(liveTimelineLinked && rangeAtEnd); atLiveEndRef.current = liveTimelineLinked && rangeAtEnd; - const handleTimelinePagination = useTimelinePagination( - mx, - timeline, - setTimeline, - PAGINATION_LIMIT - ); + const { + paginate: handleTimelinePagination, + backwardStatus, + forwardStatus, + } = useTimelinePagination(mx, timeline, setTimeline, PAGINATION_LIMIT); const getScrollElement = useCallback(() => scrollRef.current, []); @@ -878,9 +907,11 @@ export function RoomTimeline({ if (!target) return; const targetEntry = getIntersectionObserverEntry(target, entries); if (targetEntry) debounceSetAtBottom(targetEntry); - if (targetEntry?.isIntersecting && atLiveEndRef.current) { + if (targetEntry?.isIntersecting) { + // Track scroll position independently of atLiveEndRef so that atBottom + // is always accurate. tryAutoMarkAsRead still requires atLiveEndRef. setAtBottom(true); - if (document.hasFocus()) { + if (atLiveEndRef.current && document.hasFocus()) { tryAutoMarkAsRead(); } } @@ -1941,8 +1972,35 @@ export function RoomTimeline({ }; let backPaginationJSX: ReactNode | undefined; - if (canPaginateBack || !rangeAtStart) { - if (timelineItems.length === 0) { + if (canPaginateBack || !rangeAtStart || backwardStatus !== 'idle') { + if (backwardStatus === 'error') { + backPaginationJSX = ( + + + Failed to load history. + + handleTimelinePagination(true)} + > + Retry + + + ); + } else if (backwardStatus === 'loading' && timelineItems.length > 0) { + backPaginationJSX = ( + + + + ); + } else if (timelineItems.length === 0) { backPaginationJSX = messageLayout === MessageLayout.Compact ? ( <> @@ -1981,8 +2039,35 @@ export function RoomTimeline({ } let frontPaginationJSX: ReactNode | undefined; - if (!liveTimelineLinked || !rangeAtEnd) { - if (timelineItems.length === 0) { + if (!liveTimelineLinked || !rangeAtEnd || forwardStatus !== 'idle') { + if (forwardStatus === 'error') { + frontPaginationJSX = ( + + + Failed to load messages. + + handleTimelinePagination(false)} + > + Retry + + + ); + } else if (forwardStatus === 'loading' && timelineItems.length > 0) { + frontPaginationJSX = ( + + + + ); + } else if (timelineItems.length === 0) { frontPaginationJSX = messageLayout === MessageLayout.Compact ? ( <> @@ -2071,7 +2156,7 @@ export function RoomTimeline({ - {!atBottom && ( + {(!atBottom || !(liveTimelineLinked && rangeAtEnd)) && ( Enable Sliding Sync for this current login/session. Requires server support and - admin configuration. May cause issues, use with caution.{' '} + admin configuration.{' '} - More info + More info/Documentation + + .{' '} + + Known issues (Sable GitHub) . From 88324e2419424f1a8c34e15c9a08587eb6eaaf3e Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 15:11:47 -0500 Subject: [PATCH 007/124] style(message): use Chip for failed-send retry and delete buttons --- src/app/features/room/message/Message.tsx | 16 +++++++++------- src/app/features/room/message/styles.css.ts | 10 ---------- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index b9f81d54..4558a042 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -1,6 +1,7 @@ import { Avatar, Box, + Chip, Icon, IconButton, Icons, @@ -520,18 +521,19 @@ function MessageInternal( Failed to send. {canResend && ( - + + Retry + )} {canDeleteFailedSend && ( - + Delete + )} )} diff --git a/src/app/features/room/message/styles.css.ts b/src/app/features/room/message/styles.css.ts index 49ccfb92..f8946e18 100644 --- a/src/app/features/room/message/styles.css.ts +++ b/src/app/features/room/message/styles.css.ts @@ -70,13 +70,3 @@ export const SendStatusRow = style({ gap: config.space.S200, marginTop: config.space.S100, }); - -export const SendStatusButton = style([ - DefaultReset, - { - color: 'inherit', - cursor: 'pointer', - textDecoration: 'underline', - fontSize: toRem(12), - }, -]); From fe37ae23f32745906db9c213a18eeeb1a0ed50ba Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 19:11:11 -0500 Subject: [PATCH 008/124] feat(settings): badge count DMs-only toggle and highlight-only app badge option --- src/app/components/unread-badge/UnreadBadge.tsx | 9 +++++++-- src/app/features/room-nav/RoomNavItem.tsx | 6 +++++- src/app/features/settings/cosmetics/Themes.tsx | 10 ++++++++++ src/app/pages/client/sidebar/DirectTab.tsx | 1 + src/app/state/settings.ts | 2 ++ 5 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/app/components/unread-badge/UnreadBadge.tsx b/src/app/components/unread-badge/UnreadBadge.tsx index 49b8d664..4648ae05 100644 --- a/src/app/components/unread-badge/UnreadBadge.tsx +++ b/src/app/components/unread-badge/UnreadBadge.tsx @@ -7,6 +7,8 @@ import { settingsAtom } from '$state/settings'; type UnreadBadgeProps = { highlight?: boolean; count: number; + /** Whether this badge belongs to a DM room. Used with the badgeCountDMsOnly setting. */ + dm?: boolean; }; const styles: CSSProperties = { minWidth: toRem(16), @@ -19,11 +21,14 @@ export function UnreadBadgeCenter({ children }: { children: ReactNode }) { ); } -export function UnreadBadge({ highlight, count }: UnreadBadgeProps) { +export function UnreadBadge({ highlight, count, dm }: UnreadBadgeProps) { const [showUnreadCounts] = useSetting(settingsAtom, 'showUnreadCounts'); + const [badgeCountDMsOnly] = useSetting(settingsAtom, 'badgeCountDMsOnly'); const [showPingCounts] = useSetting(settingsAtom, 'showPingCounts'); - const showNumber = count > 0 && (showUnreadCounts || (highlight && showPingCounts)); + // Show count when: (showUnreadCounts OR highlight+showPingCounts) AND (not DM-only mode OR this is a DM) + const showNumber = + count > 0 && (showUnreadCounts || (highlight && showPingCounts)) && (!badgeCountDMsOnly || dm); return ( - 0} count={unreadCount} /> + 0} + count={unreadCount} + dm={direct} + /> )} {!optionsVisible && notificationMode !== RoomNotificationMode.Unset && ( diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 56d73c24..714bbd57 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -328,6 +328,7 @@ function PageZoomInput() { export function Appearance() { const [twitterEmoji, setTwitterEmoji] = useSetting(settingsAtom, 'twitterEmoji'); const [showUnreadCounts, setShowUnreadCounts] = useSetting(settingsAtom, 'showUnreadCounts'); + const [badgeCountDMsOnly, setBadgeCountDMsOnly] = useSetting(settingsAtom, 'badgeCountDMsOnly'); const [showPingCounts, setShowPingCounts] = useSetting(settingsAtom, 'showPingCounts'); return ( @@ -357,6 +358,15 @@ export function Appearance() { } /> + + + } + /> + 0} count={directUnread.highlight > 0 ? directUnread.highlight : directUnread.total} + dm /> )} diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index fab45528..cdbd95a5 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -72,6 +72,7 @@ export interface Settings { hideMembershipInReadOnly: boolean; useRightBubbles: boolean; showUnreadCounts: boolean; + badgeCountDMsOnly: boolean; showPingCounts: boolean; } @@ -129,6 +130,7 @@ const defaultSettings: Settings = { hideMembershipInReadOnly: true, useRightBubbles: false, showUnreadCounts: true, + badgeCountDMsOnly: false, showPingCounts: true, }; From e232be64d9c22258cb6bfb15050071816daf7665 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 15:10:57 -0500 Subject: [PATCH 009/124] fix(media): remove allowRedirects, add error fallbacks, apply useAuthentication in html parser --- src/app/components/message/Reaction.tsx | 77 ++++++++++++-------- src/app/plugins/react-custom-html-parser.tsx | 73 ++++++++++++++++++- src/app/utils/matrix.ts | 5 +- 3 files changed, 119 insertions(+), 36 deletions(-) diff --git a/src/app/components/message/Reaction.tsx b/src/app/components/message/Reaction.tsx index edc8640b..155de11f 100644 --- a/src/app/components/message/Reaction.tsx +++ b/src/app/components/message/Reaction.tsx @@ -1,4 +1,5 @@ -import { Box, Text, as } from 'folds'; +import { useState } from 'react'; +import { Box, Icon, Icons, Text, as } from 'folds'; import classNames from 'classnames'; import { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { getHexcodeForEmoji, getShortcodeFor } from '$plugins/emoji'; @@ -16,34 +17,52 @@ export const Reaction = as< reaction: string; useAuthentication?: boolean; } ->(({ className, mx, count, reaction, useAuthentication, ...props }, ref) => ( - - - {reaction.startsWith('mxc://') ? ( - {reaction} - ) : ( - - {reaction} - - )} - - - {count} - - -)); +>(({ className, mx, count, reaction, useAuthentication, ...props }, ref) => { + const [imgError, setImgError] = useState(false); + + return ( + + + {reaction.startsWith('mxc://') ? ( + (() => { + if (imgError) + return ( + // Image loaded but fetch failed — show a small warning icon so the + // reaction button still renders correctly and the user can see + // something went wrong rather than a browser broken-image icon. + + + + ); + return ( + {reaction} setImgError(true)} + /> + ); + })() + ) : ( + + {reaction} + + )} + + + {count} + + + ); +}); type ReactionTooltipMsgProps = { room: Room; diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 84abacf8..dc3bf484 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -3,6 +3,7 @@ import { ComponentPropsWithoutRef, lazy, ReactEventHandler, + ReactNode, Suspense, useMemo, useState, @@ -316,6 +317,20 @@ export function CodeBlock({ ); } +/** + * Thin wrapper around that gracefully swaps in a fallback node when the + * image fails to load (e.g. federation down, mxc URL unavailable). Avoids the + * silent browser broken-image icon showing up in message bodies. + */ +function FallbackImg({ + fallback, + ...props +}: ComponentPropsWithoutRef<'img'> & { fallback: ReactNode }) { + const [failed, setFailed] = useState(false); + if (failed) return <>{fallback}; + return setFailed(true)} />; +} + export const getReactCustomHtmlParser = ( mx: MatrixClient, roomId: string | undefined, @@ -501,8 +516,15 @@ export const getReactCustomHtmlParser = ( } if (name === 'img') { + // Guard: img without a src survives sanitisation (fix for crash #1731) + // but we can't convert it — skip rendering rather than passing + // undefined into mxcUrlToHttp where it would throw. + if (!props.src) return null; + const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication) ?? undefined; + // Non-mxc images were already converted to links by the sanitiser, + // but handle the edge case defensively here too. if (htmlSrc && !props.src.startsWith('mxc://')) { return ( @@ -511,7 +533,18 @@ export const getReactCustomHtmlParser = ( ); } - if (htmlSrc && 'data-mx-emoticon' in props) { + if ('data-mx-emoticon' in props) { + // When the mxc URL can't be resolved (e.g. federation unavailable), + // fall back to rendering the shortcode text so the message stays readable. + if (!htmlSrc) { + const label = props.alt || props.title || ''; + return ( + + {label ? `:${label}:` : ''} + + ); + } + const siblingCount = domNode.parent?.children.length ?? 0; // seperate style for bundled emojis @@ -519,11 +552,19 @@ export const getReactCustomHtmlParser = ( return ( - + {props.alt || props.title ? `:${props.alt || props.title}:` : '?'} + + } /> @@ -534,13 +575,37 @@ export const getReactCustomHtmlParser = ( return ( - + + {props.alt || props.title ? `:${props.alt || props.title}:` : '?'} + + } + /> ); } - if (htmlSrc) return ; + if (htmlSrc) + return ( + + {props.alt || '[media]'} + + } + /> + ); } } diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index 46d5e6ec..ea1a8514 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -293,8 +293,7 @@ export const mxcUrlToHttp = ( width?: number, height?: number, resizeMethod?: string, - allowDirectLinks?: boolean, - allowRedirects?: boolean + allowDirectLinks?: boolean ): string | null => mx.mxcUrlToHttp( mxcUrl.replace(/^["']|["']$/g, ''), @@ -302,7 +301,7 @@ export const mxcUrlToHttp = ( height, resizeMethod, allowDirectLinks, - allowRedirects, + undefined, useAuthentication ); From 6e667e284b249f034d43faabe03789a990266f44 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 15:10:02 -0500 Subject: [PATCH 010/124] fix(Reply,useRoomEvent): robust reply loading, E2EE support, blocked-user state --- src/app/components/message/Reply.tsx | 51 ++++++- .../message/content/FallbackContent.tsx | 7 + src/app/features/room/RoomInput.tsx | 21 +-- src/app/hooks/useRoomEvent.ts | 125 ++++++++++++++++-- 4 files changed, 181 insertions(+), 23 deletions(-) diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index b9e6408b..eddc13e2 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -1,6 +1,7 @@ -import { Box, Icon, Icons, Text, as, color, toRem } from 'folds'; +import { Box, Chip, Icon, Icons, Text, as, color, toRem } from 'folds'; import { EventTimelineSet, Room } from '$types/matrix-sdk'; import { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; import classNames from 'classnames'; import parse from 'html-react-parser'; import { useAtomValue } from 'jotai'; @@ -14,9 +15,16 @@ import { } from '$plugins/react-custom-html-parser'; import { useRoomEvent } from '$hooks/useRoomEvent'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; +import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { nicknamesAtom } from '$state/nicknames'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { MessageBadEncryptedContent, MessageDeletedContent, MessageFailedContent } from './content'; +import { + MessageBadEncryptedContent, + MessageBlockedContent, + MessageDeletedContent, + MessageFailedContent, +} from './content'; import * as css from './Reply.css'; import { LinePlaceholder } from './placeholder'; @@ -74,14 +82,19 @@ export const Reply = as<'div', ReplyProps>( [timelineSet, replyEventId] ); const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline); + const queryClient = useQueryClient(); const mx = useMatrixClient(); const { body, formatted_body: formattedBody, format } = replyEvent?.getContent() ?? {}; const sender = replyEvent?.getSender(); + const ignoredUsers = useIgnoredUsers(); + const isBlockedSender = !!sender && ignoredUsers.includes(sender); + const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); const nicknames = useAtomValue(nicknamesAtom); + const useAuthentication = useMediaAuthentication(); const fallbackBody = replyEvent?.isRedacted() ? ( @@ -90,6 +103,18 @@ export const Reply = as<'div', ReplyProps>( ); const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted'; + + // An encrypted event that hasn't been decrypted yet (keys pending) has an + // empty result from getClearContent(). Treat it as still-loading rather + // than a failure so the UI shows a placeholder instead of MessageFailedContent + // until the MatrixEventEvent.Decrypted callback fires. + const isPendingDecrypt = + replyEvent !== undefined && + replyEvent !== null && + replyEvent.isEncrypted() && + !replyEvent.isDecryptionFailure() && + !replyEvent.getClearContent(); + let bodyJSX: ReactNode = fallbackBody; if (format === 'org.matrix.custom.html' && formattedBody) { @@ -100,6 +125,7 @@ export const Reply = as<'div', ReplyProps>( .replace(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, + useAuthentication, nicknames, }); bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element; @@ -124,11 +150,15 @@ export const Reply = as<'div', ReplyProps>( ) } data-event-id={replyEventId} - onClick={onClick} + onClick={replyEvent !== null && !isBlockedSender ? onClick : undefined} > - {replyEvent !== undefined ? ( + {replyEvent !== undefined && !isPendingDecrypt ? ( - {badEncryption ? : bodyJSX} + {(() => { + if (isBlockedSender) return ; + if (badEncryption) return ; + return bodyJSX; + })()} ) : ( ( /> )} + {replyEvent === null && ( + } + onClick={(evt) => { + evt.stopPropagation(); + queryClient.invalidateQueries({ queryKey: [room.roomId, replyEventId] }); + }} + /> + )} ); } diff --git a/src/app/components/message/content/FallbackContent.tsx b/src/app/components/message/content/FallbackContent.tsx index 270504f0..8156a5d0 100644 --- a/src/app/components/message/content/FallbackContent.tsx +++ b/src/app/components/message/content/FallbackContent.tsx @@ -58,6 +58,13 @@ export const MessageEmptyContent = as<'div', { children?: never }>(({ ...props } )); +export const MessageBlockedContent = as<'div', { children?: never }>(({ ...props }, ref) => ( + + + Message from a blocked user + +)); + export const MessageEditedContent = as<'span', { children?: never }>(({ ...props }, ref) => ( {' (edited)'} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index cc1d0eca..134c38ec 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -298,25 +298,30 @@ export const RoomInput = forwardRef( format: replyFormat, } = replyEvent?.getContent() ?? {}; + // Prefer the live event content; fall back to what was snapshotted in the + // draft when the user hit Reply (the event may not be in SDK state if it + // was redacted or evicted, but the draft always carries the original body). + const htmlBody = + replyFormat === 'org.matrix.custom.html' ? replyFormattedBody : replyDraft?.formattedBody; + const plainBody = replyBody ?? replyDraft?.body; + let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null; - if (replyFormat === 'org.matrix.custom.html' && replyFormattedBody) { - const strippedHtml = trimReplyFromFormattedBody(replyFormattedBody) + if (htmlBody) { + const strippedHtml = trimReplyFromFormattedBody(htmlBody) .replace(//gi, ' ') .replace(/<\/p>\s*]*>/gi, ' ') .replace(/<\/?p[^>]*>/gi, '') .replace(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, roomId, { linkifyOpts: LINKIFY_OPTS, + useAuthentication, nicknames, }); replyBodyJSX = parse(strippedHtml, parserOpts); - } else if (replyBody) { - const strippedBody = trimReplyFromBody(replyBody).replace(/(?:\r\n|\r|\n)/g, ' '); - replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody)); - } else if (replyDraft) { - const strippedBody = trimReplyFromBody(replyDraft.body).replace(/(?:\r\n|\r|\n)/g, ' '); - replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody)); + } else if (plainBody) { + const strippedBody = trimReplyFromBody(plainBody).replace(/(?:\r\n|\r|\n)/g, ' '); + replyBodyJSX = scaleSystemEmoji(strippedBody); } useEffect(() => { diff --git a/src/app/hooks/useRoomEvent.ts b/src/app/hooks/useRoomEvent.ts index d9b36352..70335366 100644 --- a/src/app/hooks/useRoomEvent.ts +++ b/src/app/hooks/useRoomEvent.ts @@ -1,5 +1,12 @@ -import { IEvent, MatrixEvent, Room, CryptoBackend } from '$types/matrix-sdk'; -import { useCallback, useMemo } from 'react'; +import { + IEvent, + MatrixEvent, + MatrixEventEvent, + Room, + RoomEvent, + CryptoBackend, +} from '$types/matrix-sdk'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import to from 'await-to-js'; import { useQuery } from '@tanstack/react-query'; import { useMatrixClient } from './useMatrixClient'; @@ -8,13 +15,23 @@ const useFetchEvent = (room: Room, eventId: string) => { const mx = useMatrixClient(); const fetchEventCallback = useCallback(async () => { + // Use fetchRoomEvent rather than getEventTimeline. + // + // getEventTimeline calls /context, which adds a new EventTimeline to the + // room's UnfilteredTimelineSet. The SDK then emits RoomEvent.TimelineRefresh, + // which RoomTimeline.tsx catches and scrolls the visible window back to the + // live end — causing an unwanted jump-to-bottom on every reply reload. + // + // fetchRoomEvent fetches the raw event without touching the timeline state, + // so there is no side-effect on the visible scroll position. The trade-off + // is that the returned MatrixEvent is standalone (not tracked in SDK state), + // so we handle edits and decryption manually below. const evt = await mx.fetchRoomEvent(room.roomId, eventId); const mEvent = new MatrixEvent(evt); - if (evt.unsigned?.['m.relations'] && evt.unsigned?.['m.relations']['m.replace']) { - const replaceEvt = evt.unsigned?.['m.relations']['m.replace'] as IEvent; - const replaceEvent = new MatrixEvent(replaceEvt); - mEvent.makeReplaced(replaceEvent); + if (evt.unsigned?.['m.relations']?.['m.replace']) { + const replaceEvt = evt.unsigned['m.relations']['m.replace'] as IEvent; + mEvent.makeReplaced(new MatrixEvent(replaceEvt)); } if (mEvent.isEncrypted() && mx.getCrypto()) { @@ -38,21 +55,109 @@ export const useRoomEvent = ( eventId: string, getLocally?: () => MatrixEvent | undefined ) => { + const mx = useMatrixClient(); + + // Shared re-render trigger used by both decryption listeners below. + const [, forceUpdate] = useState(0); + + // `tick` lets useMemo re-run when the reply-target event arrives via sync. + // The Room reference is stable (SDK mutates it in-place), so without this + // the memo would never recompute even when room.findEventById(eventId) would + // now return a result. + const [tick, setTick] = useState(0); + const event = useMemo(() => { - if (getLocally) return getLocally(); - return room.findEventById(eventId); - }, [room, eventId, getLocally]); + // `tick` is in the deps array below — useMemo reruns whenever a timeline + // event for our eventId arrives (see RoomEvent.Timeline below). + // Check the caller's local window first (e.g. the rendered timeline set), + // then fall back to the SDK's full room state. Events that are present in + // room history but outside the currently visible window are found this way + // without a network round-trip. + const local = getLocally?.(); + return local ?? room.findEventById(eventId); + // eslint-disable-next-line react-hooks/exhaustive-deps -- tick intentionally forces re-eval on new timeline events + }, [room, eventId, getLocally, tick]); + + // Re-evaluate the local lookup the moment the target event arrives in the + // room's live timeline. We only subscribe while the event is missing to + // keep overhead to zero once it has been resolved. Checking the event ID + // in the handler avoids spurious setTick calls for unrelated messages. + useEffect(() => { + if (event !== undefined) return undefined; + const onTimeline = (incoming: MatrixEvent) => { + if (incoming.getId() === eventId) setTick((n) => n + 1); + }; + room.on(RoomEvent.Timeline, onTimeline); + return () => { + room.off(RoomEvent.Timeline, onTimeline); + }; + }, [room, event, eventId]); const fetchEvent = useFetchEvent(room, eventId); const { data, error } = useQuery({ + // Only hit the network when neither the visible window nor the SDK's room + // state has the event. Note: fetchRoomEvent does NOT add its result to SDK + // state, so `event` stays undefined after a successful fetch and this flag + // remains true on subsequent renders — but staleTime: Infinity prevents + // any redundant re-fetches. enabled: event === undefined, queryKey: [room.roomId, eventId], queryFn: fetchEvent, staleTime: Infinity, - gcTime: 60 * 60 * 1000, // 1hour + gcTime: 60 * 60 * 1000, // 1 hour + retry: 3, + // Progressive back-off: 1 s → 2 s → 4 s (capped at 30 s). + retryDelay: (attempt) => Math.min(1_000 * 2 ** attempt, 30_000), }); + // ── E2EE retry for standalone fetched events ────────────────────────────── + // fetchRoomEvent returns a MatrixEvent that is NOT tracked in SDK state, so + // the SDK's normal Megolm key-delivery pipeline never fires + // MatrixEventEvent.Decrypted on it. Instead, we piggyback on the Decrypted + // events of SDK-tracked live-timeline events as a proxy signal for + // "new Megolm session keys have arrived" and immediately retry + // attemptDecryption on our standalone event. + useEffect(() => { + if (!data?.isEncrypted() || !data.isDecryptionFailure()) return undefined; + const crypto = mx.getCrypto(); + if (!crypto) return undefined; + + const retryDecrypt = async () => { + const [err] = await to(data.attemptDecryption(crypto as CryptoBackend)); + if (!err && !data.isDecryptionFailure()) forceUpdate((n) => n + 1); + }; + + // Use the last 50 live-timeline events that are still encrypted as + // sentinels. When any of them fires Decrypted it means new keys arrived. + const sentinels = room + .getLiveTimeline() + .getEvents() + .slice(-50) + .filter((e) => e.isEncrypted()); + + const onKeyArrived = () => { + retryDecrypt(); + }; + sentinels.forEach((e) => e.on(MatrixEventEvent.Decrypted, onKeyArrived)); + return () => sentinels.forEach((e) => e.off(MatrixEventEvent.Decrypted, onKeyArrived)); + }, [data, room, mx]); + + // ── Decryption listener for SDK-tracked events ──────────────────────────── + // When an event IS in the SDK state (found locally via `event`), the SDK's + // Megolm pipeline fires MatrixEventEvent.Decrypted on it automatically when + // keys later arrive. Subscribe so the component re-renders without any + // manual retry. + const resolvedEvent = event ?? data ?? undefined; + useEffect(() => { + if (!resolvedEvent?.isEncrypted()) return undefined; + const onDecrypted = () => forceUpdate((n) => n + 1); + resolvedEvent.on(MatrixEventEvent.Decrypted, onDecrypted); + return () => { + resolvedEvent.off(MatrixEventEvent.Decrypted, onDecrypted); + }; + }, [resolvedEvent]); + if (event) return event; if (data) return data; if (error) return null; From f9b452bde13fceb6d3b33806728b3336fc902369 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 19:13:31 -0500 Subject: [PATCH 011/124] fix(notifications): SW push deep-links, visibility suppression, settings decoupling, nav fix - Rewrite notificationclick to deep-link via /to/:user_id/:room_id/:event_id so the correct account is activated on cold PWA launch (ToRoomEvent -> pendingNotificationAtom) - Suppress OS/SW push notification when the app window is already visible; track visibility via postMessage from the app on visibilitychange - Remove preferPushOnMobile dead code - Add useSystemNotifications setting (desktop-only, default true on desktop); split it out from useInAppNotifications so pill and OS notifications are independently controlled - Settings UI: desktop shows In-App + System Notifications; mobile shows In-App + Push Notifications; each hides the irrelevant third toggle - Fix InviteNotifications / MessageNotifications to gate OS notifications on useSystemNotifications + !mobileOrTablet(); pill remains gated on useInAppNotifications - Fix NotificationJumper: bypass useRoomNavigate (which routes through space path) -- navigate directly via getHomeRoomPath / getDirectRoomPath so tapping a pill banner on mobile opens the room timeline, not the space-nav panel - When the app is already open, use postMessage({ type: notificationClick }) from SW to the running window; new ServiceWorkerClickHandler component handles it with the same setActiveSessionId + setPending path as the pill flow; /to/ URL kept as cold-launch fallback only --- .../notifications/SystemNotification.tsx | 55 +++- src/app/hooks/useNotificationJumper.ts | 21 +- src/app/pages/client/ClientNonUIFeatures.tsx | 176 +++++++----- src/app/pages/client/ToRoomEvent.tsx | 41 ++- src/app/pages/paths.ts | 5 +- src/app/state/settings.ts | 11 +- src/sw.ts | 250 +++++++++++------- src/sw/pushNotification.ts | 1 + 8 files changed, 363 insertions(+), 197 deletions(-) diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 04e31db7..38b3a7cc 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -14,6 +14,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useClientConfig } from '$hooks/useClientConfig'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { pushSubscriptionAtom } from '$state/pushSubscription'; +import { mobileOrTablet } from '$utils/user-agent'; import { requestBrowserNotificationPermission, enablePushNotifications, @@ -165,6 +166,10 @@ function WebPushNotificationSetting() { export function SystemNotification() { const [showInAppNotifs, setShowInAppNotifs] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifs, setShowSystemNotifs] = useSetting( + settingsAtom, + 'useSystemNotifications' + ); const [isNotificationSounds, setIsNotificationSounds] = useSetting( settingsAtom, 'isNotificationSounds' @@ -177,18 +182,14 @@ export function SystemNotification() { settingsAtom, 'showMessageContentInEncryptedNotifications' ); + const [clearNotificationsOnRead, setClearNotificationsOnRead] = useSetting( + settingsAtom, + 'clearNotificationsOnRead' + ); return ( System & Notifications - - - } /> + {mobileOrTablet() && ( + + + + )} + {!mobileOrTablet() && ( + + } + /> + + )} + + } + /> + { diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index f3bbfb26..a85900a5 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,7 +1,7 @@ import { useAtomValue, useSetAtom } from 'jotai'; import { ReactNode, useCallback, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; -import { EventType, PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; +import { PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import LogoSVG from '$public/res/svg/cinny.svg'; import { NotificationBanner } from '$components/notification-banner'; @@ -28,13 +28,13 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useInboxNotificationsSelected } from '$hooks/router/useInbox'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { registrationAtom } from '$state/serviceWorkerRegistration'; -import { activeSessionIdAtom, pendingNotificationAtom, inAppBannerAtom } from '$state/sessions'; +import { pendingNotificationAtom, inAppBannerAtom, activeSessionIdAtom } from '$state/sessions'; import { buildRoomMessageNotification, resolveNotificationPreviewText, } from '$utils/notificationStyle'; import { mobileOrTablet } from '$utils/user-agent'; -import { getInboxInvitesPath, getInboxNotificationsPath } from '../pathUtils'; +import { getInboxInvitesPath } from '../pathUtils'; import { BackgroundNotifications } from './BackgroundNotifications'; function SystemEmojiFeature() { @@ -70,9 +70,11 @@ function FaviconUpdater() { let notification = false; let highlight = false; let total = 0; + let highlightTotal = 0; roomToUnread.forEach((unread) => { if (unread.from === null) { total += unread.total; + highlightTotal += unread.highlight; } if (unread.total > 0) { notification = true; @@ -88,12 +90,17 @@ function FaviconUpdater() { setFavicon(LogoSVG); } try { - navigator.setAppBadge(total); + // Only badge with highlight (mention) counts — total unread is too noisy + // for an OS-level app badge. + if (highlightTotal > 0) { + navigator.setAppBadge(highlightTotal); + } else { + navigator.clearAppBadge(); + } if (usePushNotifications) { if (total === 0) { - // All rooms read — clear every notification and the badge. + // All rooms read — clear every notification. registration.getNotifications().then((notifs) => notifs.forEach((n) => n.close())); - navigator.clearAppBadge(); } else { // Dismiss notifications for individual rooms that are now fully read. registration.getNotifications().then((notifs) => { @@ -123,7 +130,7 @@ function InviteNotifications() { const mx = useMatrixClient(); const navigate = useNavigate(); - const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); @@ -152,26 +159,26 @@ function InviteNotifications() { useEffect(() => { if (invites.length <= perviousInviteLen || mx.getSyncState() !== 'SYNCING') return; - // Page hidden: if push is enabled, SW handles the OS notification. If not, nothing to do. - if (document.visibilityState !== 'visible') return; + // SW push (via Sygnal) handles invite notifications when the app is backgrounded. + if (document.visibilityState !== 'visible' && usePushNotifications) return; - // Page is visible — show in-app experience. - // On mobile with push: iOS-style — play sound only, no OS notification (SW is silent when - // the app is visible on mobile, matching foreground behaviour of native chat apps). - // On desktop with push: SW skipped (saw a visible client), so we show the OS notification. - // Without push: always show OS notification when page is visible. - const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet(); - if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) { - notify(invites.length - perviousInviteLen); + // OS notification for invites — desktop only. + if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) { + try { + notify(invites.length - perviousInviteLen); + } catch { + // window.Notification may be unavailable in sandboxed environments. + } } - if (notificationSound) { + // Audio API requires a visible document; skip when hidden. + if (document.visibilityState === 'visible' && notificationSound) { playSound(); } }, [ mx, invites, perviousInviteLen, - showNotifications, + showSystemNotifications, usePushNotifications, notificationSound, notify, @@ -189,9 +196,14 @@ function InviteNotifications() { function MessageNotifications() { const audioRef = useRef(null); const notifiedEventsRef = useRef>(new Set()); + // Record mount time so we can distinguish live events from historical backfill + // on sliding sync proxies that don't set num_live (which causes liveEvent=false + // for all events, including actually-new messages). + const clientStartTimeRef = useRef(Date.now()); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); @@ -225,9 +237,23 @@ function MessageNotifications() { if (mx.getSyncState() !== 'SYNCING') return; if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return; + // Older sliding sync proxies (e.g. matrix-sliding-sync) omit num_live, + // which causes every event to arrive with fromCache=true and therefore + // liveEvent=false — silently blocking all notifications. Fall back to an + // age check: treat the event as potentially live only when it was sent + // within 60 s of this component mounting (tight enough to avoid phantom + // notifications for pre-existing unread messages, generous enough for + // messages that arrived during a brief offline window). + // Additionally, skip the event if the user already has a read receipt + // covering it (message was read on another device before this session). + const isHistoricalEvent = + !data.liveEvent && + (mEvent.getTs() < clientStartTimeRef.current - 60 * 1000 || + (!!room && room.hasUserReadEvent(mx.getSafeUserId(), mEvent.getId()!))); + if ( !room || - !data.liveEvent || + isHistoricalEvent || room.isSpaceRoom() || !isNotificationEvent(mEvent) || getNotificationType(mx, room.roomId) === NotificationType.Mute @@ -309,10 +335,9 @@ function MessageNotifications() { }); } - // On desktop without push: also fire an OS notification as a secondary fallback - // so the user is alerted even if the browser window is minimised. - const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet(); - if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) { + // On desktop: also fire an OS notification so the user is alerted even + // if the browser window is minimised (respects System Notifications toggle). + if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) { const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); @@ -345,7 +370,10 @@ function MessageNotifications() { }; } - if (notificationSound && loudByRule) { + // In-app audio: play whenever notification sounds are enabled. + // Not gated on loudByRule — that only controls the OS-level silent flag. + // Audio API requires a visible, focused document; skip when hidden. + if (document.visibilityState === 'visible' && notificationSound) { playSound(); } }; @@ -358,6 +386,7 @@ function MessageNotifications() { notificationSound, notificationSelected, showNotifications, + showSystemNotifications, showMessageContent, showEncryptedMessageContent, usePushNotifications, @@ -394,55 +423,39 @@ type ClientNonUIFeaturesProps = { children: ReactNode; }; -export function HandleNotificationClick() { - const navigate = useNavigate(); - const setActiveSessionId = useSetAtom(activeSessionIdAtom); +function ServiceWorkerClickHandler() { const setPending = useSetAtom(pendingNotificationAtom); + const setActiveSessionId = useSetAtom(activeSessionIdAtom); + const navigate = useNavigate(); useEffect(() => { - const handleNotificationClickEvent = (event: any) => { - if (!event.data) return; - // Note: do NOT guard on event.source — iOS Safari sets it to null for - // SW-to-client postMessages (Webkit divergence from spec). The type check - // below is the correct way to filter unrelated messages. - const eventData = event.data; - if (!(eventData?.type === 'notificationToRoomEvent')) return; - const messageData = eventData?.message; - if (!messageData) { - navigate(getInboxNotificationsPath()); + if (!('serviceWorker' in navigator)) return undefined; + + const handleMessage = (ev: MessageEvent) => { + const { data } = ev; + if (!data || data.type !== 'notificationClick') return; + + const { userId, roomId, eventId, isInvite } = data as { + userId?: string; + roomId?: string; + eventId?: string; + isInvite?: boolean; + }; + + if (userId) setActiveSessionId(userId); + + if (isInvite) { + navigate(getInboxInvitesPath()); return; } - const targetSessionId = - typeof messageData?.user_id === 'string' ? messageData.user_id : undefined; - const eventType = messageData!.type as EventType; - switch (eventType) { - case EventType.RoomMessage: - case EventType.RoomMessageEncrypted: - // Always set the target session — jotai ignores no-ops if already active. - // This ensures we never accidentally navigate under the wrong account. - if (targetSessionId) setActiveSessionId(targetSessionId); - setPending({ - roomId: messageData!.room_id, - eventId: messageData!.event_id, - targetSessionId, - }); - return; - case EventType.RoomMember: - if (!(messageData?.content?.membership === 'invite')) return; - if (targetSessionId) setActiveSessionId(targetSessionId); - navigate(getInboxInvitesPath()); - break; - default: - break; - } + if (!roomId) return; + setPending({ roomId, eventId, targetSessionId: userId }); }; - navigator.serviceWorker.addEventListener('message', handleNotificationClickEvent); - return () => { - navigator.serviceWorker.removeEventListener('message', handleNotificationClickEvent); - }; - }, [navigate, setActiveSessionId, setPending]); + navigator.serviceWorker.addEventListener('message', handleMessage); + return () => navigator.serviceWorker.removeEventListener('message', handleMessage); + }, [setPending, setActiveSessionId, navigate]); return null; } @@ -455,25 +468,45 @@ function SyncNotificationSettingsWithServiceWorker() { settingsAtom, 'showMessageContentInEncryptedNotifications' ); + const [clearNotificationsOnRead] = useSetting(settingsAtom, 'clearNotificationsOnRead'); + + useEffect(() => { + if (!('serviceWorker' in navigator)) return undefined; + + const postVisibility = () => { + const visible = document.visibilityState === 'visible'; + const msg = { type: 'setAppVisible', visible }; + navigator.serviceWorker.controller?.postMessage(msg); + navigator.serviceWorker.ready.then((reg) => reg.active?.postMessage(msg)); + }; + + // Report initial visibility immediately, then track changes. + postVisibility(); + document.addEventListener('visibilitychange', postVisibility); + return () => document.removeEventListener('visibilitychange', postVisibility); + }, []); useEffect(() => { if (!('serviceWorker' in navigator)) return; - // preferPushOnMobile=false: SW skips push when page is visible on all devices. - // The in-app path handles the visible case (sound on mobile, OS notification on desktop). - const preferPushOnMobile = false; const payload = { type: 'setNotificationSettings' as const, notificationSoundEnabled: notificationSound, - preferPushOnMobile, showMessageContent, showEncryptedMessageContent, + clearNotificationsOnRead, }; navigator.serviceWorker.controller?.postMessage(payload); navigator.serviceWorker.ready.then((registration) => { registration.active?.postMessage(payload); }); - }, [notificationSound, usePushNotifications, showMessageContent, showEncryptedMessageContent]); + }, [ + notificationSound, + usePushNotifications, + showMessageContent, + showEncryptedMessageContent, + clearNotificationsOnRead, + ]); return null; } @@ -489,6 +522,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + {children} diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx index 48321e66..3073b44e 100644 --- a/src/app/pages/client/ToRoomEvent.tsx +++ b/src/app/pages/client/ToRoomEvent.tsx @@ -1,35 +1,34 @@ import { useEffect } from 'react'; -import { useParams, useSearchParams } from 'react-router-dom'; +import { useParams } from 'react-router-dom'; import { useSetAtom } from 'jotai'; import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions'; -// ToRoomEvent handles the /to/:room_id/:event_id route used by the SW when it -// opens a new window for a push notification (killed-app case) OR by client.navigate() -// on iOS where postMessage is unreliable after focus(). +// ToRoomEvent handles /to/:user_id/:room_id/:event_id? — the canonical deep-link +// URL used by the service worker's notificationclick handler. // -// It does NOT navigate itself. Instead it writes to pendingNotificationAtom so -// that NotificationJumper handles the actual navigation once the correct client -// is synced. This survives the ClientRoot account-switch reload that happens when -// setActiveSessionId() changes the active session: ToRoomEvent unmounts as soon -// as ClientRoot calls navigate(getHomePath()), but the atom value persists and -// NotificationJumper picks it up once the new client is ready. +// The :user_id segment lets the SW embed the target Matrix user ID directly in +// the URL (e.g. %40alice%3Aserver.tld) so the correct account is always +// activated before navigation, even on a cold launch where the app restarts +// from scratch after the PWA was killed by the OS. +// +// This component does NOT navigate itself — it writes to pendingNotificationAtom +// so NotificationJumper can navigate once the Matrix client has finished its +// initial sync. The atom survives the ClientRoot reload that happens when +// setActiveSessionId() triggers an account switch. export function ToRoomEvent() { - const { room_id: roomId, event_id: eventId } = useParams(); - const [searchParams] = useSearchParams(); - const targetUserId = searchParams.get('uid') ?? undefined; + const { user_id: userId, room_id: roomId, event_id: eventId } = useParams(); const setActiveSessionId = useSetAtom(activeSessionIdAtom); const setPending = useSetAtom(pendingNotificationAtom); useEffect(() => { if (!roomId) return; - const rid = roomId; // narrowed to string - if (targetUserId) setActiveSessionId(targetUserId); - setPending({ roomId: rid, eventId, targetSessionId: targetUserId }); - // Push a clean entry onto history so the back button doesn't return to /to/… - if (window.history.length <= 2) { - window.history.pushState({}, '', '/'); - } - }, [roomId, eventId, targetUserId, setActiveSessionId, setPending]); + // Switch to the target account first so the notification jumper navigates + // under the correct session. + if (userId) setActiveSessionId(userId); + setPending({ roomId, eventId, targetSessionId: userId }); + // Replace /to/… in history so the back button doesn't return to this route. + window.history.replaceState({}, '', '/'); + }, [userId, roomId, eventId, setActiveSessionId, setPending]); return null; } diff --git a/src/app/pages/paths.ts b/src/app/pages/paths.ts index 06878fd3..82f8c6dd 100644 --- a/src/app/pages/paths.ts +++ b/src/app/pages/paths.ts @@ -86,7 +86,10 @@ export const INBOX_NOTIFICATIONS_PATH = `/inbox/${NOTIFICATIONS_PATH_SEGMENT}`; export const INBOX_INVITES_PATH = `/inbox/${INVITES_PATH_SEGMENT}`; export const TO_PATH = '/to'; -export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:room_id/:event_id?`; +// Deep-link route used by push notification click-back URLs. +// Format: /to/:user_id/:room_id/:event_id? +// e.g. /to/%40alice%3Aserver/%21room%3Aserver/%24event%3Aserver +export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:user_id/:room_id/:event_id?`; export const SPACE_SETTINGS_PATH = '/space-settings/'; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index fab45528..47b42da5 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -1,4 +1,5 @@ import { atom } from 'jotai'; +import { mobileOrTablet } from '$utils/user-agent'; const STORAGE_KEY = 'settings'; export type DateFormat = 'D MMM YYYY' | 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD' | ''; @@ -45,9 +46,11 @@ export interface Settings { usePushNotifications: boolean; useInAppNotifications: boolean; + useSystemNotifications: boolean; isNotificationSounds: boolean; showMessageContentInNotifications: boolean; showMessageContentInEncryptedNotifications: boolean; + clearNotificationsOnRead: boolean; hour24Clock: boolean; dateFormatString: string; @@ -102,11 +105,17 @@ const defaultSettings: Settings = { showHiddenEvents: false, legacyUsernameColor: false, - usePushNotifications: false, + // Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop. + // In-app pill banner: always on — it's the primary foreground alert on mobile + // and a useful secondary alert on desktop. + // System (OS) notifications: desktop-only; hidden and disabled on mobile. + usePushNotifications: mobileOrTablet(), useInAppNotifications: true, + useSystemNotifications: !mobileOrTablet(), isNotificationSounds: true, showMessageContentInNotifications: false, showMessageContentInEncryptedNotifications: false, + clearNotificationsOnRead: false, hour24Clock: false, dateFormatString: 'D MMM YYYY', diff --git a/src/sw.ts b/src/sw.ts index 87fbc348..7185fbd3 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -1,16 +1,20 @@ /// // eslint-disable-next-line import-x/no-extraneous-dependencies import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching'; -import { EventType } from 'matrix-js-sdk/lib/@types/event'; + import { createPushNotifications } from './sw/pushNotification'; export type {}; declare const self: ServiceWorkerGlobalScope; let notificationSoundEnabled = true; -let preferPushOnMobile = false; +// Tracks whether a page client has reported itself as visible. +// The clients.matchAll() visibilityState is unreliable on iOS Safari PWA, +// so we use this explicit flag as a fallback. +let appIsVisible = false; let showMessageContent = false; let showEncryptedMessageContent = false; +let clearNotificationsOnRead = false; const { handlePushNotificationPushData } = createPushNotifications(self, () => ({ notificationSoundEnabled, showMessageContent, @@ -29,9 +33,9 @@ async function persistSettings() { new Response( JSON.stringify({ notificationSoundEnabled, - preferPushOnMobile, showMessageContent, showEncryptedMessageContent, + clearNotificationsOnRead, }), { headers: { 'Content-Type': 'application/json' } } ) @@ -49,10 +53,11 @@ async function loadPersistedSettings() { const s = await response.json(); if (typeof s.notificationSoundEnabled === 'boolean') notificationSoundEnabled = s.notificationSoundEnabled; - if (typeof s.preferPushOnMobile === 'boolean') preferPushOnMobile = s.preferPushOnMobile; if (typeof s.showMessageContent === 'boolean') showMessageContent = s.showMessageContent; if (typeof s.showEncryptedMessageContent === 'boolean') showEncryptedMessageContent = s.showEncryptedMessageContent; + if (typeof s.clearNotificationsOnRead === 'boolean') + clearNotificationsOnRead = s.clearNotificationsOnRead; } catch { // Ignore — stale or missing cache is fine; we fall back to defaults. } @@ -159,6 +164,11 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { setSession(client.id, accessToken, baseUrl); event.waitUntil(cleanupDeadClients()); } + if (type === 'setAppVisible') { + if (typeof (data as { visible?: unknown }).visible === 'boolean') { + appIsVisible = (data as { visible: boolean }).visible; + } + } if (type === 'setNotificationSettings') { if ( typeof (data as { notificationSoundEnabled?: unknown }).notificationSoundEnabled === 'boolean' @@ -166,9 +176,6 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { notificationSoundEnabled = (data as { notificationSoundEnabled: boolean }) .notificationSoundEnabled; } - if (typeof (data as { preferPushOnMobile?: unknown }).preferPushOnMobile === 'boolean') { - preferPushOnMobile = (data as { preferPushOnMobile: boolean }).preferPushOnMobile; - } if (typeof (data as { showMessageContent?: unknown }).showMessageContent === 'boolean') { showMessageContent = (data as { showMessageContent: boolean }).showMessageContent; } @@ -179,12 +186,27 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { showEncryptedMessageContent = (data as { showEncryptedMessageContent: boolean }) .showEncryptedMessageContent; } + if ( + typeof (data as { clearNotificationsOnRead?: unknown }).clearNotificationsOnRead === 'boolean' + ) { + clearNotificationsOnRead = (data as { clearNotificationsOnRead: boolean }) + .clearNotificationsOnRead; + } // Persist so settings survive SW restart (iOS kills the SW aggressively). event.waitUntil(persistSettings()); } }); -const MEDIA_PATHS = ['/_matrix/client/v1/media/download', '/_matrix/client/v1/media/thumbnail']; +const MEDIA_PATHS = [ + '/_matrix/client/v1/media/download', + '/_matrix/client/v1/media/thumbnail', + // Legacy unauthenticated endpoints — servers that require auth return 404/403 + // for these when no token is present, so intercept and add auth here too. + '/_matrix/media/v3/download', + '/_matrix/media/v3/thumbnail', + '/_matrix/media/r0/download', + '/_matrix/media/r0/thumbnail', +]; function mediaPath(url: string): boolean { try { @@ -233,10 +255,17 @@ self.addEventListener('fetch', (event: FetchEvent) => { const { clientId } = event; if (!clientId) return; + // For browser sub-resource loads (images, video, audio, etc.), 'follow' is + // the correct mode: the auth header is sent to the Matrix server which owns + // the first hop; any CDN redirect it issues is followed natively by the + // Fetch machinery. 'manual' would return an opaque-redirect Response that + // the browser cannot render as an / )} { + setIsDescribed(!isDescribed); + }} aria-label="Add Upload Description" variant="SurfaceVariant" radii="Pill" size="300" > - + )} + {isDescribed && ( + { + setDesc(fileItem, htmlBio, htmlBio); + }} + /> + )} } > diff --git a/src/app/components/upload-card/UploadDescriptionEditor.css.tsx b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx new file mode 100644 index 00000000..d456b718 --- /dev/null +++ b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx @@ -0,0 +1,28 @@ +import { style, globalStyle } from '@vanilla-extract/css'; +import { config } from 'folds'; + +export const BioEditorContainer = style({ + backgroundColor: 'var(--sable-bg-container)', + borderRadius: config.radii.R400, + overflow: 'hidden', +}); + +globalStyle(`${BioEditorContainer} div[class*="EditorTextarea"]`, { + backgroundColor: 'var(--sable-bg-container) !important', + border: 'none !important', +}); + +globalStyle(`${BioEditorContainer} [class*="Toolbar"]`, { + backgroundColor: 'var(--sable-bg-container) !important', + padding: 'var(--space-S100) !important', + borderTop: '1px solid var(--sable-outline-variant) !important', +}); + +globalStyle(`${BioEditorContainer} [class*="Toolbar"] button`, { + backgroundColor: 'transparent !important', + boxShadow: 'none !important', +}); + +globalStyle(`${BioEditorContainer} [class*="Toolbar"] button:hover`, { + backgroundColor: 'var(--sable-surface-variant) !important', +}); diff --git a/src/app/components/upload-card/UploadDescriptionEditor.tsx b/src/app/components/upload-card/UploadDescriptionEditor.tsx new file mode 100644 index 00000000..b702cefd --- /dev/null +++ b/src/app/components/upload-card/UploadDescriptionEditor.tsx @@ -0,0 +1,253 @@ +import { KeyboardEventHandler, useCallback, useEffect, useState, useRef } from 'react'; +import { + Box, + Chip, + Icon, + IconButton, + Icons, + Line, + PopOut, + RectCords, + Spinner, + Text, + config, +} from 'folds'; +import { Editor, Transforms } from 'slate'; +import { ReactEditor } from 'slate-react'; +import { isKeyHotkey } from 'is-hotkey'; +import { + AutocompletePrefix, + AutocompleteQuery, + CustomEditor, + EmoticonAutocomplete, + Toolbar, + createEmoticonElement, + getAutocompleteQuery, + getPrevWorldRange, + htmlToEditorInput, + plainToEditorInput, + moveCursor, + toMatrixCustomHTML, + toPlainText, + trimCustomHtml, + useEditor, +} from '$components/editor'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { UseStateProvider } from '$components/UseStateProvider'; +import { EmojiBoard } from '$components/emoji-board'; +import { mobileOrTablet } from '$utils/user-agent'; +import * as css from './UploadDescriptionEditor.css'; + +type BioEditorProps = { + value?: string | any; + isSaving?: boolean; + imagePackRooms?: any[]; + onSave: (htmlContent: string) => void; +}; + +export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: BioEditorProps) { + const editor = useEditor(); + const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); + const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); + const [toolbar, setToolbar] = useState(false); + + const [autocompleteQuery, setAutocompleteQuery] = + useState>(); + const [hasChanged, setHasChanged] = useState(false); + + const prevValue = useRef(value); + const initialized = useRef(false); + const handleSave = useCallback(() => { + const plainText = toPlainText(editor.children, isMarkdown).trim(); + + const customHtml = trimCustomHtml( + toMatrixCustomHTML(editor.children, { + allowTextFormatting: true, + allowBlockMarkdown: isMarkdown, + allowInlineMarkdown: isMarkdown, + }) + ); + + onSave(customHtml || plainText); + setHasChanged(false); + }, [editor, isMarkdown, onSave]); + + useEffect(() => { + const valueChanged = prevValue.current !== value; + const isFirstValidLoad = !initialized.current && value !== undefined; + + if (valueChanged || isFirstValidLoad) { + prevValue.current = value; + + let normalizedValue = value; + if ( + typeof normalizedValue === 'object' && + normalizedValue !== null && + 'formatted_body' in normalizedValue + ) { + normalizedValue = normalizedValue.formatted_body; + } + + const safeValue = typeof normalizedValue === 'string' ? normalizedValue : ''; + + const incomingPlainText = toPlainText( + htmlToEditorInput(safeValue, isMarkdown), + isMarkdown + ).trim(); + const currentPlainText = toPlainText(editor.children, isMarkdown).trim(); + + if (currentPlainText === incomingPlainText && initialized.current) return; + + const isLikelyHtml = safeValue.includes('<') || safeValue.includes('>'); + const initialValue = isLikelyHtml + ? htmlToEditorInput(safeValue, isMarkdown) + : plainToEditorInput(safeValue, isMarkdown); + + editor.children = initialValue; + Editor.normalize(editor, { force: true }); + Transforms.select(editor, Editor.start(editor, [])); + + initialized.current = true; + setHasChanged(false); + } + }, [value, editor, isMarkdown]); + + const handleKeyDown: KeyboardEventHandler = useCallback( + (evt) => { + if (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) { + evt.preventDefault(); + handleSave(); + } + }, + [handleSave, enterForNewline] + ); + + const handleKeyUp: KeyboardEventHandler = useCallback( + (evt) => { + if (isKeyHotkey('escape', evt)) { + evt.preventDefault(); + return; + } + const prevWordRange = getPrevWorldRange(editor); + const query = prevWordRange + ? getAutocompleteQuery(editor, prevWordRange, [AutocompletePrefix.Emoticon]) + : undefined; + setAutocompleteQuery(query); + }, + [editor] + ); + + const handleCloseAutocomplete = useCallback(() => { + ReactEditor.focus(editor); + setAutocompleteQuery(undefined); + }, [editor]); + + const handleEmoticonSelect = (key: string, shortcode: string) => { + editor.insertNode(createEmoticonElement(key, shortcode)); + moveCursor(editor); + setHasChanged(true); + }; + + return ( + + + {autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && ( + + )} + + + + {hasChanged && ( + : undefined + } + > + {isSaving ? 'Saving' : 'Save'} + + )} + + + setToolbar(!toolbar)} + > + + + + {(anchor: RectCords | undefined, setAnchor) => ( + + setAnchor((v) => { + if (v) { + if (!mobileOrTablet()) ReactEditor.focus(editor); + return undefined; + } + return v; + }) + } + /> + } + > + setAnchor(evt.currentTarget.getBoundingClientRect())} + > + + + + )} + + + + {toolbar && ( + + + + + )} + + } + /> + + + ); +} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index cef4ef2b..f0f47443 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -205,7 +205,6 @@ export const RoomInput = forwardRef( const [uploadBoard, setUploadBoard] = useState(true); const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(roomId)); - const [describedFile, setDescribedFile] = useState(undefined); const uploadFamilyObserverAtom = createUploadFamilyObserverAtom( roomUploadAtomFamily, selectedFiles.map((f) => f.file) @@ -238,7 +237,6 @@ export const RoomInput = forwardRef( metadata: { markedAsSpoiler: false, }, - body: 'aaa', }) ); } else { @@ -250,7 +248,6 @@ export const RoomInput = forwardRef( metadata: { markedAsSpoiler: false, }, - body: 'aaa', }) ); } @@ -340,11 +337,15 @@ export const RoomInput = forwardRef( }, [setSelectedFiles] ); - const handleDescription = useCallback( - (fileItem: TUploadContent) => { - setDescribedFile(fileItem); + const setDesc = useCallback( + (fileItem: TUploadItem, body: string, formatted_body: string) => { + setSelectedFiles({ + type: 'REPLACE', + item: fileItem, + replacement: { ...fileItem, body, formatted_body }, + }); }, - [setDescribedFile] + [setSelectedFiles] ); const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { @@ -368,19 +369,12 @@ export const RoomInput = forwardRef( }; const handleSendUpload = async (uploads: UploadSuccess[]) => { - const plaintext = toPlainText(editor.children, isMarkdown).trim(); + const plainText = toPlainText(editor.children, isMarkdown).trim(); + const contentsPromises = uploads.map(async (upload) => { const fileItem = selectedFiles.find((f) => f.file === upload.file); if (!fileItem) throw new Error('Broken upload'); - if (fileItem.file === describedFile) { - fileItem.body = plaintext; - resetEditor(editor); - resetEditorHistory(editor); - setInputKey((prev) => prev + 1); - sendTypingStatus(false); - setDescribedFile(undefined); - } if (fileItem.file.type.startsWith('image')) { return getImageMsgContent(mx, fileItem, upload.mxc); } @@ -396,7 +390,7 @@ export const RoomInput = forwardRef( const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises)); if (contents.length > 0) { - const replyContent = plaintext.length === 0 ? getReplyContent(replyDraft) : undefined; + const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined; if (replyContent) contents[0]['m.relates_to'] = replyContent; setReplyDraft(undefined); } @@ -414,7 +408,6 @@ export const RoomInput = forwardRef( const submit = useCallback(async () => { uploadBoardHandlers.current?.handleSend(); - if (describedFile !== undefined) return; const commandName = getBeginCommand(editor); let plainText = toPlainText(editor.children, isMarkdown).trim(); let customHtml = trimCustomHtml( @@ -489,7 +482,6 @@ export const RoomInput = forwardRef( setReplyDraft(undefined); sendTypingStatus(false); }; - if (scheduledTime) { try { const delayMs = computeDelayMs(scheduledTime); @@ -505,7 +497,6 @@ export const RoomInput = forwardRef( setEditingScheduledDelayId(null); setScheduledTime(null); resetInput(); - setDescribedFile(undefined); } catch { // Network/server error — leave editor and scheduled state intact for retry } @@ -516,7 +507,6 @@ export const RoomInput = forwardRef( invalidate(); setEditingScheduledDelayId(null); resetInput(); - setDescribedFile(undefined); } catch { // Cancel failed — leave state intact for retry } @@ -527,22 +517,21 @@ export const RoomInput = forwardRef( }); } }, [ + editor, + isMarkdown, mx, roomId, - room, - editor, replyDraft, - sendTypingStatus, - setReplyDraft, - describedFile, - isMarkdown, - commands, scheduledTime, - setScheduledTime, - isEncrypted, - queryClient, editingScheduledDelayId, + commands, + sendTypingStatus, + queryClient, + setReplyDraft, + isEncrypted, setEditingScheduledDelayId, + setScheduledTime, + room, ]); const handleKeyDown: KeyboardEventHandler = useCallback( @@ -682,7 +671,7 @@ export const RoomInput = forwardRef( fileItem={fileItem} setMetadata={handleFileMetadata} onRemove={handleRemoveUpload} - setDescription={handleDescription} + setDesc={setDesc} /> ))} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 61b1306c..3ecc0771 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -59,6 +59,8 @@ export const getImageMsgContent = async ( msgtype: MsgType.Image, filename: file.name, body: file.name, + format: 'org.matrix.custom.html', + formatted_body: file.name, [MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, }; if (imgEl) { @@ -77,7 +79,11 @@ export const getImageMsgContent = async ( } else { content.url = mxc; } - if (item.body?.length && item.body.length > 0) content.body = item.body; + if (item.body && item.body.length > 0) content.body = item.body; + if (item.formatted_body && item.formatted_body.length > 0) { + content.format = 'org.matrix.custom.html'; + content.formatted_body = item.formatted_body; + } return content; }; @@ -95,6 +101,8 @@ export const getVideoMsgContent = async ( msgtype: MsgType.Video, filename: file.name, body: file.name, + format: 'org.matrix.custom.html', + formatted_body: file.name, [MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, }; if (videoEl) { @@ -127,7 +135,11 @@ export const getVideoMsgContent = async ( } else { content.url = mxc; } - if (item.body?.length && item.body.length > 0) content.body = item.body; + if (item.body && item.body.length > 0) content.body = item.body; + if (item.formatted_body && item.formatted_body.length > 0) { + content.format = 'org.matrix.custom.html'; + content.formatted_body = item.formatted_body; + } return content; }; @@ -137,6 +149,8 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent => msgtype: MsgType.Audio, filename: file.name, body: file.name, + format: 'org.matrix.custom.html', + formatted_body: file.name, info: { mimetype: file.type, size: file.size, @@ -150,7 +164,11 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent => } else { content.url = mxc; } - if (item.body?.length && item.body.length > 0) content.body = item.body; + if (item.body && item.body.length > 0) content.body = item.body; + if (item.formatted_body && item.formatted_body.length > 0) { + content.format = 'org.matrix.custom.html'; + content.formatted_body = item.formatted_body; + } return content; }; @@ -160,6 +178,8 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { msgtype: MsgType.File, filename: file.name, body: file.name, + format: 'org.matrix.custom.html', + formatted_body: file.name, info: { mimetype: file.type, size: file.size, @@ -173,6 +193,10 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { } else { content.url = mxc; } - if (item.body?.length && item.body.length > 0) content.body = item.body; + if (item.body && item.body.length > 0) content.body = item.body; + if (item.formatted_body && item.formatted_body.length > 0) { + content.format = 'org.matrix.custom.html'; + content.formatted_body = item.formatted_body; + } return content; }; diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index abb93d1d..51c3cfaf 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -17,6 +17,8 @@ export type TUploadItem = { metadata: TUploadMetadata; encInfo: EncryptedAttachmentInfo | undefined; body?: string; + format?: string; + formatted_body?: string; }; export type TUploadListAtom = ReturnType>; From d1ae1d459431bd1cc74878c30a1c16449b47a931 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 21:25:48 -0500 Subject: [PATCH 026/124] fix(notifications): show rich body in banner; fix encrypted msg dedup - Add early-return guard for m.room.encrypted in MessageNotifications so eventId is never added to notifiedEventsRef before decryption. Without this, the post-decryption re-emission was deduped and the banner showed "Encrypted Message" instead of actual content. - Build ReactNode bodyNode via getReactCustomHtmlParser + parse + sanitizeCustomHtml for org.matrix.custom.html messages, mirroring the timeline renderer pipeline (mxc images, mentions, etc.). - Add bodyNode?: ReactNode to InAppBannerNotification type. - Add BodyNode component in NotificationBanner; falls back to existing plain-text BodyText path when bodyNode is absent. --- .../NotificationBanner.css.ts | 9 +++++- .../NotificationBanner.tsx | 28 +++++++++++++++-- src/app/pages/client/ClientNonUIFeatures.tsx | 31 +++++++++++++++++++ src/app/state/sessions.ts | 6 ++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/app/components/notification-banner/NotificationBanner.css.ts b/src/app/components/notification-banner/NotificationBanner.css.ts index 80c3617f..1ddfacda 100644 --- a/src/app/components/notification-banner/NotificationBanner.css.ts +++ b/src/app/components/notification-banner/NotificationBanner.css.ts @@ -110,11 +110,18 @@ export const BannerRoomName = style({ }); // Caps tall previews and fades the bottom edge when content overflows. +// Desktop: 25vh, mobile (≤768px): 35vh. export const BannerBody = style({ position: 'relative', - maxHeight: toRem(56), + maxHeight: '25vh', overflow: 'hidden', + '@media': { + '(max-width: 768px)': { + maxHeight: '35vh', + }, + }, + selectors: { '&[data-overflow=true]::after': { content: '""', diff --git a/src/app/components/notification-banner/NotificationBanner.tsx b/src/app/components/notification-banner/NotificationBanner.tsx index ad0ba026..666ec077 100644 --- a/src/app/components/notification-banner/NotificationBanner.tsx +++ b/src/app/components/notification-banner/NotificationBanner.tsx @@ -1,5 +1,5 @@ import { useAtom } from 'jotai'; -import { useCallback, useEffect, useRef, useState } from 'react'; +import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'; import { Box, Icon, IconButton, Icons, Text } from 'folds'; import { inAppBannerAtom, InAppBannerNotification } from '$state/sessions'; import * as css from './NotificationBanner.css'; @@ -26,6 +26,26 @@ function BodyText({ text, hovered }: { text: string; hovered: boolean }) { ); } +// Same as BodyText but renders a pre-built ReactNode (rich HTML with mxc/mention transforms). +function BodyNode({ node, hovered }: { node: ReactNode; hovered: boolean }) { + const ref = useRef(null); + const [overflow, setOverflow] = useState(false); + + useEffect(() => { + const el = ref.current; + if (!el) return; + setOverflow(el.scrollHeight > el.clientHeight); + }, [node]); + + return ( +
+ + {node} + +
+ ); +} + type BannerItemProps = { notification: InAppBannerNotification; onDismiss: (id: string) => void; @@ -115,7 +135,11 @@ function BannerItem({ notification, onDismiss }: BannerItemProps) { )} - {notification.body && } + {notification.bodyNode ? ( + + ) : ( + notification.body && + )} { window.focus(); diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index 10a4ff3b..aadf20ce 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -1,3 +1,4 @@ +import { ReactNode } from 'react'; import { atom } from 'jotai'; import { createLogger } from '$utils/debug'; import { @@ -185,6 +186,11 @@ export type InAppBannerNotification = { /** Display name of the sender. */ senderName?: string; body?: string; + /** + * Pre-rendered rich body with mxc/mention transforms (built in ClientNonUIFeatures). + * When present, takes precedence over the plain-text `body` fallback. + */ + bodyNode?: ReactNode; /** URL of an avatar or room icon to display inside the banner. */ icon?: string; onClick: () => void; From b4de2a835a42d457785545046667d2867e45c20a Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 21:50:54 -0500 Subject: [PATCH 027/124] chore: add changeset for notification banner rich body fix --- .changeset/notification_banner_rich_body.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/notification_banner_rich_body.md diff --git a/.changeset/notification_banner_rich_body.md b/.changeset/notification_banner_rich_body.md new file mode 100644 index 00000000..ec13cbee --- /dev/null +++ b/.changeset/notification_banner_rich_body.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer. From e6ec921999785fb27acadc71981fc47c2d75d137 Mon Sep 17 00:00:00 2001 From: Jason LaGuidice <19523621+jasonlaguidice@users.noreply.github.com> Date: Thu, 5 Mar 2026 19:25:35 -0800 Subject: [PATCH 028/124] shorten changeset message --- .changeset/replace-send-chevron-mobile.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.changeset/replace-send-chevron-mobile.md b/.changeset/replace-send-chevron-mobile.md index 1f4e20d7..a1579868 100644 --- a/.changeset/replace-send-chevron-mobile.md +++ b/.changeset/replace-send-chevron-mobile.md @@ -2,8 +2,4 @@ sable: patch --- -Changed scheduled send behavior on mobile. Removed the chevron next to the send button to make it more finger-friendly. - -Now, if your homeserver reports it, tapping and holding on the send button for 1 second will invoke the schedule picker to schedule a message. - -Desktop client is unaffected and retains the chevron so there is a visible indicator if scheduled send is supported. +Mobile: changed scheduled send chevron to tap + hold From 19de8c9adfd34e79986fc719c8d2dffb8fba9683 Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Fri, 6 Mar 2026 05:59:11 +0200 Subject: [PATCH 029/124] added desc preview when appropriate --- .../upload-card/UploadCardRenderer.tsx | 27 +++++++++-- .../UploadDescriptionEditor.css.tsx | 10 ++-- .../upload-card/UploadDescriptionEditor.tsx | 47 ++++++++++--------- 3 files changed, 53 insertions(+), 31 deletions(-) diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index f4020f13..1d068575 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -1,5 +1,5 @@ import { ReactNode, useEffect, useState } from 'react'; -import { Box, Chip, Icon, IconButton, Icons, Text, color, config, toRem } from 'folds'; +import { Box, Chip, Icon, IconButton, Icons, Text, Tooltip, color, config, toRem } from 'folds'; import { UploadStatus, UploadSuccess, useBindUploadAtom } from '$state/upload'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { TUploadContent } from '$utils/matrix'; @@ -216,12 +216,31 @@ export function UploadCardRenderer({ )} {isDescribed && ( { - setDesc(fileItem, htmlBio, htmlBio); + value={fileItem.formatted_body || fileItem.body} + onSave={(plainText, htmlContent) => { + setDesc(fileItem, plainText, htmlContent); + setIsDescribed(false); }} /> )} + {!isDescribed && fileItem.body && fileItem.body.length > 0 && ( + + + {fileItem.body} + + + )} } > diff --git a/src/app/components/upload-card/UploadDescriptionEditor.css.tsx b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx index d456b718..04037a7b 100644 --- a/src/app/components/upload-card/UploadDescriptionEditor.css.tsx +++ b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx @@ -1,28 +1,28 @@ import { style, globalStyle } from '@vanilla-extract/css'; import { config } from 'folds'; -export const BioEditorContainer = style({ +export const DescriptionEditorContainer = style({ backgroundColor: 'var(--sable-bg-container)', borderRadius: config.radii.R400, overflow: 'hidden', }); -globalStyle(`${BioEditorContainer} div[class*="EditorTextarea"]`, { +globalStyle(`${DescriptionEditorContainer} div[class*="EditorTextarea"]`, { backgroundColor: 'var(--sable-bg-container) !important', border: 'none !important', }); -globalStyle(`${BioEditorContainer} [class*="Toolbar"]`, { +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"]`, { backgroundColor: 'var(--sable-bg-container) !important', padding: 'var(--space-S100) !important', borderTop: '1px solid var(--sable-outline-variant) !important', }); -globalStyle(`${BioEditorContainer} [class*="Toolbar"] button`, { +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button`, { backgroundColor: 'transparent !important', boxShadow: 'none !important', }); -globalStyle(`${BioEditorContainer} [class*="Toolbar"] button:hover`, { +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button:hover`, { backgroundColor: 'var(--sable-surface-variant) !important', }); diff --git a/src/app/components/upload-card/UploadDescriptionEditor.tsx b/src/app/components/upload-card/UploadDescriptionEditor.tsx index b702cefd..4893ba38 100644 --- a/src/app/components/upload-card/UploadDescriptionEditor.tsx +++ b/src/app/components/upload-card/UploadDescriptionEditor.tsx @@ -39,14 +39,19 @@ import { EmojiBoard } from '$components/emoji-board'; import { mobileOrTablet } from '$utils/user-agent'; import * as css from './UploadDescriptionEditor.css'; -type BioEditorProps = { +type DescriptionEditorProps = { value?: string | any; isSaving?: boolean; imagePackRooms?: any[]; - onSave: (htmlContent: string) => void; + onSave: (plaintext: string, htmlContent: string) => void; }; -export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: BioEditorProps) { +export function DescriptionEditor({ + value, + isSaving, + imagePackRooms, + onSave, +}: DescriptionEditorProps) { const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); @@ -54,7 +59,6 @@ export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: B const [autocompleteQuery, setAutocompleteQuery] = useState>(); - const [hasChanged, setHasChanged] = useState(false); const prevValue = useRef(value); const initialized = useRef(false); @@ -69,8 +73,7 @@ export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: B }) ); - onSave(customHtml || plainText); - setHasChanged(false); + onSave(plainText, customHtml || plainText); }, [editor, isMarkdown, onSave]); useEffect(() => { @@ -109,7 +112,6 @@ export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: B Transforms.select(editor, Editor.start(editor, [])); initialized.current = true; - setHasChanged(false); } }, [value, editor, isMarkdown]); @@ -146,12 +148,15 @@ export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: B const handleEmoticonSelect = (key: string, shortcode: string) => { editor.insertNode(createEmoticonElement(key, shortcode)); moveCursor(editor); - setHasChanged(true); }; return ( - + {autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && ( - {hasChanged && ( - : undefined - } - > - {isSaving ? 'Saving' : 'Save'} - - )} + : undefined + } + > + {isSaving ? 'Saving' : 'Save'} + Date: Thu, 5 Mar 2026 22:17:40 -0600 Subject: [PATCH 030/124] null and undefined checks for pronouns --- src/app/utils/pronouns.ts | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/app/utils/pronouns.ts b/src/app/utils/pronouns.ts index 63c6e29c..c653d9fd 100644 --- a/src/app/utils/pronouns.ts +++ b/src/app/utils/pronouns.ts @@ -1,15 +1,17 @@ // helper function to convert a comma-separated pronouns string into an array of objects with summary and optional language export function parsePronounsInput(pronouns: string): { summary: string; language?: string }[] { + if (!pronouns || typeof pronouns !== 'string') return []; + return pronouns .split(',') - .map((s) => s.trim()) + .map((s) => s?.trim()) .filter(Boolean) .map((s) => { const parts = s.split(':'); if (parts.length === 1) { return { - summary: parts[0].slice(0, 16), + summary: (parts[0] || '').slice(0, 16), language: 'en', }; } @@ -17,8 +19,8 @@ export function parsePronounsInput(pronouns: string): { summary: string; languag const [language, summary] = parts; return { - language: language || 'en', - summary: summary.slice(0, 16), + language: (language || 'en').trim() || 'en', + summary: (summary || '').trim().slice(0, 16), }; }); } @@ -29,21 +31,34 @@ export function filterPronounsByLanguage( enabled: boolean, languages: string[] ): { summary: string; language?: string }[] { + if (!Array.isArray(pronouns)) return []; + if (!enabled) { - return pronouns.map((p) => ({ ...p, summary: p.summary.slice(0, 16) })); + return pronouns.map((p) => ({ + ...p, + summary: (p?.summary || '').slice(0, 16), + })); } - const normalizedLanguages = languages.map((lang) => lang.trim().toLowerCase()); + const normalizedLanguages = (languages || []) + .filter(Boolean) + .map((lang) => lang.trim().toLowerCase()); const filteredPronouns = pronouns - .filter((p) => normalizedLanguages.includes((p.language || 'en').trim().toLowerCase())) + .filter((p) => { + const lang = (p?.language || 'en').trim().toLowerCase(); + return normalizedLanguages.includes(lang); + }) .map((p) => ({ ...p, - summary: p.summary.slice(0, 16), + summary: (p?.summary || '').slice(0, 16), })); if (filteredPronouns.length === 0) { - return pronouns.map((p) => ({ ...p, summary: p.summary.slice(0, 16) })); + return pronouns.map((p) => ({ + ...p, + summary: (p?.summary || '').slice(0, 16), + })); } return filteredPronouns; From e98589d374c948d90d0ab1b4db6b7ad712c45c37 Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Fri, 6 Mar 2026 06:24:54 +0200 Subject: [PATCH 031/124] fixed scrolling issue --- src/app/components/upload-card/UploadCardRenderer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 1d068575..b15a91c6 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -227,12 +227,12 @@ export function UploadCardRenderer({ Date: Thu, 5 Mar 2026 22:34:11 -0600 Subject: [PATCH 032/124] Create .gitattributes --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..94f480de --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf \ No newline at end of file From 184785f36ebe35e0c3b76752e31b7229f40468ae Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Fri, 6 Mar 2026 06:53:23 +0200 Subject: [PATCH 033/124] added knopes file thing idk --- .../feat_adding_basic_file_descriptions.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 .changeset/feat_adding_basic_file_descriptions.md diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md new file mode 100644 index 00000000..cb1faaea --- /dev/null +++ b/.changeset/feat_adding_basic_file_descriptions.md @@ -0,0 +1,36 @@ +--- +sable: minor +--- + +# Feat: Adding basic file descriptions + +#182 by @nushea + + + +### Description +This pr adds basic file description options, if one may choose to caption or provide additional details to an image itself. +Through this PR each item individually on the Upload Board has a chevron next to the delete button which when selected opens a text editor for setting up the caption for the item. If the editor is closed and a file has a description, a plaintext version of it will be displayed under the file. +Currently, descriptions have to be saved prior to sending a message, and selecting the chevron discards any changes as-well. + +(collapsed view when no file has a description) +image + +(collapsed view when files have descriptions) +image + +(open view when the editors are opened) +image + +#### Type of change + +- [x] New feature (non-breaking change which adds functionality) + +### Checklist: + +- [x] My code follows the style guidelines of this project +- [x] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [x] My changes generate no new warnings + From 31f123893470cef9b502add54a81b4e67db848ba Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Fri, 6 Mar 2026 07:01:19 +0200 Subject: [PATCH 034/124] corrected knopes thing --- .../feat_adding_basic_file_descriptions.md | 37 +------------------ 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md index cb1faaea..639d562a 100644 --- a/.changeset/feat_adding_basic_file_descriptions.md +++ b/.changeset/feat_adding_basic_file_descriptions.md @@ -1,36 +1 @@ ---- -sable: minor ---- - -# Feat: Adding basic file descriptions - -#182 by @nushea - - - -### Description -This pr adds basic file description options, if one may choose to caption or provide additional details to an image itself. -Through this PR each item individually on the Upload Board has a chevron next to the delete button which when selected opens a text editor for setting up the caption for the item. If the editor is closed and a file has a description, a plaintext version of it will be displayed under the file. -Currently, descriptions have to be saved prior to sending a message, and selecting the chevron discards any changes as-well. - -(collapsed view when no file has a description) -image - -(collapsed view when files have descriptions) -image - -(open view when the editors are opened) -image - -#### Type of change - -- [x] New feature (non-breaking change which adds functionality) - -### Checklist: - -- [x] My code follows the style guidelines of this project -- [x] I have performed a self-review of my own code -- [ ] I have commented my code, particularly in hard-to-understand areas -- [ ] I have made corresponding changes to the documentation -- [x] My changes generate no new warnings - +Added the ability to add descriptions to uploaded files From a4295e31eae01ddda2fe74d028bc04ff8dd72295 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 23:15:54 -0600 Subject: [PATCH 035/124] patch dm room nicknames applying to many rooms --- src/app/hooks/useRoomMeta.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index 0243e1dc..eee1385f 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -27,7 +27,11 @@ export const useRoomName = (room: Room): string => { room.recalculate(); } - const nextName = dmNickname ?? room.name; + // small room = dm i promise trust + const memberCount = room.getJoinedMemberCount(); + const isSmallRoom = memberCount <= 2; + + const nextName = isSmallRoom && dmNickname ? dmNickname : room.name; setName((prev) => (prev !== nextName ? nextName : prev)); }; From e8def4cdeaa5c2b39e0a3d086013775c1e8be0be Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 23:16:53 -0600 Subject: [PATCH 036/124] Create fix_dm_room_nicknames.md --- .changeset/fix_dm_room_nicknames.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix_dm_room_nicknames.md diff --git a/.changeset/fix_dm_room_nicknames.md b/.changeset/fix_dm_room_nicknames.md new file mode 100644 index 00000000..8b5921be --- /dev/null +++ b/.changeset/fix_dm_room_nicknames.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Fix dm room nicknames applying to non-dm private rooms. From ed61bec48b7287de669a628f18ea99a692c6fcb8 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 23:21:16 -0600 Subject: [PATCH 037/124] fix changeset formatting --- .changeset/feat_adding_basic_file_descriptions.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md index 639d562a..8b6e9951 100644 --- a/.changeset/feat_adding_basic_file_descriptions.md +++ b/.changeset/feat_adding_basic_file_descriptions.md @@ -1 +1,5 @@ +--- +sable: patch +--- + Added the ability to add descriptions to uploaded files From 9ef4531eeeafe32a3ad157c72703e5c8b2f96d2e Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 5 Mar 2026 23:58:09 -0600 Subject: [PATCH 038/124] fix disable in app notifs on desktop --- .../notifications/SystemNotification.tsx | 26 ++++++++++--------- .../pages/client/BackgroundNotifications.tsx | 3 ++- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 38b3a7cc..6394f423 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -190,18 +190,20 @@ export function SystemNotification() { return ( System & Notifications - - } - /> - + {mobileOrTablet() && ( + + } + /> + + )} {mobileOrTablet() && ( @@ -281,7 +282,7 @@ export function BackgroundNotifications() { if (document.visibilityState !== 'visible') return; // Respect in-app notification setting (read from ref to avoid stale closure) - if (!showNotificationsRef.current) return; + if (!mobileOrTablet() || !showNotificationsRef.current) return; const notificationPayload = buildRoomMessageNotification({ roomName: room.name ?? room.getCanonicalAlias() ?? room.roomId, From b5f3989c578eee555f50097706264e0e4fb59328 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 00:12:32 -0600 Subject: [PATCH 039/124] metadata updatessss --- ..._to_filter_user_pronouns_based_on_the_pronouns_language.md | 2 +- .changeset/badge_count_dms_only_setting.md | 2 +- .changeset/feat_adding_basic_file_descriptions.md | 2 +- .changeset/notification_banner_rich_body.md | 2 +- .changeset/pr149_react_permission_fixes.md | 2 +- .changeset/pr149_text_quick_react.md | 2 +- .changeset/room_font_and_color_toggles.md | 2 +- .changeset/unread_pins_toggle.md | 2 +- .prettierignore | 4 +++- knope.toml | 1 - 10 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md b/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md index 12f23445..390e3a43 100644 --- a/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md +++ b/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Add option to filter user pronouns based on the pronouns language diff --git a/.changeset/badge_count_dms_only_setting.md b/.changeset/badge_count_dms_only_setting.md index b95c4f3a..17dd88d8 100644 --- a/.changeset/badge_count_dms_only_setting.md +++ b/.changeset/badge_count_dms_only_setting.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on. diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md index 8b6e9951..86fea0d4 100644 --- a/.changeset/feat_adding_basic_file_descriptions.md +++ b/.changeset/feat_adding_basic_file_descriptions.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Added the ability to add descriptions to uploaded files diff --git a/.changeset/notification_banner_rich_body.md b/.changeset/notification_banner_rich_body.md index ec13cbee..6cd3d2d4 100644 --- a/.changeset/notification_banner_rich_body.md +++ b/.changeset/notification_banner_rich_body.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer. diff --git a/.changeset/pr149_react_permission_fixes.md b/.changeset/pr149_react_permission_fixes.md index f1d9a444..6f51c180 100644 --- a/.changeset/pr149_react_permission_fixes.md +++ b/.changeset/pr149_react_permission_fixes.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages). diff --git a/.changeset/pr149_text_quick_react.md b/.changeset/pr149_text_quick_react.md index e1dae4ad..72b78270 100644 --- a/.changeset/pr149_text_quick_react.md +++ b/.changeset/pr149_text_quick_react.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#` diff --git a/.changeset/room_font_and_color_toggles.md b/.changeset/room_font_and_color_toggles.md index 5130aebf..700a6b3f 100644 --- a/.changeset/room_font_and_color_toggles.md +++ b/.changeset/room_font_and_color_toggles.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors. diff --git a/.changeset/unread_pins_toggle.md b/.changeset/unread_pins_toggle.md index 0fec1416..9bf34335 100644 --- a/.changeset/unread_pins_toggle.md +++ b/.changeset/unread_pins_toggle.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts. diff --git a/.prettierignore b/.prettierignore index bc876b6c..dd3a20e6 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,4 +3,6 @@ node_modules package.json package-lock.json LICENSE -README.md \ No newline at end of file +README.md +CHANGELOG.md +./changeset \ No newline at end of file diff --git a/knope.toml b/knope.toml index 157e2214..cc19b1dc 100644 --- a/knope.toml +++ b/knope.toml @@ -5,7 +5,6 @@ changelog = "CHANGELOG.md" extra_changelog_sections = [ { name = "Documentation", types = ["docs"] }, { name = "Notes", types = ["note"] }, - { types = ["patch"], name = "Updates" }, ] # assets = "marker for GitHub bot" // TODO: add this later once we have assets From cef877d65b7f81edc823d89c36947f9412d9ebc8 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 00:15:00 -0600 Subject: [PATCH 040/124] fixed fr trust --- src/app/pages/client/ClientNonUIFeatures.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index cd00dfe0..b2a01319 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -299,7 +299,7 @@ function MessageNotifications() { // Page is visible — show the themed in-app notification banner for any // highlighted message (mention / keyword) or loud push rule. - if ((isHighlightByRule || loudByRule) && showNotifications) { + if (mobileOrTablet() && (isHighlightByRule || loudByRule) && showNotifications) { const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); From d10efd8f69831599e4d33eca5dd8695288811f70 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 00:31:48 -0600 Subject: [PATCH 041/124] Update Experimental.tsx --- src/app/features/settings/experimental/Experimental.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index b9719357..d8375271 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -42,8 +42,6 @@ export function Experimental({ requestClose }: ExperimentalProps) {
- - From d0afde43acd6f6d0f4f837d72d2d29696e4b061d Mon Sep 17 00:00:00 2001 From: Trash Panda Date: Sun, 1 Mar 2026 20:01:18 -0700 Subject: [PATCH 042/124] Add support for audio and video previews in URL previews and reuse attachment components Signed-off-by: Trash Panda --- src/app/components/url-preview/UrlPreview.tsx | 5 +- .../url-preview/UrlPreviewCard.css.tsx | 11 +++- .../components/url-preview/UrlPreviewCard.tsx | 55 ++++++++++++++----- 3 files changed, 51 insertions(+), 20 deletions(-) diff --git a/src/app/components/url-preview/UrlPreview.tsx b/src/app/components/url-preview/UrlPreview.tsx index ae970b0e..d27aa33d 100644 --- a/src/app/components/url-preview/UrlPreview.tsx +++ b/src/app/components/url-preview/UrlPreview.tsx @@ -6,13 +6,10 @@ export const UrlPreview = as<'div'>(({ className, ...props }, ref) => ( )); -export const UrlPreviewImg = as<'img'>(({ className, alt, ...props }, ref) => ( - {alt} -)); - export const UrlPreviewContent = as<'div'>(({ className, ...props }, ref) => ( - {imgUrl && ( - + {(prev['og:video'] && ( + ); }; From fe74d8b64b804faa731451dc8ae866aa447c39a8 Mon Sep 17 00:00:00 2001 From: "knope-bot[bot]" <152252888+knope-bot[bot]@users.noreply.github.com> Date: Fri, 6 Mar 2026 06:38:37 +0000 Subject: [PATCH 043/124] Release packages --- ...pronouns_based_on_the_pronouns_language.md | 5 ---- .changeset/badge_count_dms_only_setting.md | 5 ---- ...n_to_scolor_sfont_spronoun_respectively.md | 5 ---- ...emoji_board_perf_defer_image_pack_reads.md | 5 ---- .../feat_adding_basic_file_descriptions.md | 5 ---- .changeset/fix_dm_room_nicknames.md | 5 ---- ...ide_delete_modal_after_message_deletion.md | 5 ---- .changeset/media_auth_error_fallback.md | 5 ---- .changeset/message_send_button_chips.md | 5 ---- .changeset/notification_banner_rich_body.md | 5 ---- ...tification_pull_unread_background_badge.md | 5 ---- .changeset/pr149_react_permission_fixes.md | 5 ---- .changeset/pr149_text_quick_react.md | 5 ---- .changeset/replace-send-chevron-mobile.md | 5 ---- .changeset/reply_e2ee_blocked_user_fixes.md | 5 ---- .changeset/room_font_and_color_toggles.md | 5 ---- ...fications_deep_link_visibility_settings.md | 5 ---- .../timeline_sliding_sync_rendering_fixes.md | 5 ---- .changeset/unread_pins_toggle.md | 5 ---- CHANGELOG.md | 27 +++++++++++++++++++ package-lock.json | 6 ++--- package.json | 4 +-- 22 files changed, 32 insertions(+), 100 deletions(-) delete mode 100644 .changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md delete mode 100644 .changeset/badge_count_dms_only_setting.md delete mode 100644 .changeset/change_gcolor_gfont_gpronoun_to_scolor_sfont_spronoun_respectively.md delete mode 100644 .changeset/emoji_board_perf_defer_image_pack_reads.md delete mode 100644 .changeset/feat_adding_basic_file_descriptions.md delete mode 100644 .changeset/fix_dm_room_nicknames.md delete mode 100644 .changeset/hide_delete_modal_after_message_deletion.md delete mode 100644 .changeset/media_auth_error_fallback.md delete mode 100644 .changeset/message_send_button_chips.md delete mode 100644 .changeset/notification_banner_rich_body.md delete mode 100644 .changeset/notification_pull_unread_background_badge.md delete mode 100644 .changeset/pr149_react_permission_fixes.md delete mode 100644 .changeset/pr149_text_quick_react.md delete mode 100644 .changeset/replace-send-chevron-mobile.md delete mode 100644 .changeset/reply_e2ee_blocked_user_fixes.md delete mode 100644 .changeset/room_font_and_color_toggles.md delete mode 100644 .changeset/sw_notifications_deep_link_visibility_settings.md delete mode 100644 .changeset/timeline_sliding_sync_rendering_fixes.md delete mode 100644 .changeset/unread_pins_toggle.md diff --git a/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md b/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md deleted file mode 100644 index 390e3a43..00000000 --- a/.changeset/add_option_to_filter_user_pronouns_based_on_the_pronouns_language.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Add option to filter user pronouns based on the pronouns language diff --git a/.changeset/badge_count_dms_only_setting.md b/.changeset/badge_count_dms_only_setting.md deleted file mode 100644 index 17dd88d8..00000000 --- a/.changeset/badge_count_dms_only_setting.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on. diff --git a/.changeset/change_gcolor_gfont_gpronoun_to_scolor_sfont_spronoun_respectively.md b/.changeset/change_gcolor_gfont_gpronoun_to_scolor_sfont_spronoun_respectively.md deleted file mode 100644 index 5179ed1e..00000000 --- a/.changeset/change_gcolor_gfont_gpronoun_to_scolor_sfont_spronoun_respectively.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively. diff --git a/.changeset/emoji_board_perf_defer_image_pack_reads.md b/.changeset/emoji_board_perf_defer_image_pack_reads.md deleted file mode 100644 index 3a443fda..00000000 --- a/.changeset/emoji_board_perf_defer_image_pack_reads.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Improved emoji board performance by deferring image pack cache reads so the board opens instantly rather than blocking on the initial render. diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md deleted file mode 100644 index 86fea0d4..00000000 --- a/.changeset/feat_adding_basic_file_descriptions.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Added the ability to add descriptions to uploaded files diff --git a/.changeset/fix_dm_room_nicknames.md b/.changeset/fix_dm_room_nicknames.md deleted file mode 100644 index 8b5921be..00000000 --- a/.changeset/fix_dm_room_nicknames.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Fix dm room nicknames applying to non-dm private rooms. diff --git a/.changeset/hide_delete_modal_after_message_deletion.md b/.changeset/hide_delete_modal_after_message_deletion.md deleted file mode 100644 index d62f7a38..00000000 --- a/.changeset/hide_delete_modal_after_message_deletion.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Hide delete modal after successfully deleting a message. diff --git a/.changeset/media_auth_error_fallback.md b/.changeset/media_auth_error_fallback.md deleted file mode 100644 index e37b6532..00000000 --- a/.changeset/media_auth_error_fallback.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Fixed media authentication handling: removed unnecessary redirect following, added error fallback UI for failed media loads, and ensured authentication headers are applied consistently when rendering inline media in HTML message bodies. diff --git a/.changeset/message_send_button_chips.md b/.changeset/message_send_button_chips.md deleted file mode 100644 index 2eb45088..00000000 --- a/.changeset/message_send_button_chips.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Failed message retry and delete actions now use Chip buttons for visual consistency with the rest of the interface. diff --git a/.changeset/notification_banner_rich_body.md b/.changeset/notification_banner_rich_body.md deleted file mode 100644 index 6cd3d2d4..00000000 --- a/.changeset/notification_banner_rich_body.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer. diff --git a/.changeset/notification_pull_unread_background_badge.md b/.changeset/notification_pull_unread_background_badge.md deleted file mode 100644 index 0559d03a..00000000 --- a/.changeset/notification_pull_unread_background_badge.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Adds a new message pill and background app highlighted unread count. diff --git a/.changeset/pr149_react_permission_fixes.md b/.changeset/pr149_react_permission_fixes.md deleted file mode 100644 index 6f51c180..00000000 --- a/.changeset/pr149_react_permission_fixes.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages). diff --git a/.changeset/pr149_text_quick_react.md b/.changeset/pr149_text_quick_react.md deleted file mode 100644 index 72b78270..00000000 --- a/.changeset/pr149_text_quick_react.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#` diff --git a/.changeset/replace-send-chevron-mobile.md b/.changeset/replace-send-chevron-mobile.md deleted file mode 100644 index a1579868..00000000 --- a/.changeset/replace-send-chevron-mobile.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Mobile: changed scheduled send chevron to tap + hold diff --git a/.changeset/reply_e2ee_blocked_user_fixes.md b/.changeset/reply_e2ee_blocked_user_fixes.md deleted file mode 100644 index 979faf0e..00000000 --- a/.changeset/reply_e2ee_blocked_user_fixes.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail. diff --git a/.changeset/room_font_and_color_toggles.md b/.changeset/room_font_and_color_toggles.md deleted file mode 100644 index 700a6b3f..00000000 --- a/.changeset/room_font_and_color_toggles.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors. diff --git a/.changeset/sw_notifications_deep_link_visibility_settings.md b/.changeset/sw_notifications_deep_link_visibility_settings.md deleted file mode 100644 index 0a29d3a1..00000000 --- a/.changeset/sw_notifications_deep_link_visibility_settings.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel. diff --git a/.changeset/timeline_sliding_sync_rendering_fixes.md b/.changeset/timeline_sliding_sync_rendering_fixes.md deleted file mode 100644 index 422d3575..00000000 --- a/.changeset/timeline_sliding_sync_rendering_fixes.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: patch ---- - -Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state. diff --git a/.changeset/unread_pins_toggle.md b/.changeset/unread_pins_toggle.md deleted file mode 100644 index 9bf34335..00000000 --- a/.changeset/unread_pins_toggle.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -sable: minor ---- - -Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts. diff --git a/CHANGELOG.md b/CHANGELOG.md index be2cf967..2a183e8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Sable Client Changelog +## 1.4.0 (2026-03-06) + +### Features + +* Add option to filter user pronouns based on the pronouns language +* Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on. +* Added the ability to add descriptions to uploaded files +* Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer. +* You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages). +* Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#` +* Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors. +* Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts. + +### Fixes + +* Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively. +* Improved emoji board performance by deferring image pack cache reads so the board opens instantly rather than blocking on the initial render. +* Fix dm room nicknames applying to non-dm private rooms. +* Hide delete modal after successfully deleting a message. +* Fixed media authentication handling: removed unnecessary redirect following, added error fallback UI for failed media loads, and ensured authentication headers are applied consistently when rendering inline media in HTML message bodies. +* Failed message retry and delete actions now use Chip buttons for visual consistency with the rest of the interface. +* Adds a new message pill and background app highlighted unread count. +* Mobile: changed scheduled send chevron to tap + hold +* Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail. +* Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel. +* Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state. + ## 1.3.3 - 3/4/2026 - Fix unread counts and dot badges for muted rooms ([#118](https://github.com/7w1/sable/pull/118)) - [Evie Gauthier](https://github.com/Just-Insane) diff --git a/package-lock.json b/package-lock.json index 811f037d..d8254635 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sable", - "version": "1.3.3", + "version": "1.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "sable", - "version": "1.3.3", + "version": "1.4.0", "hasInstallScript": true, "license": "AGPL-3.0-only", "dependencies": { @@ -26870,4 +26870,4 @@ "dev": true } } -} +} \ No newline at end of file diff --git a/package.json b/package.json index 7be46b1a..233e6f71 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sable", - "version": "1.3.3", + "version": "1.4.0", "description": "Yet another matrix client fork", "type": "module", "packageManager": "npm@11.11.0", @@ -120,4 +120,4 @@ "vite-plugin-top-level-await": "^1.6.0", "wrangler": "^4.70.0" } -} +} \ No newline at end of file From af26eebd59403d69b248626bfa3fd6924b012b34 Mon Sep 17 00:00:00 2001 From: Sylvie Fox Date: Fri, 6 Mar 2026 00:11:24 -0700 Subject: [PATCH 044/124] fix version to match latest release --- src/app/pages/client/WelcomePage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/pages/client/WelcomePage.tsx b/src/app/pages/client/WelcomePage.tsx index 049de5c0..3dbfa1da 100644 --- a/src/app/pages/client/WelcomePage.tsx +++ b/src/app/pages/client/WelcomePage.tsx @@ -19,7 +19,7 @@ export function WelcomePage() { Yet another matrix client fork.{' '}
- v1.3.3 + v1.4.0 } From b0d568ff404a7d9ebade669fb4e884a78c6dbe09 Mon Sep 17 00:00:00 2001 From: Sylvie Fox Date: Fri, 6 Mar 2026 00:12:59 -0700 Subject: [PATCH 045/124] fix version to match latest release --- src/app/pages/auth/AuthFooter.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/pages/auth/AuthFooter.tsx b/src/app/pages/auth/AuthFooter.tsx index 3f8f5c04..e96b5cc4 100644 --- a/src/app/pages/auth/AuthFooter.tsx +++ b/src/app/pages/auth/AuthFooter.tsx @@ -14,7 +14,7 @@ export function AuthFooter() { target="_blank" rel="noreferrer" > - v1.3.3 + v1.4.0 Powered by Matrix From e713f19ac7d85287c00b107c808f1575b56eedc1 Mon Sep 17 00:00:00 2001 From: Bea Date: Fri, 6 Mar 2026 13:26:13 +0000 Subject: [PATCH 046/124] fix: source version from APP_VERSION instead of hard coding --- src/app/pages/auth/AuthFooter.tsx | 2 +- src/app/pages/client/WelcomePage.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/pages/auth/AuthFooter.tsx b/src/app/pages/auth/AuthFooter.tsx index e96b5cc4..761a690d 100644 --- a/src/app/pages/auth/AuthFooter.tsx +++ b/src/app/pages/auth/AuthFooter.tsx @@ -14,7 +14,7 @@ export function AuthFooter() { target="_blank" rel="noreferrer" > - v1.4.0 + v{APP_VERSION} Powered by Matrix diff --git a/src/app/pages/client/WelcomePage.tsx b/src/app/pages/client/WelcomePage.tsx index 3dbfa1da..34504ee9 100644 --- a/src/app/pages/client/WelcomePage.tsx +++ b/src/app/pages/client/WelcomePage.tsx @@ -19,7 +19,7 @@ export function WelcomePage() { Yet another matrix client fork.{' '} - v1.4.0 + v{APP_VERSION} } From 51072d2b72acd6e40cbf260ca1996c3ab5fc98c3 Mon Sep 17 00:00:00 2001 From: Trash Panda Date: Fri, 6 Mar 2026 07:41:31 -0700 Subject: [PATCH 047/124] Document changes --- ...eviews_in_url_previews_and_reuse_attachment_components.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md diff --git a/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md b/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md new file mode 100644 index 00000000..ae79ae01 --- /dev/null +++ b/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Add support for audio and video in URL previews From b1d5844da86418f8487bddb8a5a303f50162a6b1 Mon Sep 17 00:00:00 2001 From: Bea Date: Fri, 6 Mar 2026 13:41:55 +0000 Subject: [PATCH 048/124] feat: show dev version with commit hash when not on a release tag --- .github/workflows/docker-publish.yml | 1 + Dockerfile | 2 ++ src/app/features/settings/about/About.tsx | 3 ++- src/app/pages/auth/AuthFooter.tsx | 2 +- src/app/pages/client/WelcomePage.tsx | 2 +- src/ext.d.ts | 1 + vite.config.ts | 12 ++++++++++++ 7 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index c25e47d9..79becac5 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -85,6 +85,7 @@ jobs: cache-to: type=gha,mode=max build-args: | VITE_BUILD_HASH=${{ steps.vars.outputs.short_sha }} + VITE_IS_RELEASE_TAG=${{ steps.release_tag.outputs.is_release }} - name: Generate artifact attestation uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0 diff --git a/Dockerfile b/Dockerfile index 863b2ba7..1be07f4a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,9 @@ FROM --platform=$BUILDPLATFORM node:24.13.1-alpine AS builder WORKDIR /src ARG VITE_BUILD_HASH +ARG VITE_IS_RELEASE_TAG=false ENV VITE_BUILD_HASH=$VITE_BUILD_HASH +ENV VITE_IS_RELEASE_TAG=$VITE_IS_RELEASE_TAG COPY .npmrc package.json package-lock.json /src/ RUN npm ci --ignore-scripts diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index d51cae0d..abeec4ae 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -147,6 +147,7 @@ type AboutProps = { }; export function About({ requestClose }: AboutProps) { const mx = useMatrixClient(); + const devLabel = IS_RELEASE_TAG ? '' : '-dev'; const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : ''; return ( @@ -181,7 +182,7 @@ export function About({ requestClose }: AboutProps) { Sable - {`v${APP_VERSION}${buildLabel}`} + {`v${APP_VERSION}${devLabel}${buildLabel}`} Yet another matrix client fork(ed from cinny). diff --git a/src/app/pages/auth/AuthFooter.tsx b/src/app/pages/auth/AuthFooter.tsx index 761a690d..2e8db057 100644 --- a/src/app/pages/auth/AuthFooter.tsx +++ b/src/app/pages/auth/AuthFooter.tsx @@ -14,7 +14,7 @@ export function AuthFooter() { target="_blank" rel="noreferrer" > - v{APP_VERSION} + {`v${APP_VERSION}${IS_RELEASE_TAG ? '' : `-dev${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`}`} Powered by Matrix diff --git a/src/app/pages/client/WelcomePage.tsx b/src/app/pages/client/WelcomePage.tsx index 34504ee9..345bb118 100644 --- a/src/app/pages/client/WelcomePage.tsx +++ b/src/app/pages/client/WelcomePage.tsx @@ -19,7 +19,7 @@ export function WelcomePage() { Yet another matrix client fork.{' '} - v{APP_VERSION} + {`v${APP_VERSION}${IS_RELEASE_TAG ? '' : `-dev${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`}`} } diff --git a/src/ext.d.ts b/src/ext.d.ts index 2dcdcd1c..7ee0a20a 100644 --- a/src/ext.d.ts +++ b/src/ext.d.ts @@ -2,6 +2,7 @@ declare const APP_VERSION: string; declare const BUILD_HASH: string; +declare const IS_RELEASE_TAG: boolean; declare module 'browser-encrypt-attachment' { export interface EncryptedAttachmentInfo { diff --git a/vite.config.ts b/vite.config.ts index ab5757c2..983f0ad7 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -46,6 +46,17 @@ const resolveBuildHash = (): string | undefined => { const appVersion = packageJson.version; const buildHash = resolveBuildHash(); +const isReleaseTag = (() => { + const envVal = process.env.VITE_IS_RELEASE_TAG; + if (envVal !== undefined && envVal !== '') return envVal === 'true'; + try { + const tag = execSync('git describe --exact-match --tags HEAD 2>/dev/null').toString().trim(); + return tag.startsWith('sable/v'); + } catch { + return false; + } +})(); + const copyFiles = { targets: [ { @@ -112,6 +123,7 @@ export default defineConfig({ define: { APP_VERSION: JSON.stringify(appVersion), BUILD_HASH: JSON.stringify(buildHash ?? ''), + IS_RELEASE_TAG: JSON.stringify(isReleaseTag), }, resolve: { alias: { From 80e049fc5eaeae6de79a56f3a0f7fb6b1f92e525 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Fri, 6 Mar 2026 10:10:22 -0500 Subject: [PATCH 049/124] fix(notifications): banner default off on desktop, show for DMs, fix space navigation --- CHANGELOG.md | 3 +++ src/app/hooks/useNotificationJumper.ts | 23 +++++++++++++++++--- src/app/pages/client/ClientNonUIFeatures.tsx | 11 +++++++--- src/app/state/settings.ts | 5 ++--- 4 files changed, 33 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a183e8c..54ee1933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,9 @@ * Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail. * Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel. * Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state. +* In-app notification banners now appear for DMs by default, even without a mention or keyword match. +* Notification banner on desktop now defaults to off, consistent with push notification defaults. +* Fixed space room navigation when tapping an in-app notification banner for a room inside a space. ## 1.3.3 - 3/4/2026 diff --git a/src/app/hooks/useNotificationJumper.ts b/src/app/hooks/useNotificationJumper.ts index c0610527..6f7c7768 100644 --- a/src/app/hooks/useNotificationJumper.ts +++ b/src/app/hooks/useNotificationJumper.ts @@ -7,13 +7,15 @@ import { mDirectAtom } from '../state/mDirectList'; import { useSyncState } from './useSyncState'; import { useMatrixClient } from './useMatrixClient'; import { getCanonicalAliasOrRoomId } from '../utils/matrix'; -import { getDirectRoomPath, getHomeRoomPath } from '../pages/pathUtils'; +import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '../pages/pathUtils'; +import { roomToParentsAtom } from '../state/room/roomToParents'; import { createLogger } from '../utils/debug'; export function NotificationJumper() { const [pending, setPending] = useAtom(pendingNotificationAtom); const activeSessionId = useAtomValue(activeSessionIdAtom); const mDirects = useAtomValue(mDirectAtom); + const roomToParents = useAtomValue(roomToParentsAtom); const mx = useMatrixClient(); const navigate = useNavigate(); const log = createLogger('NotificationJumper'); @@ -57,7 +59,22 @@ export function NotificationJumper() { if (mDirects.has(pending.roomId)) { navigate(getDirectRoomPath(roomIdOrAlias, pending.eventId)); } else { - navigate(getHomeRoomPath(roomIdOrAlias, pending.eventId)); + // If the room lives inside a space, route through the space path so + // SpaceRouteRoomProvider can resolve it — HomeRouteRoomProvider only + // knows orphan rooms and would show JoinBeforeNavigate otherwise. + const parents = roomToParents.get(pending.roomId); + const firstParentId = parents && [...parents][0]; + if (firstParentId) { + navigate( + getSpaceRoomPath( + getCanonicalAliasOrRoomId(mx, firstParentId), + roomIdOrAlias, + pending.eventId + ) + ); + } else { + navigate(getHomeRoomPath(roomIdOrAlias, pending.eventId)); + } } setPending(null); // jumpingRef stays true until pending changes — see effect below. @@ -68,7 +85,7 @@ export function NotificationJumper() { membership: room?.getMyMembership(), }); } - }, [pending, activeSessionId, mx, mDirects, navigate, setPending, log]); + }, [pending, activeSessionId, mx, mDirects, roomToParents, navigate, setPending, log]); // Reset the guard only when pending is replaced (new notification or cleared). useEffect(() => { diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index b2a01319..02f175ab 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -16,6 +16,7 @@ import { notificationPermission, setFavicon } from '$utils/dom'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { nicknamesAtom } from '$state/nicknames'; +import { mDirectAtom } from '$state/mDirectList'; import { allInvitesAtom } from '$state/room-list/inviteList'; import { usePreviousValue } from '$hooks/usePreviousValue'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -217,6 +218,9 @@ function MessageNotifications() { const nicknames = useAtomValue(nicknamesAtom); const nicknamesRef = useRef(nicknames); nicknamesRef.current = nicknames; + const mDirects = useAtomValue(mDirectAtom); + const mDirectsRef = useRef(mDirects); + mDirectsRef.current = mDirects; const setPending = useSetAtom(pendingNotificationAtom); const setInAppBanner = useSetAtom(inAppBannerAtom); @@ -283,9 +287,10 @@ function MessageNotifications() { if (!pushActions?.notify) return; const loudByRule = Boolean(pushActions.tweaks?.sound); const isHighlightByRule = Boolean(pushActions.tweaks?.highlight); + const isDM = mDirectsRef.current.has(room.roomId); - // If neither a loud nor a highlight rule matches, nothing to show. - if (!isHighlightByRule && !loudByRule) return; + // If neither a loud nor a highlight rule matches, and it's not a DM, nothing to show. + if (!isHighlightByRule && !loudByRule && !isDM) return; // Page hidden: SW (push) handles the OS notification. Nothing to do in-app. if (document.visibilityState !== 'visible') return; @@ -299,7 +304,7 @@ function MessageNotifications() { // Page is visible — show the themed in-app notification banner for any // highlighted message (mention / keyword) or loud push rule. - if (mobileOrTablet() && (isHighlightByRule || loudByRule) && showNotifications) { + if (showNotifications && (isHighlightByRule || loudByRule || isDM)) { const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 790733ae..f845afa1 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -107,11 +107,10 @@ const defaultSettings: Settings = { legacyUsernameColor: false, // Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop. - // In-app pill banner: always on — it's the primary foreground alert on mobile - // and a useful secondary alert on desktop. + // In-app pill banner: default on for mobile (primary foreground alert), opt-in on desktop. // System (OS) notifications: desktop-only; hidden and disabled on mobile. usePushNotifications: mobileOrTablet(), - useInAppNotifications: true, + useInAppNotifications: mobileOrTablet(), useSystemNotifications: !mobileOrTablet(), isNotificationSounds: true, showMessageContentInNotifications: false, From a45365f28a1bab385c5d0c6cbbe7669af186eada Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Fri, 6 Mar 2026 10:10:28 -0500 Subject: [PATCH 050/124] chore: add changeset --- .changeset/notification_banner_dm_default.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/notification_banner_dm_default.md diff --git a/.changeset/notification_banner_dm_default.md b/.changeset/notification_banner_dm_default.md new file mode 100644 index 00000000..e9355419 --- /dev/null +++ b/.changeset/notification_banner_dm_default.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +In-app notification banners now appear for DMs by default; desktop banner setting defaults to off; fixed space room navigation from banner tap. From c210ab7f7e0b22f129baa33d5cdd47185ccb312c Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Fri, 6 Mar 2026 10:10:43 -0500 Subject: [PATCH 051/124] fix(timeline): prefer room-scoped member avatar over global profile --- CHANGELOG.md | 1 + src/app/features/room/message/Message.tsx | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a183e8c..1d9a00a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ * Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail. * Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel. * Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state. +* Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile when set via `/myroomavatar` or `/myroomnick`. ## 1.3.3 - 3/4/2026 diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 4558a042..6b62a51c 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -341,9 +341,11 @@ function MessageInternal( const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); // Avatars + // Prefer the room-scoped member avatar (m.room.member) over the global profile + // avatar so per-room avatar overrides are respected in the timeline. const avatarUrl = useMemo(() => { if (collapse) return undefined; - const mxc = profile.avatarUrl || getMemberAvatarMxc(room, senderId); + const mxc = getMemberAvatarMxc(room, senderId) || profile.avatarUrl; return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined; }, [collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]); From 9d0590f44425885ccdcf6490f042c2e593631ca5 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Fri, 6 Mar 2026 10:10:50 -0500 Subject: [PATCH 052/124] chore: add changeset --- .changeset/member_avatar_room_scope.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/member_avatar_room_scope.md diff --git a/.changeset/member_avatar_room_scope.md b/.changeset/member_avatar_room_scope.md new file mode 100644 index 00000000..7d419fd8 --- /dev/null +++ b/.changeset/member_avatar_room_scope.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile, when set via `/myroomavatar` or `/myroomnick`. From 7af4ee5c7c0bf67a474af6b18b02958e8b424f8d Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 17:21:51 +0100 Subject: [PATCH 053/124] disable spellcheck and auto correct on login items (username and homeserver address) --- src/app/pages/auth/ServerPicker.tsx | 3 +++ src/app/pages/auth/login/PasswordLoginForm.tsx | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/app/pages/auth/ServerPicker.tsx b/src/app/pages/auth/ServerPicker.tsx index 10dddb7d..12dfa175 100644 --- a/src/app/pages/auth/ServerPicker.tsx +++ b/src/app/pages/auth/ServerPicker.tsx @@ -91,6 +91,9 @@ export function ServerPicker({ onClick={allowCustomServer ? undefined : handleOpenServerMenu} // disable auto-capitalization, which is usually undesirable for server name input. autoCapitalize="off" + // disable spell-check and auto-correction + spellCheck={false} + autoCorrect="off" after={ serverList.length === 0 || (serverList.length === 1 && !allowCustomServer) ? undefined : ( } /> {loginState.status === AsyncStatus.Error && ( From 69dbd34e00a312d2ee199593a8f909629575a78d Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 17:28:02 +0100 Subject: [PATCH 054/124] added changeset --- .changeset/fix_autocorrectspellcheck_issue_on_login_page.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix_autocorrectspellcheck_issue_on_login_page.md diff --git a/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md b/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md new file mode 100644 index 00000000..08ce2f28 --- /dev/null +++ b/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Disable autocorrect and spellcheck on the login page. \ No newline at end of file From 389c891de9878c366c71f47cf907c67f1f379258 Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 17:29:52 +0100 Subject: [PATCH 055/124] fixup! added changeset --- .changeset/fix_autocorrectspellcheck_issue_on_login_page.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md b/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md index 08ce2f28..9852f7cf 100644 --- a/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md +++ b/.changeset/fix_autocorrectspellcheck_issue_on_login_page.md @@ -2,4 +2,4 @@ sable: patch --- -Disable autocorrect and spellcheck on the login page. \ No newline at end of file +Disable autocorrect and spellcheck on the login page. From cd97283a86e045428db85b3bb143fb0bc8b4627c Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 10:42:42 -0600 Subject: [PATCH 056/124] revert changelog changes Updated changelog with new features and fixes for version 1.3.3. --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d9a00a9..2a183e8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,6 @@ * Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail. * Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel. * Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state. -* Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile when set via `/myroomavatar` or `/myroomnick`. ## 1.3.3 - 3/4/2026 From f17993372137d3da0276b59461ab6afe7e79db6c Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 12:35:18 -0600 Subject: [PATCH 057/124] update change set to mention homeserver requirement --- ..._previews_in_url_previews_and_reuse_attachment_components.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md b/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md index ae79ae01..f176d8de 100644 --- a/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md +++ b/.changeset/add_support_for_audio_and_video_previews_in_url_previews_and_reuse_attachment_components.md @@ -2,4 +2,4 @@ sable: minor --- -Add support for audio and video in URL previews +Add support for audio and video in URL previews if homeserver provides it. From 672b88d4a56748e113dd7bb57d72534dfc559874 Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 21:00:12 +0100 Subject: [PATCH 058/124] stub for message forwarding menu item --- src/app/features/room/message/Message.tsx | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 6b62a51c..988e2436 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -155,6 +155,35 @@ export const MessageCopyLinkItem = as< ); }); +// MessageForwardItem is for forwarding a message to another room +export const MessageForwardItem = as< + 'button', + { + room: Room; + mEvent: MatrixEvent; + onClose?: () => void; + } +>(({ room, mEvent, onClose, ...props }, ref) => { + const mx = useMatrixClient(); + + // TODO: replace icon + return ( + } + radii="300" + onClick={handleForward} + {...props} + ref={ref} + > + + Forward Message + + + ); +}); + +// message pinning export const MessagePinItem = as< 'button', { @@ -812,6 +841,7 @@ function MessageInternal( )} + {canPinEvent && ( )} @@ -1100,6 +1130,7 @@ export const Event = as<'div', EventProps>( )} + {((!mEvent.isRedacted() && canDelete && !stateEvent) || (mEvent.getSender() !== mx.getUserId() && !stateEvent)) && ( From d1c0ca78524041619d4f9f4d3fa51a8f20b21fda Mon Sep 17 00:00:00 2001 From: Joop Kiefte Date: Fri, 6 Mar 2026 20:01:10 +0000 Subject: [PATCH 059/124] fix: Element Call DM video calls + delayed event methods + post-lobby reload (port from Wally) - getCallIntentParams: voice rooms use join_existing/audio, DM rooms use start_call/video, group rooms use start_call/audio; intent param is now correctly passed to EC URL - SmallWidgetDriver: replace updateDelayedEvent with the three specific methods (cancelScheduledDelayedEvent, restartScheduledDelayedEvent, sendScheduledDelayedEvent) that ClientWidgetApi actually dispatches; fixes 'Connection lost' for all users - Post-lobby reload: after io.element.join, poll MatrixRTCSession.callMembershipsForRoom every 200ms; once EC's call member state event propagates, reload EC with intent=join_existing + skipLobby=true so it auto-joins the existing session and shows the full in-call grid instead of just the control bar; hangs up after 10s timeout - Fix registerActiveClientWidgetApi interface: clientWidget/iframeRef are nullable - Add resetActiveCallReady to CallProvider context --- src/app/features/call/SmallWidget.ts | 20 ++++++ src/app/features/call/SmallWidgetDriver.ts | 22 +++++-- src/app/pages/client/call/CallProvider.tsx | 11 +++- .../client/call/PersistentCallContainer.tsx | 61 +++++++++++++++++-- 4 files changed, 101 insertions(+), 13 deletions(-) diff --git a/src/app/features/call/SmallWidget.ts b/src/app/features/call/SmallWidget.ts index 24791198..63186862 100644 --- a/src/app/features/call/SmallWidget.ts +++ b/src/app/features/call/SmallWidget.ts @@ -15,6 +15,7 @@ import { MatrixClient, MatrixEvent, MatrixEventEvent, + Room, RoomStateEvent, } from '$types/matrix-sdk'; import { @@ -33,6 +34,25 @@ import { SmallWidgetDriver } from './SmallWidgetDriver'; const log = createLogger('SmallWidget'); +/** + * Returns the appropriate EC `intent` and `callIntent` URL params for a room. + * - Voice rooms (`isCallRoom()`): `join_existing` intent, `audio` callType (persistent channel). + * - DM rooms (≤2 joined members): `start_call` intent, `video` callType (1:1 video call). + * - Group rooms: `start_call` intent, `audio` callType. + */ +export function getCallIntentParams(room: Room | null | undefined): { + intent: 'join_existing' | 'start_call'; + callIntentParam: 'audio' | 'video'; +} { + const isVoiceRoom = room?.isCallRoom() ?? false; + // Require room to be non-null: unknown/missing room should not be treated as a DM. + const isDmRoom = room != null && !isVoiceRoom && room.currentState.getJoinedMemberCount() <= 2; + return { + intent: isVoiceRoom ? 'join_existing' : 'start_call', + callIntentParam: isDmRoom ? 'video' : 'audio', + }; +} + /** * Generates the URL for the Element Call widget. * @param mx - The MatrixClient instance. diff --git a/src/app/features/call/SmallWidgetDriver.ts b/src/app/features/call/SmallWidgetDriver.ts index 29f441cf..467adbb5 100644 --- a/src/app/features/call/SmallWidgetDriver.ts +++ b/src/app/features/call/SmallWidgetDriver.ts @@ -295,16 +295,26 @@ export class SmallWidgetDriver extends WidgetDriver { /** * @experimental Part of MSC4140 & MSC4157 + * ClientWidgetApi dispatches three specific actions; the base WidgetDriver.updateDelayedEvent + * is never called. Implementing all three prevents 'Failed to override function' errors and + * the resulting 'Connection lost' in Element Call's MembershipManager. */ - public async updateDelayedEvent( - delayId: string, - action: UpdateDelayedEventAction - ): Promise { + public async cancelScheduledDelayedEvent(delayId: string): Promise { const client = this.mxClient; - if (!client) throw new Error('Not in a room or not attached to a client'); + await client._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel); + } - await client._unstable_updateDelayedEvent(delayId, action); + public async restartScheduledDelayedEvent(delayId: string): Promise { + const client = this.mxClient; + if (!client) throw new Error('Not in a room or not attached to a client'); + await client._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart); + } + + public async sendScheduledDelayedEvent(delayId: string): Promise { + const client = this.mxClient; + if (!client) throw new Error('Not in a room or not attached to a client'); + await client._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Send); } /** diff --git a/src/app/pages/client/call/CallProvider.tsx b/src/app/pages/client/call/CallProvider.tsx index 69aa3bdb..e484a0bf 100644 --- a/src/app/pages/client/call/CallProvider.tsx +++ b/src/app/pages/client/call/CallProvider.tsx @@ -35,8 +35,8 @@ interface CallContextState { registerActiveClientWidgetApi: ( roomId: string | null, clientWidgetApi: ClientWidgetApi | null, - clientWidget: SmallWidget, - activeClientIframeRef: HTMLIFrameElement + clientWidget: SmallWidget | null, + activeClientIframeRef: HTMLIFrameElement | null ) => void; sendWidgetAction: ( action: WidgetApiToWidgetAction | string, @@ -46,6 +46,7 @@ interface CallContextState { isVideoEnabled: boolean; isChatOpen: boolean; isActiveCallReady: boolean; + resetActiveCallReady: () => void; toggleAudio: () => Promise; toggleVideo: () => Promise; toggleChat: () => Promise; @@ -280,6 +281,10 @@ export function CallProvider({ children }: CallProviderProps) { sendWidgetAction, ]); + const resetActiveCallReady = useCallback(() => { + setIsActiveCallReady(false); + }, []); + const toggleChat = useCallback(async () => { const newState = !isChatOpen; setIsChatOpenState(newState); @@ -300,6 +305,7 @@ export function CallProvider({ children }: CallProviderProps) { isAudioEnabled, isVideoEnabled, isActiveCallReady, + resetActiveCallReady, toggleAudio, toggleVideo, toggleChat, @@ -318,6 +324,7 @@ export function CallProvider({ children }: CallProviderProps) { isAudioEnabled, isVideoEnabled, isActiveCallReady, + resetActiveCallReady, toggleAudio, toggleVideo, toggleChat, diff --git a/src/app/pages/client/call/PersistentCallContainer.tsx b/src/app/pages/client/call/PersistentCallContainer.tsx index 31809786..a8b57a40 100644 --- a/src/app/pages/client/call/PersistentCallContainer.tsx +++ b/src/app/pages/client/call/PersistentCallContainer.tsx @@ -8,12 +8,14 @@ import { useRef, } from 'react'; import { ClientWidgetApi } from 'matrix-widget-api'; +import { MatrixRTCSession } from 'matrix-js-sdk/lib/matrixrtc/MatrixRTCSession'; import { Box } from 'folds'; import { createVirtualWidget, SmallWidget, getWidgetData, getWidgetUrl, + getCallIntentParams, } from '$features/call/SmallWidget'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useClientConfig } from '$hooks/useClientConfig'; @@ -33,6 +35,9 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro const callIframeRef = useRef(null); const callWidgetApiRef = useRef(null); const callSmallWidgetRef = useRef(null); + // After a non-voice room lobby join, reload EC with join_existing for proper in-call view. + const hasReloadedAfterLobbyRef = useRef(false); + const postLobbyIntentRef = useRef<'join_existing' | null>(null); const { activeCallRoomId, @@ -41,6 +46,8 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro isActiveCallReady, registerActiveClientWidgetApi, activeClientWidget, + resetActiveCallReady, + hangUp, } = useCallState(); const mx = useMatrixClient(); const clientConfig = useClientConfig(); @@ -56,11 +63,15 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro smallWidgetRef: MutableRefObject, iframeRef: MutableRefObject, skipLobby: boolean, - themeKind: ThemeKind | null + themeKind: ThemeKind | null, + intentOverride?: 'join_existing' ) => { if (mx?.getUserId()) { if (activeCallRoomId && !isActiveCallReady) { const roomIdToSet = activeCallRoomId; + const room = mx.getRoom(roomIdToSet); + const { intent: intentParam, callIntentParam } = getCallIntentParams(room); + const effectiveIntent = intentOverride ?? intentParam; const widgetId = `element-call-${roomIdToSet}-${Date.now()}`; const newUrl = getWidgetUrl( @@ -69,11 +80,12 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro clientConfig.elementCallUrl ?? '', widgetId, { - skipLobby: skipLobby.toString(), + skipLobby: (intentOverride === 'join_existing' ? true : skipLobby).toString(), returnToLobby: 'true', perParticipantE2EE: 'true', theme: themeKind, - callIntent: 'audio', + intent: effectiveIntent, + callIntent: callIntentParam, } ); @@ -106,7 +118,7 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro 'm.call', newUrl, false, - getWidgetData(mx, roomIdToSet, {}, { skipLobby: true, callIntent: 'audio' }), + getWidgetData(mx, roomIdToSet, {}, { skipLobby: true, intent: effectiveIntent, callIntent: callIntentParam }), roomIdToSet ); @@ -134,9 +146,48 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro ] ); + // After a non-voice room lobby join, poll until EC's call member state event has propagated + // to the room, then reload EC with intent=join_existing + skipLobby=true so it auto-joins + // the existing session and shows the full in-call grid. Hangs up if the session never + // appears (e.g. EC failed to send its state event) to avoid leaving the user stuck. + useEffect(() => { + if (!activeCallRoomId) { + hasReloadedAfterLobbyRef.current = false; + return undefined; + } + if (isActiveCallReady && !hasReloadedAfterLobbyRef.current) { + const room = mx?.getRoom(activeCallRoomId); + // Voice rooms already use join_existing and work correctly; skip reload for them. + if (room && !room.isCallRoom()) { + hasReloadedAfterLobbyRef.current = true; + const POLL_INTERVAL_MS = 200; + const TIMEOUT_MS = 10000; + const startTime = Date.now(); + const pollTimer = setInterval(() => { + if (MatrixRTCSession.callMembershipsForRoom(room).length > 0) { + clearInterval(pollTimer); + callSmallWidgetRef.current?.stopMessaging(); + callWidgetApiRef.current = null; + callSmallWidgetRef.current = null; + registerActiveClientWidgetApi(activeCallRoomId, null, null, null); + postLobbyIntentRef.current = 'join_existing'; + resetActiveCallReady(); + } else if (Date.now() - startTime >= TIMEOUT_MS) { + clearInterval(pollTimer); + hangUp(); + } + }, POLL_INTERVAL_MS); + return () => clearInterval(pollTimer); + } + } + return undefined; + }, [isActiveCallReady, activeCallRoomId, mx, registerActiveClientWidgetApi, resetActiveCallReady, hangUp]); + useEffect(() => { if (activeCallRoomId) { - setupWidget(callWidgetApiRef, callSmallWidgetRef, callIframeRef, true, theme.kind); + const intentOverride = postLobbyIntentRef.current ?? undefined; + postLobbyIntentRef.current = null; + setupWidget(callWidgetApiRef, callSmallWidgetRef, callIframeRef, true, theme.kind, intentOverride); } }, [ theme, From 6b6b7f4ed0593497bd58410584dfcc8ba0362d1e Mon Sep 17 00:00:00 2001 From: Jason Beetham Date: Fri, 6 Mar 2026 11:54:59 -0700 Subject: [PATCH 060/124] Add setting to disable element-call's disabling of picture in picture --- ...nable_picture_in_picture_in_element_call.md | 5 +++++ src/app/features/call/CallView.tsx | 18 ++++++++++++++++++ .../features/settings/cosmetics/Cosmetics.tsx | 18 ++++++++++++++++++ src/app/state/settings.ts | 2 ++ 4 files changed, 43 insertions(+) create mode 100644 .changeset/add_setting_to_enable_picture_in_picture_in_element_call.md diff --git a/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md new file mode 100644 index 00000000..46bb9966 --- /dev/null +++ b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +# Add setting to enable picture-in-picture in element-call diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx index 485cd331..c845e80c 100644 --- a/src/app/features/call/CallView.tsx +++ b/src/app/features/call/CallView.tsx @@ -26,6 +26,8 @@ import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { useRoomName } from '$hooks/useRoomMeta'; import { useAtomValue } from 'jotai'; import { nicknamesAtom } from '$state/nicknames'; +import { settingsAtom } from '$state/settings'; +import { useSetting } from '$state/hooks/settings'; import * as css from './CallView.css'; import { CallViewUser } from './CallViewUser'; @@ -138,10 +140,25 @@ export function CallView({ room }: { room: Room }) { wait: 50, immediate: false, }); + + const [allowPipVideos] = useSetting(settingsAtom, 'allowPipVideos'); + useEffect(() => { const iframeElement = activeIframeDisplayRef?.current; const hostElement = iframeHostRef?.current; + if (allowPipVideos) { + const removeDisablePictureInPicture = (mutated: any) => { + mutated.forEach((event: any) => { + Array.from(event.target.getElementsByTagName('video')).forEach((video: any) => { + video.removeAttribute('disablepictureinpicture'); + }); + }); + }; + const pipObserver = new MutationObserver(removeDisablePictureInPicture); + pipObserver.observe(iframeElement?.contentDocument!, { subtree: true, childList: true }); + } + if (room.isCallRoom() || (callIsCurrentAndReady && iframeElement && hostElement)) { applyFixedPositioningToIframe(); @@ -172,6 +189,7 @@ export function CallView({ room }: { room: Room }) { debouncedApplyFixedPositioning, callIsCurrentAndReady, room, + allowPipVideos, ]); const handleJoinVCClick: MouseEventHandler = (evt) => { diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index d39d3a2a..0e2f555e 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -240,6 +240,23 @@ function IdentityCosmetics() { ); } +function VideoCosmetics() { + const [allowPipVideos, setPipVideos] = useSetting(settingsAtom, 'allowPipVideos'); + + return ( + + Video + + } + /> + + + ); +} + type CosmeticsProps = { requestClose: () => void; }; @@ -269,6 +286,7 @@ export function Cosmetics({ requestClose }: CosmeticsProps) { + diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index f845afa1..318485b0 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -43,6 +43,7 @@ export interface Settings { encUrlPreview: boolean; showHiddenEvents: boolean; legacyUsernameColor: boolean; + allowPipVideos: boolean; usePushNotifications: boolean; useInAppNotifications: boolean; @@ -105,6 +106,7 @@ const defaultSettings: Settings = { encUrlPreview: false, showHiddenEvents: false, legacyUsernameColor: false, + allowPipVideos: false, // Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop. // In-app pill banner: default on for mobile (primary foreground alert), opt-in on desktop. From c6c8a9aaf68f728f1b80d28f182ec039b1a46c63 Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 21:32:17 +0100 Subject: [PATCH 061/124] stub implement message forwarding functionality with modal integration --- .../message/modals/GlobalModalManager.tsx | 7 ++ .../message/modals/MessageForward.tsx | 70 +++++++++++++++++++ src/app/features/room/message/Message.tsx | 29 +------- src/app/state/modal.ts | 3 + 4 files changed, 81 insertions(+), 28 deletions(-) create mode 100644 src/app/components/message/modals/MessageForward.tsx diff --git a/src/app/components/message/modals/GlobalModalManager.tsx b/src/app/components/message/modals/GlobalModalManager.tsx index e01c73bb..5245e98b 100644 --- a/src/app/components/message/modals/GlobalModalManager.tsx +++ b/src/app/components/message/modals/GlobalModalManager.tsx @@ -6,6 +6,7 @@ import { modalAtom, ModalType } from '$state/modal'; import { MessageReportInternal } from './MessageReport'; import { MessageDeleteInternal } from './MessageDelete'; import { MessageSourceInternal } from './MessageSource'; +import { MessageForwardInternal } from './MessageForward'; import { MessageAllReactionInternal } from './MessageReactions'; import { MessageReadReceiptInternal } from './MessageReadRecipts'; @@ -40,6 +41,12 @@ export function GlobalModalManager() { )} + {modal.type === ModalType.Forward && ( + + + + )} + {modal.type === ModalType.Source && ( diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx new file mode 100644 index 00000000..891daee1 --- /dev/null +++ b/src/app/components/message/modals/MessageForward.tsx @@ -0,0 +1,70 @@ +// Modal for message forwarding, which allows users to select a room to forward the message to + +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { modalAtom, ModalType } from '$state/modal'; +import { Avatar, Box, Button, Dialog, Header, Icon, Icons, IconButton, MenuItem, Text, config } from 'folds'; +import { useSetAtom } from 'jotai'; +import { MatrixEvent, Room } from '$types/matrix-sdk'; + +// Message forwarding component +export function MessageForwardItem({ + room, + mEvent, + onClose, +}: { + room: Room; + mEvent: MatrixEvent; + onClose: () => void; +}) { + const setModal = useSetAtom(modalAtom); + + const handleClick = () => { + setModal({ + type: ModalType.Forward, + room, + mEvent, + }); + onClose(); + }; + + return ( + } + radii="300" + onClick={handleClick} + > + + Forward + + + ); +} + +type MessageForwardInternalProps = { + room: Room; + mEvent: MatrixEvent; + onClose: () => void; +}; + +export function MessageForwardInternal({ room, mEvent, onClose }: MessageForwardInternalProps) { + return ( + +
+ + Forward Message + + + + +
+
+ ); +} diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 988e2436..0ea8c29f 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -75,6 +75,7 @@ import { useBlobCache } from '$hooks/useBlobCache'; import { MessageAllReactionItem } from '$components/message/modals/MessageReactions'; import { MessageReadReceiptItem } from '$components/message/modals/MessageReadRecipts'; import { MessageSourceCodeItem } from '$components/message/modals/MessageSource'; +import { MessageForwardItem } from '$components/message/modals/MessageForward'; import { MessageDeleteItem } from '$components/message/modals/MessageDelete'; import { MessageReportItem } from '$components/message/modals/MessageReport'; import { filterPronounsByLanguage } from '$utils/pronouns'; @@ -155,34 +156,6 @@ export const MessageCopyLinkItem = as< ); }); -// MessageForwardItem is for forwarding a message to another room -export const MessageForwardItem = as< - 'button', - { - room: Room; - mEvent: MatrixEvent; - onClose?: () => void; - } ->(({ room, mEvent, onClose, ...props }, ref) => { - const mx = useMatrixClient(); - - // TODO: replace icon - return ( - } - radii="300" - onClick={handleForward} - {...props} - ref={ref} - > - - Forward Message - - - ); -}); - // message pinning export const MessagePinItem = as< 'button', diff --git a/src/app/state/modal.ts b/src/app/state/modal.ts index 1d16cfe8..c4f4cf79 100644 --- a/src/app/state/modal.ts +++ b/src/app/state/modal.ts @@ -3,6 +3,8 @@ import { MatrixEvent, Room, Relations } from '$types/matrix-sdk'; export enum ModalType { Delete = 'delete', + // for forwarding a message to another room, not to be confused with the "share" action which is for sharing a message to another app + Forward = 'forward', Report = 'report', Source = 'source', Reactions = 'reactions', @@ -11,6 +13,7 @@ export enum ModalType { export type ModalState = | { type: ModalType.Delete; room: Room; mEvent: MatrixEvent } + | { type: ModalType.Forward; room: Room; mEvent: MatrixEvent } | { type: ModalType.Report; room: Room; mEvent: MatrixEvent } | { type: ModalType.Source; room: Room; mEvent: MatrixEvent } | { type: ModalType.Reactions; room: Room; relations: Relations } From 1cfdd94dc0924eec6f57b0e2553c3208ed6de9fe Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 22:11:17 +0100 Subject: [PATCH 062/124] some more implementation (not yet workable tho) list added and some basic, not yet working logic to actually send the message --- .../message/modals/MessageForward.tsx | 98 ++++++++++++++++++- 1 file changed, 96 insertions(+), 2 deletions(-) diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx index 891daee1..a60bb324 100644 --- a/src/app/components/message/modals/MessageForward.tsx +++ b/src/app/components/message/modals/MessageForward.tsx @@ -2,9 +2,25 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { modalAtom, ModalType } from '$state/modal'; -import { Avatar, Box, Button, Dialog, Header, Icon, Icons, IconButton, MenuItem, Text, config } from 'folds'; -import { useSetAtom } from 'jotai'; +import { + Box, + Button, + Dialog, + Header, + Icon, + Icons, + IconButton, + MenuItem, + Text, + config, + Scroll, +} from 'folds'; +import { useAtomValue, useSetAtom } from 'jotai'; import { MatrixEvent, Room } from '$types/matrix-sdk'; +import { useMemo, useState } from 'react'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; +import { factoryRoomIdByActivity } from '$utils/sort'; // Message forwarding component export function MessageForwardItem({ @@ -48,6 +64,53 @@ type MessageForwardInternalProps = { }; export function MessageForwardInternal({ room, mEvent, onClose }: MessageForwardInternalProps) { + const mx = useMatrixClient(); + + const [isTargetSelected, setIsTargetSelected] = useState(false); + const [targetRoomId, setTargetRoomId] = useState(null); + + const allRooms = useAtomValue(allRoomsAtom); + const allJoinedRooms = useAllJoinedRoomsSet(); + const getRoom = useGetRoom(allJoinedRooms); + // possible targets to forward the message to + const forwardTargets = useMemo( + () => + allRooms + .filter((id) => id !== room.roomId) + .filter((id) => { + const target = getRoom(id); + return !!target && !target.isSpaceRoom(); + }) + .sort(factoryRoomIdByActivity(mx)), + [allRooms, room.roomId, getRoom, mx] + ); + + // actually forward the message to the selected room + const handleForwardClick = (event: React.MouseEvent) => { + const { roomId } = event.currentTarget.dataset; + if (!roomId) return; + + const targetRoom = getRoom(roomId); + const eventId = mEvent.getId(); + if (!targetRoom || !eventId) return; + + type SendEventType = Parameters[2]; + type SendEventContent = Parameters[3]; + + const eventType = mEvent.getType() as SendEventType; + const content = { + ...mEvent.getContent(), + 'm.relates_to': { + 'm.in_reply_to': { + event_id: eventId, + }, + }, + } as SendEventContent; + + mx.sendEvent(targetRoom.roomId, null, eventType, content); + onClose(); + }; + return (
+ + + + {forwardTargets.map((roomId) => { + const target = getRoom(roomId); + if (!target) return null; + return ( + { + setIsTargetSelected(true); + setTargetRoomId(roomId); + }} + variant={targetRoomId === roomId ? 'Success' : 'Surface'} + aria-pressed={targetRoomId === roomId} + size="400" + radii="400" + > + {target.name} + + ); + })} + + + {isTargetSelected && ( + + )} +
); } From d416bb228b15dc78607b2452148365b0f3cb24f7 Mon Sep 17 00:00:00 2001 From: Joop Kiefte Date: Fri, 6 Mar 2026 22:23:54 +0000 Subject: [PATCH 063/124] chore: add changeset for element-call-dm PR --- .changeset/element-call-dm-video-calls.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/element-call-dm-video-calls.md diff --git a/.changeset/element-call-dm-video-calls.md b/.changeset/element-call-dm-video-calls.md new file mode 100644 index 00000000..99841dc1 --- /dev/null +++ b/.changeset/element-call-dm-video-calls.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Fix Element Call video/audio calls in DM and non-voice rooms: after joining through the lobby, the in-call grid now displays correctly instead of showing only the control bar. From 1be51b340732e23a09be7a03a2e4a7ef81edc1a4 Mon Sep 17 00:00:00 2001 From: mini-bomba <55105495+mini-bomba@users.noreply.github.com> Date: Fri, 6 Mar 2026 22:25:54 +0100 Subject: [PATCH 064/124] fix(commands): /myroomnick without new nick resets nick --- .changeset/pr207-myroomnick-unset.md | 5 +++++ src/app/hooks/useCommands.ts | 8 +++++--- 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 .changeset/pr207-myroomnick-unset.md diff --git a/.changeset/pr207-myroomnick-unset.md b/.changeset/pr207-myroomnick-unset.md new file mode 100644 index 00000000..66b67053 --- /dev/null +++ b/.changeset/pr207-myroomnick-unset.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Executing /myroomnick without a new nickname now removes the nickname. diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index de830354..eae38cbb 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -33,6 +33,7 @@ import { createRoomEncryptionState } from '$components/create-room'; import { parsePronounsInput } from '$utils/pronouns'; import { useRoomNavigate } from './useRoomNavigate'; import { enrichWidgetUrl } from './useRoomWidgets'; +import { useUserProfile } from './useUserProfile'; export const SHRUG = '¯\\_(ツ)_/¯'; export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻'; @@ -253,6 +254,7 @@ export type CommandRecord = Record; export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const { navigateRoom } = useRoomNavigate(); const [developerTools] = useSetting(settingsAtom, 'developerTools'); + const profile = useUserProfile(mx.getSafeUserId()); const commands: CommandRecord = useMemo( () => ({ @@ -439,8 +441,8 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { name: Command.MyRoomNick, description: 'Change nick in current room.', exe: async (payload) => { - const nick = payload.trim(); - if (nick === '') return; + let nick: string | null = payload.trim(); + if (nick === '') nick = profile.displayName ?? null; const mEvent = room .getLiveTimeline() .getState(EventTimeline.FORWARDS) @@ -1288,7 +1290,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }, }, }), - [mx, room, navigateRoom, developerTools] + [mx, navigateRoom, room, profile.displayName, profile.avatarUrl, developerTools] ); return commands; From 76faf7fb1768cb0f8d2569cd11eda89d83fa8d51 Mon Sep 17 00:00:00 2001 From: mini-bomba <55105495+mini-bomba@users.noreply.github.com> Date: Fri, 6 Mar 2026 23:19:15 +0100 Subject: [PATCH 065/124] fix(commands): do it for /myroomavatar as well --- .changeset/pr207-myroomnick-unset.md | 2 +- src/app/hooks/useCommands.ts | 38 ++++++++++++++++------------ 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/.changeset/pr207-myroomnick-unset.md b/.changeset/pr207-myroomnick-unset.md index 66b67053..76252010 100644 --- a/.changeset/pr207-myroomnick-unset.md +++ b/.changeset/pr207-myroomnick-unset.md @@ -2,4 +2,4 @@ sable: patch --- -Executing /myroomnick without a new nickname now removes the nickname. +Executing /myroomnick or /myroomavatar without a new nickname/avatar now removes the nickname/avatar. diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index eae38cbb..fb171874 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -464,23 +464,29 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { name: Command.MyRoomAvatar, description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc', exe: async (payload) => { - if (payload.match(/^mxc:\/\/\S+$/)) { - const mEvent = room - .getLiveTimeline() - .getState(EventTimeline.FORWARDS) - ?.getStateEvents(StateEvent.RoomMember, mx.getSafeUserId()); - const content = mEvent?.getContent(); - if (!content) return; - await mx.sendStateEvent( - room.roomId, - StateEvent.RoomMember as any, - { - ...content, - avatar_url: payload, - }, - mx.getSafeUserId() - ); + let newAvatar: string | undefined = payload.trim(); + if (newAvatar.length === 0) { + // no avatar, reset to global + newAvatar = profile.avatarUrl; + } else if (!newAvatar.match(/^mxc:\/\/\S+$/)) { + // bad mxc + return; } + const mEvent = room + .getLiveTimeline() + .getState(EventTimeline.FORWARDS) + ?.getStateEvents(StateEvent.RoomMember, mx.getSafeUserId()); + const content = mEvent?.getContent(); + if (!content) return; + await mx.sendStateEvent( + room.roomId, + StateEvent.RoomMember as any, + { + ...content, + avatar_url: newAvatar, + }, + mx.getSafeUserId() + ); }, }, [Command.ConvertToDm]: { From bc23dab6928df77d18674913f93ee247363c1700 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 16:45:03 -0600 Subject: [PATCH 066/124] Change sable version from patch to minor --- .../add_setting_to_enable_picture_in_picture_in_element_call.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md index 46bb9966..521791c6 100644 --- a/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md +++ b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md @@ -1,5 +1,5 @@ --- -sable: patch +sable: minor --- # Add setting to enable picture-in-picture in element-call From 65665a0998187887781370a96d63eaa59355a667 Mon Sep 17 00:00:00 2001 From: Rye Date: Fri, 6 Mar 2026 23:47:33 +0100 Subject: [PATCH 067/124] made IndexedDB Error page a bit more understandable --- src/app/pages/FeatureCheck.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/app/pages/FeatureCheck.tsx b/src/app/pages/FeatureCheck.tsx index df408d61..4963927e 100644 --- a/src/app/pages/FeatureCheck.tsx +++ b/src/app/pages/FeatureCheck.tsx @@ -19,8 +19,12 @@ export function FeatureCheck({ children }: { children: ReactNode }) { Missing Browser Feature - No IndexedDB support found. This application requires IndexedDB to store session - data locally. Please make sure your browser support IndexedDB and have it enabled. + This application needs a feature called IndexedDB to save your session data on your + device. It looks like your browser either doesn't support IndexedDB or it + isn't working properly right now. Please make sure your browser supports + IndexedDB and that it's enabled. If your browser does support IndexedDB, try + restarting your browser or checking your browser settings to ensure it's + working correctly. Date: Sat, 7 Mar 2026 00:14:09 +0000 Subject: [PATCH 068/124] fix: apply post-lobby reload to voice rooms too (same timing issue as DM calls) --- .../pages/client/call/PersistentCallContainer.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/app/pages/client/call/PersistentCallContainer.tsx b/src/app/pages/client/call/PersistentCallContainer.tsx index a8b57a40..d1cf8c24 100644 --- a/src/app/pages/client/call/PersistentCallContainer.tsx +++ b/src/app/pages/client/call/PersistentCallContainer.tsx @@ -35,7 +35,7 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro const callIframeRef = useRef(null); const callWidgetApiRef = useRef(null); const callSmallWidgetRef = useRef(null); - // After a non-voice room lobby join, reload EC with join_existing for proper in-call view. + // After any lobby join, reload EC with join_existing for proper in-call view. const hasReloadedAfterLobbyRef = useRef(false); const postLobbyIntentRef = useRef<'join_existing' | null>(null); @@ -146,10 +146,11 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro ] ); - // After a non-voice room lobby join, poll until EC's call member state event has propagated - // to the room, then reload EC with intent=join_existing + skipLobby=true so it auto-joins - // the existing session and shows the full in-call grid. Hangs up if the session never - // appears (e.g. EC failed to send its state event) to avoid leaving the user stuck. + // After any lobby join, poll until EC's call member state event has propagated to the room, + // then reload EC with intent=join_existing + skipLobby=true so it auto-joins the existing + // session and shows the full in-call grid. Hangs up if the session never appears. + // Applies to all room types: DM/group (start_call) and voice rooms (join_existing) both + // hit the same timing issue where the in-call grid is not shown after the first join. useEffect(() => { if (!activeCallRoomId) { hasReloadedAfterLobbyRef.current = false; @@ -157,8 +158,7 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro } if (isActiveCallReady && !hasReloadedAfterLobbyRef.current) { const room = mx?.getRoom(activeCallRoomId); - // Voice rooms already use join_existing and work correctly; skip reload for them. - if (room && !room.isCallRoom()) { + if (room) { hasReloadedAfterLobbyRef.current = true; const POLL_INTERVAL_MS = 200; const TIMEOUT_MS = 10000; From fbf6d27600fc329f28c0dd21127b894aa1714bdf Mon Sep 17 00:00:00 2001 From: Bea Date: Sat, 7 Mar 2026 00:37:49 +0000 Subject: [PATCH 069/124] ci(docker): build site once and package per-arch The multi-arch Docker build previously ran npm ci + npm run build for each target platform despite producing identical static assets. Add an overridable site-dist stage to the Dockerfile that CI replaces via --build-context site-dist=./dist. The workflow now builds the site once natively with Node.js on the runner, then the multi-arch step only packages the pre-built dist into nginx. --- .dockerignore | 1 + .github/workflows/docker-publish.yml | 27 ++++++++++++++++++++------- Dockerfile | 9 ++++++--- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/.dockerignore b/.dockerignore index be0443ae..ac33e3c4 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,2 +1,3 @@ node_modules/ +dist/ .git/ diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 79becac5..ea43d4be 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -62,16 +62,30 @@ jobs: type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }} type=semver,pattern={{major}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' && !startsWith(steps.release_tag.outputs.value, 'v0.') }} + - name: Compute short SHA + id: vars + run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT + + - name: Set up Node.js + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version: '24' + cache: 'npm' + + - name: Build site + env: + VITE_BUILD_HASH: ${{ steps.vars.outputs.short_sha }} + VITE_IS_RELEASE_TAG: ${{ steps.release_tag.outputs.is_release }} + run: | + npm ci --ignore-scripts + NODE_OPTIONS=--max_old_space_size=4096 npm run build + - name: Set up QEMU uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 - name: Set up Docker Buildx uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 - - name: Compute short SHA - id: vars - run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - - name: Build and push Docker image id: push uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2 @@ -83,9 +97,8 @@ jobs: labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max - build-args: | - VITE_BUILD_HASH=${{ steps.vars.outputs.short_sha }} - VITE_IS_RELEASE_TAG=${{ steps.release_tag.outputs.is_release }} + build-contexts: | + site-dist=./dist - name: Generate artifact attestation uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0 diff --git a/Dockerfile b/Dockerfile index 1be07f4a..aebd72f1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,12 +14,15 @@ COPY . /src/ ENV NODE_OPTIONS=--max_old_space_size=4096 RUN npm run build +## Dist +FROM scratch AS site-dist +COPY --from=builder /src/dist / ## App FROM nginx:1.29.5-alpine -COPY --from=builder /src/dist /app -COPY --from=builder /src/docker-nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=site-dist / /app +COPY docker-nginx.conf /etc/nginx/conf.d/default.conf RUN rm -rf /usr/share/nginx/html \ - && ln -s /app /usr/share/nginx/html + && ln -s /app /usr/share/nginx/html From 91e290a94f0ebc3fec73f72882df13ede8572e00 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 7 Mar 2026 02:11:47 +0100 Subject: [PATCH 070/124] rephrasing of error message might have gotten a bit to verbose --- src/app/pages/FeatureCheck.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/app/pages/FeatureCheck.tsx b/src/app/pages/FeatureCheck.tsx index 4963927e..6728b3d4 100644 --- a/src/app/pages/FeatureCheck.tsx +++ b/src/app/pages/FeatureCheck.tsx @@ -21,10 +21,9 @@ export function FeatureCheck({ children }: { children: ReactNode }) { This application needs a feature called IndexedDB to save your session data on your device. It looks like your browser either doesn't support IndexedDB or it - isn't working properly right now. Please make sure your browser supports - IndexedDB and that it's enabled. If your browser does support IndexedDB, try - restarting your browser or checking your browser settings to ensure it's - working correctly. + isn't working properly right now. Make sure your browser supports IndexedDB and + that it's enabled. Please also check if you have enough free disk space, as + IndexedDB may not work properly if your device is running low on storage. Date: Sat, 7 Mar 2026 02:14:48 +0100 Subject: [PATCH 071/124] made the warning more concise --- src/app/pages/FeatureCheck.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/app/pages/FeatureCheck.tsx b/src/app/pages/FeatureCheck.tsx index 6728b3d4..3036b55c 100644 --- a/src/app/pages/FeatureCheck.tsx +++ b/src/app/pages/FeatureCheck.tsx @@ -11,7 +11,7 @@ export function FeatureCheck({ children }: { children: ReactNode }) { checkIDBSupport(); }, [checkIDBSupport]); - if (idbSupportState.status === AsyncStatus.Success && idbSupportState.data === false) { + if (idbSupportState.status === AsyncStatus.Success && idbSupportState.data === true) { return ( @@ -19,11 +19,10 @@ export function FeatureCheck({ children }: { children: ReactNode }) { Missing Browser Feature - This application needs a feature called IndexedDB to save your session data on your - device. It looks like your browser either doesn't support IndexedDB or it - isn't working properly right now. Make sure your browser supports IndexedDB and - that it's enabled. Please also check if you have enough free disk space, as - IndexedDB may not work properly if your device is running low on storage. + This app needs IndexedDB to save sessions, but your browser doesn't support it + or it's disabled. Please ensure IndexedDB is enabled, restart your browser, + check settings/extensions or privacy mode, free up disk space, or try updating/using + another browser. Date: Sat, 7 Mar 2026 02:17:17 +0100 Subject: [PATCH 072/124] fix accidental set to true for test purposes --- src/app/pages/FeatureCheck.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/pages/FeatureCheck.tsx b/src/app/pages/FeatureCheck.tsx index 3036b55c..dd621c90 100644 --- a/src/app/pages/FeatureCheck.tsx +++ b/src/app/pages/FeatureCheck.tsx @@ -11,7 +11,7 @@ export function FeatureCheck({ children }: { children: ReactNode }) { checkIDBSupport(); }, [checkIDBSupport]); - if (idbSupportState.status === AsyncStatus.Success && idbSupportState.data === true) { + if (idbSupportState.status === AsyncStatus.Success && idbSupportState.data === false) { return ( From 8f8f3aa8fde44c0f030094848a8d56e4a86d6a65 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 7 Mar 2026 02:20:57 +0100 Subject: [PATCH 073/124] added changeset Signed-off-by: Rye --- .changeset/change_indexdb_warning.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/change_indexdb_warning.md diff --git a/.changeset/change_indexdb_warning.md b/.changeset/change_indexdb_warning.md new file mode 100644 index 00000000..68cebe4d --- /dev/null +++ b/.changeset/change_indexdb_warning.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +change indexdb warning phrasing to include low disk space as possible reason From 0a194281760bf2011a997b382341b26484d5541e Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 19:29:40 -0600 Subject: [PATCH 074/124] Create 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 00000000..be6c9424 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @7w1 \ No newline at end of file From a3470e02e271edb9d602ad3b0f9ad3b7cd0bec7c Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 20:31:51 -0600 Subject: [PATCH 075/124] split read and typing indicators --- ...able_picture_in_picture_in_element_call.md | 2 +- .changeset/split_typing_and_read.md | 5 +++ src/app/features/room-nav/RoomNavItem.tsx | 4 +-- src/app/features/room/Room.tsx | 6 ++-- src/app/features/room/RoomTimeline.tsx | 32 +++++++++---------- src/app/features/room/RoomView.tsx | 4 +-- src/app/features/room/RoomViewHeader.tsx | 4 +-- src/app/features/settings/general/General.tsx | 12 +++++-- src/app/pages/client/direct/Direct.tsx | 4 +-- src/app/pages/client/home/Home.tsx | 4 +-- src/app/pages/client/inbox/Notifications.tsx | 10 +++--- src/app/pages/client/sidebar/DirectTab.tsx | 4 +-- src/app/pages/client/sidebar/HomeTab.tsx | 4 +-- src/app/pages/client/sidebar/SpaceTabs.tsx | 4 +-- src/app/pages/client/space/Space.tsx | 4 +-- src/app/state/settings.ts | 2 ++ 16 files changed, 60 insertions(+), 45 deletions(-) create mode 100644 .changeset/split_typing_and_read.md diff --git a/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md index 521791c6..fd212c46 100644 --- a/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md +++ b/.changeset/add_setting_to_enable_picture_in_picture_in_element_call.md @@ -2,4 +2,4 @@ sable: minor --- -# Add setting to enable picture-in-picture in element-call +Add setting to enable picture-in-picture in element-call diff --git a/.changeset/split_typing_and_read.md b/.changeset/split_typing_and_read.md new file mode 100644 index 00000000..bd1aed0c --- /dev/null +++ b/.changeset/split_typing_and_read.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Split typing and read status settings, allowing toggling off one and not the other. diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 81cb1072..9ba8b0f8 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -93,7 +93,7 @@ type RoomNavItemMenuProps = { const RoomNavItemMenu = forwardRef( ({ room, requestClose, notificationMode }, ref) => { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const unread = useRoomUnread(room.roomId, roomToUnreadAtom); const powerLevels = usePowerLevels(room); const creators = useRoomCreators(room); @@ -106,7 +106,7 @@ const RoomNavItemMenu = forwardRef( const [invitePrompt, setInvitePrompt] = useState(false); const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideActivity); + markAsRead(mx, room.roomId, hideReads); requestClose(); }; diff --git a/src/app/features/room/Room.tsx b/src/app/features/room/Room.tsx index c6983eb4..f2619e6a 100644 --- a/src/app/features/room/Room.tsx +++ b/src/app/features/room/Room.tsx @@ -25,7 +25,7 @@ export function Room() { const [isDrawer] = useSetting(settingsAtom, 'isPeopleDrawer'); const [isWidgetDrawerOpen] = useSetting(settingsAtom, 'isWidgetDrawer'); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const screenSize = useScreenSizeContext(); const powerLevels = usePowerLevels(room); const members = useRoomMembers(mx, room.roomId); @@ -36,10 +36,10 @@ export function Room() { useCallback( (evt) => { if (isKeyHotkey('escape', evt)) { - markAsRead(mx, room.roomId, hideActivity); + markAsRead(mx, room.roomId, hideReads); } }, - [mx, room.roomId, hideActivity] + [mx, room.roomId, hideReads] ) ); diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 5e448993..37021e37 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -560,7 +560,7 @@ export function RoomTimeline({ }: RoomTimelineProps) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const [messageLayout] = useSetting(settingsAtom, 'messageLayout'); const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents'); @@ -754,7 +754,7 @@ export function RoomTimeline({ // Check if the document is in focus (user is actively viewing the app), // and either there are no unread messages or the latest message is from the current user. // If either condition is met, trigger the markAsRead function to send a read receipt. - requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideActivity)); + requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReads)); } if (!document.hasFocus() && !unreadInfo) { @@ -780,7 +780,7 @@ export function RoomTimeline({ setUnreadInfo(getRoomUnreadInfo(room)); } }, - [mx, room, unreadInfo, hideActivity] + [mx, room, unreadInfo, hideReads] ) ); @@ -884,15 +884,15 @@ export function RoomTimeline({ const tryAutoMarkAsRead = useCallback(() => { const readUptoEventId = readUptoEventIdRef.current; if (!readUptoEventId) { - requestAnimationFrame(() => markAsRead(mx, room.roomId, hideActivity)); + requestAnimationFrame(() => markAsRead(mx, room.roomId, hideReads)); return; } const evtTimeline = getEventTimeline(room, readUptoEventId); const latestTimeline = evtTimeline && getFirstLinkedTimeline(evtTimeline, Direction.Forward); if (latestTimeline === room.getLiveTimeline()) { - requestAnimationFrame(() => markAsRead(mx, room.roomId, hideActivity)); + requestAnimationFrame(() => markAsRead(mx, room.roomId, hideReads)); } - }, [mx, room, hideActivity]); + }, [mx, room, hideReads]); const debounceSetAtBottom = useDebounce( useCallback((entry: IntersectionObserverEntry) => { @@ -1119,7 +1119,7 @@ export function RoomTimeline({ }; const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideActivity); + markAsRead(mx, room.roomId, hideReads); }; const handleOpenReply: MouseEventHandler = useCallback( @@ -1363,7 +1363,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(senderId)} hour24Clock={hour24Clock} @@ -1450,7 +1450,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} hour24Clock={hour24Clock} @@ -1572,7 +1572,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} hour24Clock={hour24Clock} @@ -1624,7 +1624,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} > (null); const roomViewRef = useRef(null); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const screenSize = useScreenSizeContext(); const { roomId } = room; @@ -184,7 +184,7 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) { )} - {hideActivity ? : } + {hideReads ? : } diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index b0ccb91c..0490350f 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -106,7 +106,7 @@ type RoomMenuProps = { }; const RoomMenu = forwardRef(({ room, requestClose }, ref) => { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const unread = useRoomUnread(room.roomId, roomToUnreadAtom); const powerLevels = usePowerLevelsContext(); const creators = useRoomCreators(room); @@ -123,7 +123,7 @@ const RoomMenu = forwardRef(({ room, requestClose const [directInvitePrompt, setDirectInvitePrompt] = useState(false); const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideActivity); + markAsRead(mx, room.roomId, hideReads); requestClose(); }; diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 16b98461..384ecf08 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -404,6 +404,7 @@ function Editor({ isMobile }: { isMobile: boolean }) { const [enterForNewline, setEnterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown'); const [hideActivity, setHideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads, setHideReads] = useSetting(settingsAtom, 'hideReads'); return ( @@ -435,11 +436,18 @@ function Editor({ isMobile }: { isMobile: boolean }) {
} /> + + } + /> + ); } diff --git a/src/app/pages/client/direct/Direct.tsx b/src/app/pages/client/direct/Direct.tsx index 7f19df3f..657cc199 100644 --- a/src/app/pages/client/direct/Direct.tsx +++ b/src/app/pages/client/direct/Direct.tsx @@ -58,13 +58,13 @@ type DirectMenuProps = { }; const DirectMenu = forwardRef(({ requestClose }, ref) => { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const orphanRooms = useDirectRooms(); const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); const handleMarkAsRead = () => { if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideActivity)); + orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); requestClose(); }; diff --git a/src/app/pages/client/home/Home.tsx b/src/app/pages/client/home/Home.tsx index 4b3e61c9..d798077a 100644 --- a/src/app/pages/client/home/Home.tsx +++ b/src/app/pages/client/home/Home.tsx @@ -69,13 +69,13 @@ type HomeMenuProps = { }; const HomeMenu = forwardRef(({ requestClose }, ref) => { const orphanRooms = useHomeRooms(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); const mx = useMatrixClient(); const handleMarkAsRead = () => { if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideActivity)); + orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); requestClose(); }; diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 2d82521d..79234851 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -207,7 +207,7 @@ type RoomNotificationsGroupProps = { notifications: INotification[]; mediaAutoLoad?: boolean; urlPreview?: boolean; - hideActivity: boolean; + hideReads: boolean; onOpen: (roomId: string, eventId: string) => void; legacyUsernameColor?: boolean; hour24Clock: boolean; @@ -218,7 +218,7 @@ function RoomNotificationsGroupComp({ notifications, mediaAutoLoad, urlPreview, - hideActivity, + hideReads, onOpen, legacyUsernameColor, hour24Clock, @@ -414,7 +414,7 @@ function RoomNotificationsGroupComp({ onOpen(room.roomId, eventId); }; const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideActivity); + markAsRead(mx, room.roomId, hideReads); }; return ( @@ -565,7 +565,7 @@ const FAST_REFRESH_MS = 2500; export function Notifications() { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); const [legacyUsernameColor] = useSetting(settingsAtom, 'legacyUsernameColor'); @@ -720,7 +720,7 @@ export function Notifications() { notifications={group.notifications} mediaAutoLoad={mediaAutoLoad} urlPreview={urlPreview} - hideActivity={hideActivity} + hideReads={hideReads} onOpen={navigateRoom} legacyUsernameColor={ legacyUsernameColor || mDirects.has(groupRoom.roomId) diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index b4a90be5..b59f852c 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -31,13 +31,13 @@ type DirectMenuProps = { }; const DirectMenu = forwardRef(({ requestClose }, ref) => { const orphanRooms = useDirectRooms(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); const mx = useMatrixClient(); const handleMarkAsRead = () => { if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideActivity)); + orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); requestClose(); }; diff --git a/src/app/pages/client/sidebar/HomeTab.tsx b/src/app/pages/client/sidebar/HomeTab.tsx index a19aee98..ba02326e 100644 --- a/src/app/pages/client/sidebar/HomeTab.tsx +++ b/src/app/pages/client/sidebar/HomeTab.tsx @@ -32,13 +32,13 @@ type HomeMenuProps = { }; const HomeMenu = forwardRef(({ requestClose }, ref) => { const orphanRooms = useHomeRooms(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); const mx = useMatrixClient(); const handleMarkAsRead = () => { if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideActivity)); + orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); requestClose(); }; diff --git a/src/app/pages/client/sidebar/SpaceTabs.tsx b/src/app/pages/client/sidebar/SpaceTabs.tsx index bc3927da..15ebd518 100644 --- a/src/app/pages/client/sidebar/SpaceTabs.tsx +++ b/src/app/pages/client/sidebar/SpaceTabs.tsx @@ -102,7 +102,7 @@ type SpaceMenuProps = { const SpaceMenu = forwardRef( ({ room, requestClose, onUnpin }, ref) => { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const roomToParents = useAtomValue(roomToParentsAtom); const powerLevels = usePowerLevels(room); const creators = useRoomCreators(room); @@ -121,7 +121,7 @@ const SpaceMenu = forwardRef( const unread = useRoomsUnread(allChild, roomToUnreadAtom); const handleMarkAsRead = () => { - allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideActivity)); + allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads)); requestClose(); }; diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index d83769dd..7cfe5417 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -80,7 +80,7 @@ type SpaceMenuProps = { }; const SpaceMenu = forwardRef(({ room, requestClose }, ref) => { const mx = useMatrixClient(); - const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const [developerTools] = useSetting(settingsAtom, 'developerTools'); const roomToParents = useAtomValue(roomToParentsAtom); const powerLevels = usePowerLevels(room); @@ -101,7 +101,7 @@ const SpaceMenu = forwardRef(({ room, requestClo const unread = useRoomsUnread(allChild, roomToUnreadAtom); const handleMarkAsRead = () => { - allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideActivity)); + allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads)); requestClose(); }; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 318485b0..68aa8ff0 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -78,6 +78,7 @@ export interface Settings { showUnreadCounts: boolean; badgeCountDMsOnly: boolean; showPingCounts: boolean; + hideReads: boolean; } const defaultSettings: Settings = { @@ -142,6 +143,7 @@ const defaultSettings: Settings = { showUnreadCounts: true, badgeCountDMsOnly: false, showPingCounts: true, + hideReads: false, }; export const getSettings = () => { From f11a1d7eae1fbb75c210003a9b710eaf883c6a1f Mon Sep 17 00:00:00 2001 From: Kierre Date: Fri, 6 Mar 2026 21:50:37 -0500 Subject: [PATCH 076/124] allow replies to state events --- src/app/features/room/RoomTimeline.tsx | 33 ++++++++++++++++------- src/app/features/room/message/Message.tsx | 14 ++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 5e448993..5c4bcbba 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1210,15 +1210,24 @@ export function RoomTimeline({ ? { 'm.relates_to': { rel_type: 'm.thread', event_id: replyId } } : replyEvt.getWireContent(); const senderId = replyEvt.getSender(); - if (senderId && typeof body === 'string') { - setReplyDraft({ - userId: senderId, - eventId: replyId, - body, - formattedBody, - relation, - }); - setTimeout(() => ReactEditor.focus(editor), 100); + if (senderId) { + if (typeof body === 'string') { + setReplyDraft({ + userId: senderId, + eventId: replyId, + body, + formattedBody, + relation, + }); + } else { + setReplyDraft({ + userId: senderId, + eventId: replyId, + body: '', + formattedBody: '', + relation, + }); + } } }, [room, setReplyDraft, editor, activeReplyId] @@ -1624,6 +1633,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > @@ -1667,6 +1677,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > @@ -1711,6 +1722,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > @@ -1755,6 +1767,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > @@ -1801,6 +1814,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > @@ -1852,6 +1866,7 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} + onReplyClick={handleReplyClick} hideReadReceipts={hideActivity} showDeveloperTools={showDeveloperTools} > diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 6b62a51c..00870960 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -970,6 +970,10 @@ export type EventProps = { mEvent: MatrixEvent; highlight: boolean; canDelete?: boolean; + onReplyClick: ( + ev: Parameters>[0], + startThread?: boolean + ) => void; messageSpacing: MessageSpacing; hideReadReceipts?: boolean; showDeveloperTools?: boolean; @@ -982,6 +986,7 @@ export const Event = as<'div', EventProps>( mEvent, highlight, canDelete, + onReplyClick, messageSpacing, hideReadReceipts, showDeveloperTools, @@ -1119,6 +1124,15 @@ export const Event = as<'div', EventProps>( } > + + + Date: Fri, 6 Mar 2026 20:50:38 -0600 Subject: [PATCH 077/124] fix formatting and lint --- .../client/call/PersistentCallContainer.tsx | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/app/pages/client/call/PersistentCallContainer.tsx b/src/app/pages/client/call/PersistentCallContainer.tsx index d1cf8c24..f6548bc7 100644 --- a/src/app/pages/client/call/PersistentCallContainer.tsx +++ b/src/app/pages/client/call/PersistentCallContainer.tsx @@ -118,7 +118,12 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro 'm.call', newUrl, false, - getWidgetData(mx, roomIdToSet, {}, { skipLobby: true, intent: effectiveIntent, callIntent: callIntentParam }), + getWidgetData( + mx, + roomIdToSet, + {}, + { skipLobby: true, intent: effectiveIntent, callIntent: callIntentParam } + ), roomIdToSet ); @@ -181,13 +186,27 @@ export function PersistentCallContainer({ children }: PersistentCallContainerPro } } return undefined; - }, [isActiveCallReady, activeCallRoomId, mx, registerActiveClientWidgetApi, resetActiveCallReady, hangUp]); + }, [ + isActiveCallReady, + activeCallRoomId, + mx, + registerActiveClientWidgetApi, + resetActiveCallReady, + hangUp, + ]); useEffect(() => { if (activeCallRoomId) { const intentOverride = postLobbyIntentRef.current ?? undefined; postLobbyIntentRef.current = null; - setupWidget(callWidgetApiRef, callSmallWidgetRef, callIframeRef, true, theme.kind, intentOverride); + setupWidget( + callWidgetApiRef, + callSmallWidgetRef, + callIframeRef, + true, + theme.kind, + intentOverride + ); } }, [ theme, From 78c404951014ab0f2e6eb49b8acb448988da595a Mon Sep 17 00:00:00 2001 From: Kierre Date: Fri, 6 Mar 2026 21:53:48 -0500 Subject: [PATCH 078/124] resolve conflicts hopefully --- src/app/features/room/RoomTimeline.tsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 5c4bcbba..9551fa76 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1372,7 +1372,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(senderId)} hour24Clock={hour24Clock} @@ -1459,7 +1459,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} hour24Clock={hour24Clock} @@ -1581,7 +1581,7 @@ export function RoomTimeline({ /> ) } - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} hour24Clock={hour24Clock} @@ -1634,7 +1634,7 @@ export function RoomTimeline({ messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} onReplyClick={handleReplyClick} - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} showDeveloperTools={showDeveloperTools} > Date: Fri, 6 Mar 2026 21:54:36 -0500 Subject: [PATCH 079/124] newsfile --- .changeset/221.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/221.md diff --git a/.changeset/221.md b/.changeset/221.md new file mode 100644 index 00000000..eb3b1007 --- /dev/null +++ b/.changeset/221.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Allow for replying to state events. From 136ee3fe490a2f964f8b58eb9e73a7f7a4933c02 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 21:04:26 -0600 Subject: [PATCH 080/124] fix lint --- src/app/features/room/RoomTimeline.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 1cf4d52d..7bbdf859 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1230,7 +1230,7 @@ export function RoomTimeline({ } } }, - [room, setReplyDraft, editor, activeReplyId] + [room, setReplyDraft, activeReplyId] ); const handleReplyClick: MouseEventHandler = useCallback( From 5fd09cc9e2a85e6d65086bfdf802594989476826 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 21:30:02 -0600 Subject: [PATCH 081/124] adjust styling for smaller standard image previews --- .../components/url-preview/UrlPreviewCard.tsx | 58 ++++++++++++++----- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx index 4c89426e..3855085d 100644 --- a/src/app/components/url-preview/UrlPreviewCard.tsx +++ b/src/app/components/url-preview/UrlPreviewCard.tsx @@ -52,7 +52,16 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s ); return ( - + {(prev['og:video'] && ( )) || (prev['og:image'] && ( - } - renderImage={(p) => } - /> + + {' '} + } + renderImage={(p) => ( + + )} + /> + )) || (prev['og:audio'] && ( - + ))} - + Date: Fri, 6 Mar 2026 22:19:51 -0600 Subject: [PATCH 082/124] add emoji autocomplete threshold setting --- .changeset/emoji_autocomplete_setting.md | 5 ++ .../autocomplete/EmoticonAutocomplete.tsx | 13 +++-- src/app/features/settings/general/General.tsx | 52 +++++++++++++++++++ src/app/state/settings.ts | 2 + 4 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 .changeset/emoji_autocomplete_setting.md diff --git a/.changeset/emoji_autocomplete_setting.md b/.changeset/emoji_autocomplete_setting.md new file mode 100644 index 00000000..4fb710e7 --- /dev/null +++ b/.changeset/emoji_autocomplete_setting.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Added a new setting "Emoji Selector Character Threshold" to set the number of characters to type before the suggestions pop up. diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index 16926645..d89c3504 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -14,6 +14,8 @@ import { mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { ImageUsage, PackImageReader } from '$plugins/custom-emoji'; import { getEmoticonSearchStr } from '$plugins/utils'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { createEmoticonElement, moveCursor, replaceWithElement } from '$components/editor/utils'; import { AutocompleteMenu } from './AutocompleteMenu'; import { AutocompleteQuery } from './autocompleteQuery'; @@ -53,6 +55,8 @@ export function EmoticonAutocomplete({ const imagePacks = useRelevantImagePacks(ImageUsage.Emoticon, imagePackRooms); const recentEmoji = useRecentEmoji(mx, 20); + const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold'); + const searchList = useMemo(() => { const list: Array = []; return list.concat( @@ -69,9 +73,12 @@ export function EmoticonAutocomplete({ const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji; useEffect(() => { - if (query.text) search(query.text); - else resetSearch(); - }, [query.text, search, resetSearch]); + if (query.text && query.text.length >= emojiThreshold) { + search(query.text); + } else { + resetSearch(); + } + }, [query.text, search, resetSearch, emojiThreshold]); const handleAutocomplete: EmoticonCompleteHandler = onEmoticonSelected ?? diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 384ecf08..b35500b3 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -1,6 +1,7 @@ import { ChangeEventHandler, FormEventHandler, + KeyboardEventHandler, MouseEventHandler, useEffect, useState, @@ -22,6 +23,7 @@ import { Scroll, Switch, Text, + toRem, } from 'folds'; import FocusTrap from 'focus-trap-react'; import { useAtomValue, useSetAtom } from 'jotai'; @@ -46,6 +48,7 @@ import { SequenceCardStyle } from '$features/settings/styles.css'; import { sessionsAtom, activeSessionIdAtom } from '$state/sessions'; import { useClientConfig } from '$hooks/useClientConfig'; import { resolveSlidingEnabled } from '$client/initMatrix'; +import { isKeyHotkey } from 'is-hotkey'; type DateHintProps = { hasChanges: boolean; @@ -689,6 +692,49 @@ function Gestures({ isMobile }: { isMobile: boolean }) { ); } +function EmojiSelectorThresholdInput() { + const [emojiThreshold, setEmojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold'); + const [inputValue, setInputValue] = useState(emojiThreshold.toString()); + + const handleChange: ChangeEventHandler = (evt) => { + const val = evt.target.value; + setInputValue(val); + + const parsed = parseInt(val, 10); + if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) { + setEmojiThreshold(parsed); + } + }; + + const handleKeyDown: KeyboardEventHandler = (evt) => { + if (isKeyHotkey('escape', evt)) { + evt.stopPropagation(); + setInputValue(emojiThreshold.toString()); + (evt.target as HTMLInputElement).blur(); + } + + if (isKeyHotkey('enter', evt)) { + (evt.target as HTMLInputElement).blur(); + } + }; + + return ( + + ); +} + function Messages() { const [hideMembershipEvents, setHideMembershipEvents] = useSetting( settingsAtom, @@ -716,6 +762,12 @@ function Messages() { } /> + + } + /> + { From b345efde1679201287d045f5c1cd4f13237b1361 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 23:46:51 -0600 Subject: [PATCH 083/124] add catination settings --- .changeset/z_cat_settings.md | 5 ++ .../user-profile/UserRoomProfile.tsx | 25 ++++++- src/app/features/room/RoomTimeline.tsx | 2 + src/app/features/settings/account/Profile.tsx | 75 ++++++++++++++++++- src/app/hooks/useUserProfile.ts | 6 ++ src/app/state/settings.ts | 8 ++ 6 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 .changeset/z_cat_settings.md diff --git a/.changeset/z_cat_settings.md b/.changeset/z_cat_settings.md new file mode 100644 index 00000000..686fc480 --- /dev/null +++ b/.changeset/z_cat_settings.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Added settings to Account that let you set if you are a cat or have cats, or not display other peoples cat status. diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index 0031943d..3878bba5 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -31,8 +31,9 @@ import { } from '$plugins/react-custom-html-parser'; import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; import { RenderBody } from '$components/message'; -import { getSettings } from '$state/settings'; +import { getSettings, settingsAtom } from '$state/settings'; import { filterPronounsByLanguage } from '$utils/pronouns'; +import { useSetting } from '$state/hooks/settings'; import { CreatorChip } from './CreatorChip'; import { UserInviteAlert, UserBanAlert, UserModeration, UserKickAlert } from './UserModeration'; import { PowerChip } from './PowerChip'; @@ -50,6 +51,8 @@ const KNOWN_KEYS = [ 'moe.sable.app.name_color', 'avatar_url', 'displayname', + 'kitty.meow.has_cats', + 'kitty.meow.is_cat', ]; type UserExtendedSectionProps = { @@ -69,6 +72,18 @@ function UserExtendedSection({ }; const [showMore, setShowMore] = useState(false); + const [renderAnimals] = useSetting(settingsAtom, 'renderAnimals'); + const isCat = profile.isCat === true; + const hasCats = profile.hasCats === true; + + const catStatusText = useMemo(() => { + if (!renderAnimals) return null; + if (isCat && hasCats) return 'Cat with cats—needs pets & love!'; + if (isCat) return 'Is a cat—give pets & love!'; + if (hasCats) return 'Has cats—send love!'; + return null; + }, [renderAnimals, isCat, hasCats]); + const renderValue = (val: any) => { if (val === null || val === undefined) return 'n/a'; if (typeof val === 'boolean') return val ? 'Yes' : 'No'; @@ -152,6 +167,14 @@ function UserExtendedSection({ )} + {catStatusText && ( + + + + {catStatusText} + + + )} )} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 7bbdf859..38063d24 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1153,6 +1153,8 @@ export function RoomTimeline({ delete cleanExtended['moe.sable.app.name_color']; delete cleanExtended.avatar_url; delete cleanExtended.displayname; + delete cleanExtended['kitty.meow.has_cats']; + delete cleanExtended['kitty.meow.is_cat']; } openUserRoomProfile( diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 707c5916..4cbe5fda 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -23,6 +23,7 @@ import { Header, config, Spinner, + Switch, } from 'folds'; import FocusTrap from 'focus-trap-react'; import { useSetAtom } from 'jotai'; @@ -51,6 +52,8 @@ import { PronounEditor } from './PronounEditor'; import { BioEditor } from './BioEditor'; import { NameColorEditor } from './NameColorEditor'; import { StatusEditor } from './StatusEditor'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; type PronounSet = { summary: string; @@ -484,9 +487,14 @@ function ProfileExtended({ profile, userId }: ProfileProps) { const presence = useUserPresence(userId); 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']; + // Unknown fields / unimplemented non-matrix-spec fields // Only renders them, can't edit or set - const extendedFields = Object.entries(profile.extended || {}); + const extendedFields = Object.entries(profile.extended || {}).filter( + ([key]) => !EXCLUDED_KEYS.includes(key) + ); const handleSaveField = useCallback( async (key: string, value: any) => { @@ -627,6 +635,70 @@ function ProfileExtended({ profile, userId }: ProfileProps) { ); } +type AnimalCosmeticsProps = { + profile: UserProfile; + userId: string; +}; +function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) { + const mx = useMatrixClient(); + const setGlobalProfiles = useSetAtom(profilesCacheAtom); + const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals'); + + const isCat = profile.isCat === true; + const hasCats = profile.hasCats === true; + + const handleSaveField = useCallback( + async (key: string, value: any) => { + await mx.setExtendedProfileProperty?.(key, value); + setGlobalProfiles((prev) => { + const newCache = { ...prev }; + delete newCache[userId]; + return newCache; + }); + }, + [mx, userId, setGlobalProfiles] + ); + + return ( + + Animal Identity + + } + /> + + + handleSaveField('kitty.meow.is_cat', !isCat)} + /> + } + /> + + + handleSaveField('kitty.meow.has_cats', !hasCats)} + /> + } + /> + + + ); +} + export function Profile() { const mx = useMatrixClient(); const userId = mx.getUserId()!; @@ -662,6 +734,7 @@ export function Profile() { + ); } diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index f5af57c6..e5f1a013 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -20,6 +20,8 @@ export type UserProfile = { status?: string; bannerUrl?: string; nameColor?: string; + isCat?: boolean; + hasCats?: boolean; extended?: Record; _fetched?: boolean; }; @@ -36,6 +38,8 @@ const normalizeInfo = (info: any): UserProfile => { 'chat.commet.profile_banner', 'chat.commet.profile_status', 'moe.sable.app.name_color', + 'kitty.meow.has_cats', + 'kitty.meow.is_cat', ]; const extended: Record = {}; @@ -54,6 +58,8 @@ const normalizeInfo = (info: any): UserProfile => { status: info['chat.commet.profile_status'], bannerUrl: info['chat.commet.profile_banner'], nameColor: info['moe.sable.app.name_color'], + isCat: info['kitty.meow.is_cat'] === true, + hasCats: info['kitty.meow.has_cats'] === true, extended, _fetched: true, }; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 68aa8ff0..d7067171 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -79,6 +79,10 @@ export interface Settings { badgeCountDMsOnly: boolean; showPingCounts: boolean; hideReads: boolean; + emojiSuggestThreshold: number; + + // furry stuff + renderAnimals: boolean; } const defaultSettings: Settings = { @@ -144,6 +148,10 @@ const defaultSettings: Settings = { badgeCountDMsOnly: false, showPingCounts: true, hideReads: false, + emojiSuggestThreshold: 2, + + // furry stuff + renderAnimals: true, }; export const getSettings = () => { From 457eceff519f3af456342a5790bb3e9781c384e8 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Fri, 6 Mar 2026 23:57:05 -0600 Subject: [PATCH 084/124] Update Profile.tsx --- src/app/features/settings/account/Profile.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 4cbe5fda..85bf0bc3 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -47,13 +47,13 @@ import { useCapabilities } from '$hooks/useCapabilities'; import { profilesCacheAtom } from '$state/userRoomProfile'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { useUserPresence } from '$hooks/useUserPresence'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { TimezoneEditor } from './TimezoneEditor'; import { PronounEditor } from './PronounEditor'; import { BioEditor } from './BioEditor'; import { NameColorEditor } from './NameColorEditor'; import { StatusEditor } from './StatusEditor'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; type PronounSet = { summary: string; @@ -644,11 +644,11 @@ function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) { const setGlobalProfiles = useSetAtom(profilesCacheAtom); const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals'); - const isCat = profile.isCat === true; - const hasCats = profile.hasCats === true; + const isCat = profile.isCat || profile.extended?.['kitty.meow.is_cat'] === true; + const hasCats = profile.hasCats || profile.extended?.['kitty.meow.has_cats'] === true; const handleSaveField = useCallback( - async (key: string, value: any) => { + async (key: string, value: boolean) => { await mx.setExtendedProfileProperty?.(key, value); setGlobalProfiles((prev) => { const newCache = { ...prev }; From 71521341355870f84e053014f74e1c13ad48b54e Mon Sep 17 00:00:00 2001 From: Joop Kiefte Date: Sat, 7 Mar 2026 06:31:57 +0000 Subject: [PATCH 085/124] feat: keyboard navigation shortcuts, ARIA form labels, and keyboard shortcuts page (#201) --- .../keyboard-navigation-aria-accessibility.md | 5 + .../components/GlobalKeyboardShortcuts.tsx | 117 +++++++++++++ src/app/features/settings/Settings.tsx | 10 ++ .../keyboard-shortcuts/KeyboardShortcuts.tsx | 159 ++++++++++++++++++ .../settings/keyboard-shortcuts/index.ts | 1 + src/app/pages/Router.tsx | 17 ++ .../pages/auth/login/PasswordLoginForm.tsx | 14 +- .../auth/register/PasswordRegisterForm.tsx | 20 ++- src/app/utils/announce.ts | 12 ++ 9 files changed, 347 insertions(+), 8 deletions(-) create mode 100644 .changeset/keyboard-navigation-aria-accessibility.md create mode 100644 src/app/components/GlobalKeyboardShortcuts.tsx create mode 100644 src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx create mode 100644 src/app/features/settings/keyboard-shortcuts/index.ts create mode 100644 src/app/utils/announce.ts diff --git a/.changeset/keyboard-navigation-aria-accessibility.md b/.changeset/keyboard-navigation-aria-accessibility.md new file mode 100644 index 00000000..94845a64 --- /dev/null +++ b/.changeset/keyboard-navigation-aria-accessibility.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Add keyboard navigation shortcuts for unread rooms (Alt+N, Alt+Shift+Up/Down), ARIA form label associations for screen reader accessibility, and a keyboard shortcuts settings page. diff --git a/src/app/components/GlobalKeyboardShortcuts.tsx b/src/app/components/GlobalKeyboardShortcuts.tsx new file mode 100644 index 00000000..5e2a43ee --- /dev/null +++ b/src/app/components/GlobalKeyboardShortcuts.tsx @@ -0,0 +1,117 @@ +/** + * Global keyboard shortcuts for navigation and accessibility. + * + * Shortcuts provided: + * Alt+N — jump to the highest-priority unread room + * Alt+Shift+Down — cycle forward through unread rooms + * Alt+Shift+Up — cycle backward through unread rooms + */ +import { useCallback, useRef } from 'react'; +import { useNavigate, useLocation, matchPath } from 'react-router-dom'; +import { useAtomValue } from 'jotai'; +import { isKeyHotkey } from 'is-hotkey'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { roomToParentsAtom } from '$state/room/roomToParents'; +import { mDirectAtom } from '$state/mDirectList'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { useKeyDown } from '$hooks/useKeyDown'; +import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '$pages/pathUtils'; +import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths'; +import { getCanonicalAliasOrRoomId } from '$utils/matrix'; +import { announce } from '$utils/announce'; + +export function GlobalKeyboardShortcuts() { + const navigate = useNavigate(); + const location = useLocation(); + const mx = useMatrixClient(); + const roomToParents = useAtomValue(roomToParentsAtom); + const mDirects = useAtomValue(mDirectAtom); + const roomToUnread = useAtomValue(roomToUnreadAtom); + const unreadIndexRef = useRef(0); + + // Derive the current room ID from the URL so we know which room is active. + const roomMatch = + matchPath(HOME_ROOM_PATH, location.pathname) ?? + matchPath(DIRECT_ROOM_PATH, location.pathname) ?? + matchPath(SPACE_ROOM_PATH, location.pathname); + const roomIdOrAlias = roomMatch?.params.roomIdOrAlias + ? decodeURIComponent(roomMatch.params.roomIdOrAlias) + : undefined; + let currentRoomId: string | null = null; + if (roomIdOrAlias) { + if (roomIdOrAlias.startsWith('!')) { + currentRoomId = roomIdOrAlias; + } else { + currentRoomId = + mx.getRooms().find((r) => r.getCanonicalAlias() === roomIdOrAlias)?.roomId ?? null; + } + } + + /** Navigate to a room by ID and announce it to screen readers. */ + const navigateToRoom = useCallback( + (roomId: string, remaining: number) => { + const roomIdOrAliasToNav = getCanonicalAliasOrRoomId(mx, roomId); + const isDirect = mDirects.has(roomId); + if (isDirect) { + navigate(getDirectRoomPath(roomIdOrAliasToNav)); + } else { + const parents = roomToParents.get(roomId); + if (parents && parents.size > 0) { + const spaceId = Array.from(parents)[0]; + const spaceIdOrAlias = getCanonicalAliasOrRoomId(mx, spaceId); + navigate(getSpaceRoomPath(spaceIdOrAlias, roomIdOrAliasToNav)); + } else { + navigate(getHomeRoomPath(roomIdOrAliasToNav)); + } + } + const roomName = mx.getRoom(roomId)?.name ?? 'Room'; + const roomType = isDirect ? 'Direct Message' : 'Group Room'; + announce(`${roomName}, ${roomType}. ${remaining} room${remaining === 1 ? '' : 's'} unread.`); + }, + [mx, mDirects, roomToParents, navigate] + ); + + /** Alt+N: jump to the top-priority unread room and reset the cycle index. */ + const handleNextUnreadKeyDown = useCallback( + (evt: KeyboardEvent) => { + if (!isKeyHotkey('alt+n', evt)) return; + const unreadEntries = Array.from(roomToUnread.entries()) + .filter(([id, u]) => u.total > 0 && id !== currentRoomId) + .sort((a, b) => b[1].highlight - a[1].highlight || b[1].total - a[1].total); + if (unreadEntries.length === 0) return; + evt.preventDefault(); + unreadIndexRef.current = 0; + const [roomId] = unreadEntries[0]; + navigateToRoom(roomId, unreadEntries.length - 1); + }, + [roomToUnread, currentRoomId, navigateToRoom] + ); + + /** Alt+Shift+Down / Alt+Shift+Up: cycle through unread rooms. */ + const handleUnreadNavKeyDown = useCallback( + (evt: KeyboardEvent) => { + const isDown = isKeyHotkey('alt+shift+down', evt); + const isUp = isKeyHotkey('alt+shift+up', evt); + if (!isDown && !isUp) return; + const unreadEntries = Array.from(roomToUnread.entries()) + .filter(([, u]) => u.total > 0) + .sort((a, b) => b[1].highlight - a[1].highlight || b[1].total - a[1].total); + if (unreadEntries.length === 0) return; + evt.preventDefault(); + if (isDown) { + unreadIndexRef.current = (unreadIndexRef.current + 1) % unreadEntries.length; + } else { + unreadIndexRef.current = + (unreadIndexRef.current - 1 + unreadEntries.length) % unreadEntries.length; + } + const [roomId] = unreadEntries[unreadIndexRef.current]; + navigateToRoom(roomId, unreadEntries.length - 1); + }, + [roomToUnread, navigateToRoom] + ); + + useKeyDown(window, handleNextUnreadKeyDown); + useKeyDown(window, handleUnreadNavKeyDown); + + return null; +} diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index dafeb726..34f350b3 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -35,6 +35,7 @@ import { Account } from './account'; import { General } from './general'; import { Cosmetics } from './cosmetics/Cosmetics'; import { Experimental } from './experimental/Experimental'; +import { KeyboardShortcuts } from './keyboard-shortcuts'; export enum SettingsPages { GeneralPage, @@ -46,6 +47,7 @@ export enum SettingsPages { DeveloperToolsPage, ExperimentalPage, AboutPage, + KeyboardShortcutsPage, } type SettingsMenuItem = { @@ -104,6 +106,11 @@ const useSettingsMenuItems = (): SettingsMenuItem[] => name: 'About', icon: Icons.Info, }, + { + page: SettingsPages.KeyboardShortcutsPage, + name: 'Keyboard Shortcuts', + icon: Icons.BlockCode, + }, ], [] ); @@ -259,6 +266,9 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { )} {activePage === SettingsPages.AboutPage && } + {activePage === SettingsPages.KeyboardShortcutsPage && ( + + )} ); } diff --git a/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx b/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx new file mode 100644 index 00000000..0ce94a9c --- /dev/null +++ b/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx @@ -0,0 +1,159 @@ +/** + * Keyboard Shortcuts settings page. + * + * Lists all keyboard shortcuts available in Sable in a semantic, + * screen-reader-friendly dl/dt/dd structure. + */ +import { Box, Icon, IconButton, Icons, Scroll, Text, config } from 'folds'; +import { Page, PageContent, PageHeader } from '$components/page'; + +type ShortcutEntry = { + keys: string; + description: string; +}; + +type ShortcutCategory = { + name: string; + shortcuts: ShortcutEntry[]; +}; + +function formatKey(key: string): string { + const isMac = + typeof navigator !== 'undefined' && navigator.platform.toUpperCase().indexOf('MAC') >= 0; + return key + .replace(/\bmod\b/g, isMac ? '⌘' : 'Ctrl') + .replace(/\balt\b/gi, isMac ? '⌥' : 'Alt') + .replace(/\bshift\b/gi, '⇧') + .replace(/\+/g, '+'); +} + +const SHORTCUT_CATEGORIES: ShortcutCategory[] = [ + { + name: 'Navigation', + shortcuts: [ + { keys: 'Alt+N', description: 'Jump to the highest-priority unread room' }, + { keys: 'Alt+Shift+Down', description: 'Go to next unread room (cycle)' }, + { keys: 'Alt+Shift+Up', description: 'Go to previous unread room (cycle)' }, + ], + }, + { + name: 'Messages', + shortcuts: [ + { keys: 'Ctrl+Z / ⌘+Z', description: 'Undo in message editor' }, + { keys: 'Ctrl+Shift+Z / ⌘+Shift+Z', description: 'Redo in message editor' }, + { keys: 'Ctrl+B / ⌘+B', description: 'Bold' }, + { keys: 'Ctrl+I / ⌘+I', description: 'Italic' }, + { keys: 'Ctrl+U / ⌘+U', description: 'Underline' }, + ], + }, +]; + +function ShortcutRow({ keys, description }: ShortcutEntry) { + const parts = keys.split('/').map((k) => k.trim()); + return ( +
+ + {description} + + + {parts.map((part, i) => ( + + {part.split('+').map((seg, si, arr) => ( + + + {formatKey(seg)} + + {si < arr.length - 1 && ( + + )} + + ))} + {i < parts.length - 1 && ( + + {' / '} + + )} + + ))} + +
+ ); +} + +type KeyboardShortcutsProps = { + requestClose: () => void; +}; +export function KeyboardShortcuts({ requestClose }: KeyboardShortcutsProps) { + return ( + + + + + + Keyboard Shortcuts + + + + + + + + + + + + + + {SHORTCUT_CATEGORIES.map((category) => ( + + + {category.name} + +
+ {category.shortcuts.map((entry) => ( +
+
{entry.keys}
+
+ +
+
+ ))} +
+
+ ))} +
+
+
+
+
+ ); +} diff --git a/src/app/features/settings/keyboard-shortcuts/index.ts b/src/app/features/settings/keyboard-shortcuts/index.ts new file mode 100644 index 00000000..c786400a --- /dev/null +++ b/src/app/features/settings/keyboard-shortcuts/index.ts @@ -0,0 +1 @@ +export * from './KeyboardShortcuts'; diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index a5891db6..f5473463 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -23,6 +23,7 @@ import { getFallbackSession, MATRIX_SESSIONS_KEY, Sessions } from '$state/sessio import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage'; import { NotificationJumper } from '$hooks/useNotificationJumper'; import { SearchModalRenderer } from '$features/search'; +import { GlobalKeyboardShortcuts } from '$components/GlobalKeyboardShortcuts'; import { AuthLayout, Login, Register, ResetPassword } from './auth'; import { DIRECT_PATH, @@ -170,6 +171,22 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) + + {/* Screen reader live region — populated by announce() in utils/announce.ts */} +
diff --git a/src/app/pages/auth/login/PasswordLoginForm.tsx b/src/app/pages/auth/login/PasswordLoginForm.tsx index 6b7a0471..d0e2f099 100644 --- a/src/app/pages/auth/login/PasswordLoginForm.tsx +++ b/src/app/pages/auth/login/PasswordLoginForm.tsx @@ -199,10 +199,11 @@ export function PasswordLoginForm({ defaultUsername, defaultEmail }: PasswordLog return ( - + Username - + Password - + {loginState.status === AsyncStatus.Error && ( <> diff --git a/src/app/pages/auth/register/PasswordRegisterForm.tsx b/src/app/pages/auth/register/PasswordRegisterForm.tsx index 7dacb7f0..e363ea62 100644 --- a/src/app/pages/auth/register/PasswordRegisterForm.tsx +++ b/src/app/pages/auth/register/PasswordRegisterForm.tsx @@ -258,10 +258,11 @@ export function PasswordRegisterForm({ <> - + Username ( <> - + Password - + Confirm Password {hasStageInFlows(uiaFlows, AuthType.RegistrationToken) && ( - + {requiredStageInFlows(uiaFlows, AuthType.RegistrationToken) ? 'Registration Token' : 'Registration Token (Optional)'} - + {requiredStageInFlows(uiaFlows, AuthType.Email) ? 'Email' : 'Email (Optional)'} { + el.textContent = msg; + }); +} From 511f28956ee2d97b8895a2a38deb7fd2f83da464 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 00:57:05 -0600 Subject: [PATCH 086/124] Replaced the monochrome mode with a saturation slider for more control. --- .changeset/y_saturation_slider.md | 5 ++++ .../features/settings/cosmetics/Themes.tsx | 25 ++++++++++++++++--- src/app/pages/ThemeManager.tsx | 9 ++++--- src/app/state/settings.ts | 17 ++++++++++--- 4 files changed, 46 insertions(+), 10 deletions(-) create mode 100644 .changeset/y_saturation_slider.md diff --git a/.changeset/y_saturation_slider.md b/.changeset/y_saturation_slider.md new file mode 100644 index 00000000..77fbb35b --- /dev/null +++ b/.changeset/y_saturation_slider.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Replaced the monochrome mode with a saturation slider for more control. diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 714bbd57..778550b1 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -244,7 +244,7 @@ function SystemThemePreferences() { function ThemeSettings() { const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); - const [monochromeMode, setMonochromeMode] = useSetting(settingsAtom, 'monochromeMode'); + const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); return ( @@ -274,8 +274,27 @@ function ThemeSettings() { } + title="Saturation" + description={`${saturation}%`} + after={ + setSaturation(parseInt(e.target.value, 10))} + style={{ + width: toRem(160), + cursor: 'pointer', + appearance: 'none', + height: toRem(6), + borderRadius: config.radii.Pill, + backgroundColor: 'var(--sable-surface-container-line)', + accentColor: 'var(--sable-primary-main)', + }} + /> + } /> diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index dea860f9..49319d55 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -30,20 +30,21 @@ export function UnAuthRouteThemeManager() { export function AuthRouteThemeManager({ children }: { children: ReactNode }) { const activeTheme = useActiveTheme(); - const [monochromeMode] = useSetting(settingsAtom, 'monochromeMode'); + const [saturation] = useSetting(settingsAtom, 'saturationLevel'); useEffect(() => { document.body.className = ''; document.body.classList.add(configClass, varsClass); - document.body.classList.add(...activeTheme.classNames); - if (monochromeMode) { + if (saturation === 0) { document.body.style.filter = 'grayscale(1)'; + } else if (saturation && saturation < 100) { + document.body.style.filter = `saturate(${saturation}%)`; } else { document.body.style.filter = ''; } - }, [activeTheme, monochromeMode]); + }, [activeTheme, saturation]); return {children}; } diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index d7067171..5ae12802 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -22,7 +22,7 @@ export interface Settings { useSystemTheme: boolean; lightThemeId?: string; darkThemeId?: string; - monochromeMode?: boolean; + saturationLevel?: number; uniformIcons: boolean; isMarkdown: boolean; editorToolbar: boolean; @@ -90,7 +90,7 @@ const defaultSettings: Settings = { useSystemTheme: true, lightThemeId: undefined, darkThemeId: undefined, - monochromeMode: false, + saturationLevel: 100, uniformIcons: false, isMarkdown: true, editorToolbar: false, @@ -157,9 +157,20 @@ const defaultSettings: Settings = { export const getSettings = () => { const settings = localStorage.getItem(STORAGE_KEY); if (settings === null) return defaultSettings; + + // migration for old keys + // monochrome -> saturation + const parsed = JSON.parse(settings); + if (parsed.monochromeMode === true && parsed.saturationLevel === undefined) { + parsed.saturationLevel = 0; + } else if (parsed.monochromeMode === false && parsed.saturationLevel === undefined) { + parsed.saturationLevel = 100; + } + delete parsed.monochromeMode; + return { ...defaultSettings, - ...(JSON.parse(settings) as Settings), + ...(parsed as Settings), }; }; From 54d61fc57dd3a37f8cd2bd5c3511dbe4c88baeb5 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 01:02:48 -0600 Subject: [PATCH 087/124] option to underline links --- .changeset/y_always_underline_links.md | 5 +++++ src/app/features/settings/cosmetics/Themes.tsx | 8 ++++++++ src/app/pages/ThemeManager.tsx | 9 ++++++++- src/app/state/settings.ts | 2 ++ src/index.css | 6 ++++++ 5 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 .changeset/y_always_underline_links.md diff --git a/.changeset/y_always_underline_links.md b/.changeset/y_always_underline_links.md new file mode 100644 index 00000000..793daf3e --- /dev/null +++ b/.changeset/y_always_underline_links.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Added setting to always underline links. diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 778550b1..6203ad8b 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -245,6 +245,7 @@ function SystemThemePreferences() { function ThemeSettings() { const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); + const [underlineLinks, setUnderlineLinks] = useSetting(settingsAtom, 'underlineLinks'); return ( @@ -297,6 +298,13 @@ function ThemeSettings() { } /> + + } + /> + ); } diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 49319d55..2b335012 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -31,12 +31,19 @@ export function UnAuthRouteThemeManager() { export function AuthRouteThemeManager({ children }: { children: ReactNode }) { const activeTheme = useActiveTheme(); const [saturation] = useSetting(settingsAtom, 'saturationLevel'); + const [underlineLinks] = useSetting(settingsAtom, 'underlineLinks'); useEffect(() => { document.body.className = ''; document.body.classList.add(configClass, varsClass); document.body.classList.add(...activeTheme.classNames); + if (underlineLinks) { + document.body.classList.add('force-underline-links'); + } else { + document.body.classList.remove('force-underline-links'); + } + if (saturation === 0) { document.body.style.filter = 'grayscale(1)'; } else if (saturation && saturation < 100) { @@ -44,7 +51,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { } else { document.body.style.filter = ''; } - }, [activeTheme, saturation]); + }, [activeTheme, saturation, underlineLinks]); return {children}; } diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 5ae12802..5daaad09 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -80,6 +80,7 @@ export interface Settings { showPingCounts: boolean; hideReads: boolean; emojiSuggestThreshold: number; + underlineLinks: boolean; // furry stuff renderAnimals: boolean; @@ -149,6 +150,7 @@ const defaultSettings: Settings = { showPingCounts: true, hideReads: false, emojiSuggestThreshold: 2, + underlineLinks: false, // furry stuff renderAnimals: true, diff --git a/src/index.css b/src/index.css index 5935979f..cebe1da7 100755 --- a/src/index.css +++ b/src/index.css @@ -174,3 +174,9 @@ pre { letter-spacing: -0.01em; font-variant-ligatures: contextual; } + +.force-underline-links a { + text-decoration: underline !important; + text-decoration-thickness: 1px; + text-underline-offset: 2px; +} From b050cd01f9ada1f253b0f5f50c6c1eddaf929978 Mon Sep 17 00:00:00 2001 From: Krishan <33421343+kfiven@users.noreply.github.com> Date: Sat, 7 Mar 2026 18:03:32 +1100 Subject: [PATCH 088/124] feat: Add voice/video room support (#2680) * Add users on the nav to showcase call activity and who is in the call * add check to prevent DCing from the call you're currently in... * Add avatar and username for the space (needs to be moved into RoomNavItem proper) * Add background variant to buttons * Update hook to keep method signature (accepting an array of Rooms instead) to support multiple room event tracking of the same event * Add state listener so the call activity is real time updated on joins/leaves within the space * Add RoomNavUser for displaying the user avatar + name in the nav for a visual of call activity and participants * rename CallNavBottom to CallNavStatus * Rename callnavbottom and fix linking implementation to actually be correct * temp fix to allow the status to be cleared in some way * re-add background to active call link button * prepare to feed this to child elements for visibility handling * loosely provide nav handling for testing refactoring * Add CallView * Update to funnel Outlet context through for Call handling (might not be the best approach, but removes code replication in PersistentCallContainer where we were remaking the roomview entirely) * update client layout to funnel outlet the iframes for the call container * funnel through just iframe for now for testing sake * Update room to use CallView * Pass forward the backupIframeRef now * remove unused params * Add backupIframeRef so we can re-add the lobby screen for non-joined calls (for viewing their text channels) * Remove unused imports and restructure to support being parent to clientlayout * Re-add layout as we're no longer oddly passing outlet context * swap to using ref provider context from to connect to persistentcallcontainer more directly * Revert to original code as we've moved calling to be more inline with design * Revert to original code as we've moved the outlet context passing out and made more direct use of the ref * Fix unexpected visibility in non-room areas * correctly provide visibility * re-add mobile chat handling * Improve call room view stability * split into two refs * add ViewedRoom usage * Disable * add roomViewId and related * (broken) juggle the iframe states proper... still needs fixing * Conditionals to manage the active iframe state better * add navigateRoom to be in both conditions for the nav button * Fix the view to correctly display the active iframe based on which is currently hosting the active call (juggling views) * Testing the iframe juggling. Seems to work for the first and second joins... so likely on the right path with this * add url as a param for widget url * fix backup iframe visibility * Much closer to the call state handling we want w/ hangups and joins * Fix the position of the member drawer to its correct location * Ensure drawer doesn't appear in call room * Better handling of the isCallActive in the join handler * Add ideal call room join behavior where text rooms to call room simply joins, but doesn't swap current view * Fix mobile call room default behavior from auto-join to displaying lobby * swap call status to be bound to call state and not active call id * Remove clean room ID and add default handler for if no active call has existed yet, but user clicks on show chat * Applies the correct changes to the call state and removes listeners of old active widget so we don't trigger hang ups on the new one (the element-call widget likes to spam the hang up response back several times for some reason long after you tell it to hang up) * Remove superfluous comments and Date.now() that was causing loading... bug when widgetId desynced * Remove Date.now() that was causing widgetId desync * add listener clearing, camel case es lint rule exception, remove unneeded else statements * Remove unused * Add widgetId as a getWidgetUrl param * Remove no longer needed files * revert ternary expression change and add to dependency array * add widgetId to correct pos in getWidgetUrl usage * Remove CallActivation * Move and rename RoomCallNavStatus * update imports and dependency array * Rename and clean up * Moved CallProvider * Fix spelling mistake * Fix to use shorthand prop * Remove unneeded logger.errors * Fixes element-call embedded support (but it seems to run poorly) * null the default url so that we fallback to the embedded version (would recommend hosting it until performance issue is determined) * Fix vite build to place element-call correctly for embedded npm package support * add vite preview as an npm script * Move files to more correct location * Add package-lock changes * Set dep version to exact * Fix path issue from moving file locations * Sets initial states so the iframes don't cause the other to fail with the npm embedded package * Revert navitem change * Just check for state on both which should only occur at initial * Fixes call initializing by default on mobile * Provides correct behavior when call isn't active and no activeClientWidgetApi exists yet * Corrects the state for the situations where both iframes are "active" (not necessarily visible) * Reduce code reuse in handleJoin * Seems to sort out the hangup status button bug the occurred after joining a call via lobby * Re-add the default view current active room behavior * Remove repetitive check * Add storing widget for comparing with (since we already store room id and the clientWidgetApi anyway) * Update rendering logic to clear up remaining rendering bug (straight to call -> lobby of another room and joining call from that interface -> lobby of that previous room and joining was leading to duplication of the user in lobbies. This was actually from listening to and acknowledging hangups from the viewed widget in CallProvider) * Prevent null rooms from ever rendering * This seems to manage the hangup state with the status bar button well enough that black screens should never be encountered * Remove viewed room setting here and pass the room to hang up (seems state doesn't update fast enough otherwise) * Remove unused * Properly declare new hangup method sig * Seems to avoid almost all invalid states (hang up while viewing another lobby and hitting join seems to black screen, sets the active call as the previous active room id, but does join the viewed room correctly) * Fix for cases where you're viewing a lobby and hang up your existing call and try to join lobby (was not rendering for the correct room id, but was joining the correct call prior) * Re-add intended switching behavior * More correct filter (viewedRoom can return false on that compare in some cases) * Seems to shore up the remaining state issues with the status bar hangup * Fix formatting * In widget hang up button should be handled correct now * Solves the CHCH sequence issue, CLJH remains * Fixes CLJH, found CCH * Solves CCH. Looks like CLCH left * A bit of an abomination, but adds a state counter to iteratively handle the diverse potential states (where a user can join from the nav bar or the join button, hang up from either as well, and account for the juggling iframes) Black screens shouldn't be occurring now. * Fix dependency array * Technically corrects the hangup button in the widget, should be more precise though * Bind the on messaging iframe for easier access in hangup/join handling * Far cleaner and more sensible handling of the call window... I just really don't like the idea of sending a click event, but right now the element-call code treats preload/skipLobby hangups (sent from our end) as if they had no lobby at all and thus black screens. Other implementation was working around that without just sending a click event on the iframe's hangup button. * Fixes a bug where if you left a call then went to a lobby and joined it didn't update the actual activeCallRoomId * Fixes complaints of null contentDocument in iframe * Update to use new icons (thank you) * Remove unneeded prop * Re-arrange more options and add checks for each option to see if it is a call room (probably should manage a state to see if a header is already on screen and provide a slightly modified visual based on that for call rooms) * Invert icons to show the state instead of the action they will perform (more visual clarity) * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomCallNavStatus.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavItem.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavUser.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavUser.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room-nav/RoomNavUser.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/pages/client/space/Space.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/call/CallView.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/call/CallView.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/call/CallView.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomView.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomView.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * adjust room header for calling * Remove No Active Call text when not in a call * update element-call version * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Update src/app/features/room/RoomViewHeader.tsx Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> * Revert most changes to Space.tsx * Show call room even if category is collapsed * changes to RoomNavItem, RoomNavUser and add useCallMembers * Rename file, sprinkle in the magic one line for matrixRTCSession. and remove comment block * swap userId to callMembership as a prop and add a nullchecked userId that uses the membership sender * update references to use callMembership instead * Simplify RoomNavUser Discard future functionality since it probably won't exist in time for merging this PR * Simplify RoomViewHeader.tsx Remove unused UI elements that don't have implemented functionality. Replace custom function for checking if a room is direct with a standard hook. * Update Room.tsx to accomodate restructuring of Room, RoomView and CallView * Update RoomView.tsx to accomodate restructuring of Room, RoomView and CallView * Update CallView.tsx to accomodate restructuring of Room, RoomView and CallView + suggested changes * add call related permissions to room permissions * bump element call to 0.16.3, apply cinny theme to element call ui, replace element call lobby (backup iframe) with custom ui and only use element call for the in-call ui * update text spacing * redo roomcallnavstatus ui, force user preferred mute/video states when first joining calls, update variable names and remove unnecessary logic * set default mic state to enabled * clean up ts/eslint errors * remove debug logs * format using prettier rules from project prettierrc * fix: show call nav status while active call is ongoing * fix: clean up call nav/call view console warnings * fix: keep call media controls visible before joining * fix: restore header icon button fill behavior Fixes regression from b074d421b66eb4d8b600dfa55b967e6c4f783044. * style: blend header and room input button styles in call nav * fix page header background color on room view header * fix: permissions and room icon resolution (#2) * Initialize call state upon room creation for call rooms, remove subsequent useless permission * handle case of missing call permissions * use call icon for room item summary when room is call room * replace previous icon src resolution function with a more robust approach * replace usages of previous icon resolution function with new implementation * fix room name not updating for a while when changed * set up framework for room power level overrides upon room creation * override join call permission to all members upon room creation * fix broken usages of RoomIcon * remove unneeded import * remove unnecessary logic * format with prettier * feat: show connected/connecting call status * fix: preserve navigation context when opening non-call rooms * fix: reset room name state when room instance changes * feat: Disable webcam by default using callIntent='audio' * Add channel type selecor * Add option for voice rooms, which for now sets the default selected option in the creation modal * Add proper support for room selection from the enu * Move enums to `types.ts` and change icons selection to use `getRoomIconSrc` * fix: group duplicate conditions into one * fix: typo * refactor: rename kind/voice to access/type and simplify room creation - rename CreateRoomVoice to CreateRoomType and modal voice state to type - rename CreateRoomKind to CreateRoomAccess and KindSelector to AccessSelector - propagate access/defaultAccess through create room and create space forms - set voice room power levels via createRoom power_level_content_override * refactor: unify join rule icon mapping and update call/space icons - bump folds from 2.5.0 to 2.6.0 - replace separate room/space join-rule icon hooks with useJoinRuleIcons(roomType) - route join-rule icons through getRoomIconSrc for consistent room type handling - simplify getRoomIconSrc by removing the locked override path - use VolumeHighGlobe for public call rooms and VolumeHighLock for private call rooms * chore(deps): bump matrix-widget-api to 1.17 and remove react-sdk-module-api * fix: adapt SmallWidget to matrix-widget-api 1.17.0 API * fix: render call room chat only when chat panel is open * fix(permissions): show call settings permissions only for call rooms * refactor: remove redundant room-nav props/guards and minor naming cleanup * fix: use PhoneDown icon for hang up action * chore(hooks): remove unused useStateEvents hook * fix(room): enable members drawer toggle in desktop call rooms - show filled User icon when the drawer is open * Revert "fix: adapt SmallWidget to matrix-widget-api 1.17.0 API" This reverts commit a4c34eff8a53669afa095be41b26f3e54adab0ed. * fix: semi-revert matrix-widget-api 1.17 bump and migrate to 1.13 API * fix(call): wait for Element Call contentLoaded before widget handshake - fixes not working on firefox * fix missing imports * improve create room type design and add beta badge for voice room * add beta badge for voice room in space lobby * fix create room modal title * pass missing roomType param to roomicon component * add roomtype * Add deafen functionality (#2695) * feat:(deafen functionality) * feat:(reworked voice controls for deafen) * ref:(use muted instead of volume for deafen) * fix:(backpedal audio_enabled rename) * ref:(renaming of deafened vars) * add stack avatar component * add call status bar - WIP * remove call status from navigation drawer * fix deprecated method use in use call members hook * render new call status bar * move call widget driver to plugins * remove old status bar usage from navigation drawer * add call session and joined hook * remove unknown changes * upgrade widget api * add element call embed plugin * remove unknown change * add call embed atom * add call embed hooks and context * add call embed provider * replace old call implementation * stop joining other call on second click if already in a call * refactor embed placement hook * add merge border prop to sequence card * add call preferences * add prescreen to call view - WIP * prevent joining new call if already in call * make call layout adaptive * render call chat as right panel * show call members in prescreen * render call join leave event in timeline * remove unknown rewrite in docker-nginx file * render call event without hidden event enable --------- Co-authored-by: Gigiaj Co-authored-by: Jaggar <18173108+GigiaJ@users.noreply.github.com> Co-authored-by: Gimle Larpes <97182804+GimleLarpes@users.noreply.github.com> Co-authored-by: Gimle Larpes Co-authored-by: YoJames2019 Co-authored-by: YoJames2019 Co-authored-by: hazre Co-authored-by: haz <37149950+hazre@users.noreply.github.com> Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com> Co-authored-by: James <49845975+YoJames2019@users.noreply.github.com> Co-authored-by: James Reilly Co-authored-by: Tymek Co-authored-by: Thedustbuster <92692948+Thedustbustr@users.noreply.github.com> --- config.json | 10 +- package-lock.json | 15 +- package.json | 3 + src/app/components/CallEmbedProvider.tsx | 63 +++ src/app/components/JoinRulesSwitcher.tsx | 30 +- ...ector.tsx => CreateRoomAccessSelector.tsx} | 48 ++- .../create-room/CreateRoomTypeSelector.tsx | 75 ++++ src/app/components/create-room/index.ts | 3 +- src/app/components/create-room/types.ts | 10 + src/app/components/create-room/utils.ts | 30 +- .../autocomplete/RoomMentionAutocomplete.tsx | 3 +- src/app/components/room-avatar/RoomAvatar.tsx | 14 +- .../components/sequence-card/SequenceCard.tsx | 3 +- src/app/components/sequence-card/style.css.ts | 13 +- .../stacked-avatar/StackedAvatar.tsx | 18 + src/app/components/stacked-avatar/index.ts | 1 + .../components/stacked-avatar/styles.css.ts | 59 +++ src/app/components/user-profile/UserChips.tsx | 2 +- src/app/features/add-existing/AddExisting.tsx | 6 +- src/app/features/call-status/CallControl.tsx | 168 ++++++++ src/app/features/call-status/CallRoomName.tsx | 55 +++ src/app/features/call-status/CallStatus.tsx | 52 +++ src/app/features/call-status/LiveChip.tsx | 137 +++++++ src/app/features/call-status/MemberGlance.tsx | 72 ++++ src/app/features/call-status/components.tsx | 9 + src/app/features/call-status/index.ts | 1 + src/app/features/call-status/styles.css.ts | 17 + src/app/features/call/CallMemberCard.tsx | 121 ++++++ src/app/features/call/CallView.tsx | 105 +++++ src/app/features/call/Controls.tsx | 145 +++++++ src/app/features/call/PrescreenControls.tsx | 68 ++++ src/app/features/call/styles.css.ts | 20 + .../common-settings/general/RoomJoinRules.tsx | 8 +- .../common-settings/general/RoomProfile.tsx | 4 +- src/app/features/create-room/CreateRoom.tsx | 85 +++-- .../features/create-room/CreateRoomModal.tsx | 9 +- src/app/features/create-space/CreateSpace.tsx | 46 +-- src/app/features/lobby/LobbyHeader.tsx | 15 +- src/app/features/lobby/RoomItem.tsx | 8 +- src/app/features/lobby/SpaceItem.tsx | 20 +- .../features/message-search/SearchFilters.tsx | 11 +- .../message-search/SearchResultGroup.tsx | 7 +- src/app/features/room-nav/RoomNavItem.tsx | 77 +++- .../features/room-settings/RoomSettings.tsx | 1 + .../room-settings/permissions/Permissions.tsx | 2 +- .../permissions/usePermissionItems.ts | 18 +- src/app/features/room/CallChatView.tsx | 57 +++ src/app/features/room/Room.tsx | 36 +- src/app/features/room/RoomTimeline.tsx | 46 +++ src/app/features/room/RoomView.tsx | 10 +- src/app/features/room/RoomViewHeader.tsx | 79 +++- src/app/features/search/Search.tsx | 2 +- .../features/space-settings/SpaceSettings.tsx | 2 +- src/app/hooks/useCall.ts | 55 +++ src/app/hooks/useCallEmbed.ts | 130 +++++++ src/app/hooks/useRoomMeta.ts | 2 + src/app/hooks/useStateEvents.ts | 28 -- src/app/pages/CallStatusRenderer.tsx | 11 + src/app/pages/Router.tsx | 23 +- .../pages/client/ClientInitStorageAtom.tsx | 8 +- src/app/pages/client/inbox/Notifications.tsx | 7 +- src/app/pages/client/space/Space.tsx | 13 +- src/app/plugins/call/CallControl.ts | 117 ++++++ src/app/plugins/call/CallControlState.ts | 13 + src/app/plugins/call/CallEmbed.ts | 358 ++++++++++++++++++ src/app/plugins/call/CallWidgetDriver.ts | 340 +++++++++++++++++ src/app/plugins/call/hooks.ts | 49 +++ src/app/plugins/call/index.ts | 3 + src/app/plugins/call/types.ts | 25 ++ src/app/plugins/call/utils.ts | 118 ++++++ src/app/state/callEmbed.ts | 20 + src/app/state/callPreferences.ts | 39 ++ src/app/state/createRoomModal.ts | 2 + src/app/state/hooks/callPreferences.ts | 61 +++ src/app/state/hooks/createRoomModal.ts | 7 +- src/app/utils/room.ts | 51 ++- src/types/matrix/room.ts | 3 + vite.config.js | 13 +- 78 files changed, 3154 insertions(+), 261 deletions(-) create mode 100644 src/app/components/CallEmbedProvider.tsx rename src/app/components/create-room/{CreateRoomKindSelector.tsx => CreateRoomAccessSelector.tsx} (54%) create mode 100644 src/app/components/create-room/CreateRoomTypeSelector.tsx create mode 100644 src/app/components/create-room/types.ts create mode 100644 src/app/components/stacked-avatar/StackedAvatar.tsx create mode 100644 src/app/components/stacked-avatar/index.ts create mode 100644 src/app/components/stacked-avatar/styles.css.ts create mode 100644 src/app/features/call-status/CallControl.tsx create mode 100644 src/app/features/call-status/CallRoomName.tsx create mode 100644 src/app/features/call-status/CallStatus.tsx create mode 100644 src/app/features/call-status/LiveChip.tsx create mode 100644 src/app/features/call-status/MemberGlance.tsx create mode 100644 src/app/features/call-status/components.tsx create mode 100644 src/app/features/call-status/index.ts create mode 100644 src/app/features/call-status/styles.css.ts create mode 100644 src/app/features/call/CallMemberCard.tsx create mode 100644 src/app/features/call/CallView.tsx create mode 100644 src/app/features/call/Controls.tsx create mode 100644 src/app/features/call/PrescreenControls.tsx create mode 100644 src/app/features/call/styles.css.ts create mode 100644 src/app/features/room/CallChatView.tsx create mode 100644 src/app/hooks/useCall.ts create mode 100644 src/app/hooks/useCallEmbed.ts delete mode 100644 src/app/hooks/useStateEvents.ts create mode 100644 src/app/pages/CallStatusRenderer.tsx create mode 100644 src/app/plugins/call/CallControl.ts create mode 100644 src/app/plugins/call/CallControlState.ts create mode 100644 src/app/plugins/call/CallEmbed.ts create mode 100644 src/app/plugins/call/CallWidgetDriver.ts create mode 100644 src/app/plugins/call/hooks.ts create mode 100644 src/app/plugins/call/index.ts create mode 100644 src/app/plugins/call/types.ts create mode 100644 src/app/plugins/call/utils.ts create mode 100644 src/app/state/callEmbed.ts create mode 100644 src/app/state/callPreferences.ts create mode 100644 src/app/state/hooks/callPreferences.ts diff --git a/config.json b/config.json index 644f0eb6..aed232e6 100644 --- a/config.json +++ b/config.json @@ -1,12 +1,6 @@ { "defaultHomeserver": 1, - "homeserverList": [ - "converser.eu", - "matrix.org", - "mozilla.org", - "unredacted.org", - "xmr.se" - ], + "homeserverList": ["converser.eu", "matrix.org", "mozilla.org", "unredacted.org", "xmr.se"], "allowCustomHomeservers": true, "featuredCommunities": { @@ -27,7 +21,7 @@ "#PrivSec.dev:arcticfoxes.net", "#disroot:aria-net.org" ], - "servers": [ "matrix.org", "mozilla.org", "unredacted.org" ] + "servers": ["matrix.org", "mozilla.org", "unredacted.org"] }, "hashRouter": { diff --git a/package-lock.json b/package-lock.json index 05466866..4648a9fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "linkify-react": "4.3.2", "linkifyjs": "4.3.2", "matrix-js-sdk": "38.2.0", + "matrix-widget-api": "1.17.0", "millify": "6.1.0", "pdfjs-dist": "4.2.67", "prismjs": "1.30.0", @@ -65,6 +66,7 @@ "ua-parser-js": "1.0.35" }, "devDependencies": { + "@element-hq/element-call-embedded": "0.16.3", "@esbuild-plugins/node-globals-polyfill": "0.2.3", "@rollup/plugin-inject": "5.0.3", "@rollup/plugin-wasm": "6.1.1", @@ -1649,6 +1651,12 @@ "node": ">=6.9.0" } }, + "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/@emotion/hash": { "version": "0.9.2", "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz", @@ -8666,9 +8674,9 @@ } }, "node_modules/matrix-widget-api": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.13.1.tgz", - "integrity": "sha512-mkOHUVzaN018TCbObfGOSaMW2GoUxOfcxNNlTVx5/HeMk3OSQPQM0C9oEME5Liiv/dBUoSrEB64V8wF7e/gb1w==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.17.0.tgz", + "integrity": "sha512-5FHoo3iEP3Bdlv5jsYPWOqj+pGdFQNLWnJLiB0V7Ygne7bb+Gsj3ibyFyHWC6BVw+Z+tSW4ljHpO17I9TwStwQ==", "license": "Apache-2.0", "dependencies": { "@types/events": "^3.0.0", @@ -10909,6 +10917,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/package.json b/package.json index de8ee72d..4eeead2d 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "scripts": { "start": "vite", "build": "vite build", + "preview": "vite preview", "lint": "yarn check:eslint && yarn check:prettier", "check:eslint": "eslint src/*", "check:prettier": "prettier --check .", @@ -55,6 +56,7 @@ "linkify-react": "4.3.2", "linkifyjs": "4.3.2", "matrix-js-sdk": "38.2.0", + "matrix-widget-api": "1.17.0", "millify": "6.1.0", "pdfjs-dist": "4.2.67", "prismjs": "1.30.0", @@ -76,6 +78,7 @@ "ua-parser-js": "1.0.35" }, "devDependencies": { + "@element-hq/element-call-embedded": "0.16.3", "@esbuild-plugins/node-globals-polyfill": "0.2.3", "@rollup/plugin-inject": "5.0.3", "@rollup/plugin-wasm": "6.1.1", diff --git a/src/app/components/CallEmbedProvider.tsx b/src/app/components/CallEmbedProvider.tsx new file mode 100644 index 00000000..9f4b3f2b --- /dev/null +++ b/src/app/components/CallEmbedProvider.tsx @@ -0,0 +1,63 @@ +import React, { ReactNode, useCallback, useRef } from 'react'; +import { useAtomValue, useSetAtom } from 'jotai'; +import { + CallEmbedContextProvider, + CallEmbedRefContextProvider, + useCallHangupEvent, + useCallJoined, + useCallThemeSync, +} from '../hooks/useCallEmbed'; +import { callChatAtom, callEmbedAtom } from '../state/callEmbed'; +import { CallEmbed } from '../plugins/call'; +import { useSelectedRoom } from '../hooks/router/useSelectedRoom'; +import { ScreenSize, useScreenSizeContext } from '../hooks/useScreenSize'; + +function CallUtils({ embed }: { embed: CallEmbed }) { + const setCallEmbed = useSetAtom(callEmbedAtom); + + useCallThemeSync(embed); + useCallHangupEvent( + embed, + useCallback(() => { + setCallEmbed(undefined); + }, [setCallEmbed]) + ); + + return null; +} + +type CallEmbedProviderProps = { + children?: ReactNode; +}; +export function CallEmbedProvider({ children }: CallEmbedProviderProps) { + const callEmbed = useAtomValue(callEmbedAtom); + const callEmbedRef = useRef(null); + const joined = useCallJoined(callEmbed); + + const selectedRoom = useSelectedRoom(); + const chat = useAtomValue(callChatAtom); + const screenSize = useScreenSizeContext(); + + const chatOnlyView = chat && screenSize !== ScreenSize.Desktop; + + const callVisible = callEmbed && selectedRoom === callEmbed.roomId && joined && !chatOnlyView; + + return ( + + {callEmbed && } + {children} +
+ + ); +} diff --git a/src/app/components/JoinRulesSwitcher.tsx b/src/app/components/JoinRulesSwitcher.tsx index 9507317a..bbc0a65d 100644 --- a/src/app/components/JoinRulesSwitcher.tsx +++ b/src/app/components/JoinRulesSwitcher.tsx @@ -16,34 +16,24 @@ import { import { JoinRule } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '../utils/keyboard'; +import { getRoomIconSrc } from '../utils/room'; export type ExtraJoinRules = 'knock_restricted'; export type ExtendedJoinRules = JoinRule | ExtraJoinRules; type JoinRuleIcons = Record; -export const useRoomJoinRuleIcon = (): JoinRuleIcons => + +export const useJoinRuleIcons = (roomType?: string): JoinRuleIcons => useMemo( () => ({ - [JoinRule.Invite]: Icons.HashLock, - [JoinRule.Knock]: Icons.HashLock, - knock_restricted: Icons.Hash, - [JoinRule.Restricted]: Icons.Hash, - [JoinRule.Public]: Icons.HashGlobe, - [JoinRule.Private]: Icons.HashLock, + [JoinRule.Invite]: getRoomIconSrc(Icons, roomType, JoinRule.Invite), + [JoinRule.Knock]: getRoomIconSrc(Icons, roomType, JoinRule.Knock), + knock_restricted: getRoomIconSrc(Icons, roomType, JoinRule.Restricted), + [JoinRule.Restricted]: getRoomIconSrc(Icons, roomType, JoinRule.Restricted), + [JoinRule.Public]: getRoomIconSrc(Icons, roomType, JoinRule.Public), + [JoinRule.Private]: getRoomIconSrc(Icons, roomType, JoinRule.Private), }), - [] - ); -export const useSpaceJoinRuleIcon = (): JoinRuleIcons => - useMemo( - () => ({ - [JoinRule.Invite]: Icons.SpaceLock, - [JoinRule.Knock]: Icons.SpaceLock, - knock_restricted: Icons.Space, - [JoinRule.Restricted]: Icons.Space, - [JoinRule.Public]: Icons.SpaceGlobe, - [JoinRule.Private]: Icons.SpaceLock, - }), - [] + [roomType] ); type JoinRuleLabels = Record; diff --git a/src/app/components/create-room/CreateRoomKindSelector.tsx b/src/app/components/create-room/CreateRoomAccessSelector.tsx similarity index 54% rename from src/app/components/create-room/CreateRoomKindSelector.tsx rename to src/app/components/create-room/CreateRoomAccessSelector.tsx index 096954fb..35f39af8 100644 --- a/src/app/components/create-room/CreateRoomKindSelector.tsx +++ b/src/app/components/create-room/CreateRoomAccessSelector.tsx @@ -2,43 +2,39 @@ import React from 'react'; import { Box, Text, Icon, Icons, config, IconSrc } from 'folds'; import { SequenceCard } from '../sequence-card'; import { SettingTile } from '../setting-tile'; +import { CreateRoomAccess } from './types'; -export enum CreateRoomKind { - Private = 'private', - Restricted = 'restricted', - Public = 'public', -} -type CreateRoomKindSelectorProps = { - value?: CreateRoomKind; - onSelect: (value: CreateRoomKind) => void; +type CreateRoomAccessSelectorProps = { + value?: CreateRoomAccess; + onSelect: (value: CreateRoomAccess) => void; canRestrict?: boolean; disabled?: boolean; - getIcon: (kind: CreateRoomKind) => IconSrc; + getIcon: (access: CreateRoomAccess) => IconSrc; }; -export function CreateRoomKindSelector({ +export function CreateRoomAccessSelector({ value, onSelect, canRestrict, disabled, getIcon, -}: CreateRoomKindSelectorProps) { +}: CreateRoomAccessSelectorProps) { return ( {canRestrict && ( onSelect(CreateRoomKind.Restricted)} + aria-pressed={value === CreateRoomAccess.Restricted} + onClick={() => onSelect(CreateRoomAccess.Restricted)} disabled={disabled} > } - after={value === CreateRoomKind.Restricted && } + before={} + after={value === CreateRoomAccess.Restricted && } > Restricted @@ -49,18 +45,18 @@ export function CreateRoomKindSelector({ )} onSelect(CreateRoomKind.Private)} + aria-pressed={value === CreateRoomAccess.Private} + onClick={() => onSelect(CreateRoomAccess.Private)} disabled={disabled} > } - after={value === CreateRoomKind.Private && } + before={} + after={value === CreateRoomAccess.Private && } > Private @@ -70,18 +66,18 @@ export function CreateRoomKindSelector({ onSelect(CreateRoomKind.Public)} + aria-pressed={value === CreateRoomAccess.Public} + onClick={() => onSelect(CreateRoomAccess.Public)} disabled={disabled} > } - after={value === CreateRoomKind.Public && } + before={} + after={value === CreateRoomAccess.Public && } > Public diff --git a/src/app/components/create-room/CreateRoomTypeSelector.tsx b/src/app/components/create-room/CreateRoomTypeSelector.tsx new file mode 100644 index 00000000..b1f69c39 --- /dev/null +++ b/src/app/components/create-room/CreateRoomTypeSelector.tsx @@ -0,0 +1,75 @@ +import React from 'react'; +import { Box, Text, Icon, Icons, config, IconSrc } from 'folds'; +import { SequenceCard } from '../sequence-card'; +import { SettingTile } from '../setting-tile'; +import { CreateRoomType } from './types'; +import { BetaNoticeBadge } from '../BetaNoticeBadge'; + +type CreateRoomTypeSelectorProps = { + value?: CreateRoomType; + onSelect: (value: CreateRoomType) => void; + disabled?: boolean; + getIcon: (type: CreateRoomType) => IconSrc; +}; +export function CreateRoomTypeSelector({ + value, + onSelect, + disabled, + getIcon, +}: CreateRoomTypeSelectorProps) { + return ( + + onSelect(CreateRoomType.TextRoom)} + disabled={disabled} + > + } + after={value === CreateRoomType.TextRoom && } + > + + + Chat Room + + + - Messages, photos, and videos. + + + + + onSelect(CreateRoomType.VoiceRoom)} + disabled={disabled} + > + } + after={value === CreateRoomType.VoiceRoom && } + > + + + Voice Room + + + - Live audio and video conversations. + + + + + + + ); +} diff --git a/src/app/components/create-room/index.ts b/src/app/components/create-room/index.ts index ffd9cb3d..cce6e037 100644 --- a/src/app/components/create-room/index.ts +++ b/src/app/components/create-room/index.ts @@ -1,5 +1,6 @@ -export * from './CreateRoomKindSelector'; +export * from './CreateRoomAccessSelector'; export * from './CreateRoomAliasInput'; export * from './RoomVersionSelector'; export * from './utils'; export * from './AdditionalCreatorInput'; +export * from './types'; diff --git a/src/app/components/create-room/types.ts b/src/app/components/create-room/types.ts new file mode 100644 index 00000000..8b54587d --- /dev/null +++ b/src/app/components/create-room/types.ts @@ -0,0 +1,10 @@ +export enum CreateRoomType { + TextRoom = 'text', + VoiceRoom = 'voice', +} + +export enum CreateRoomAccess { + Private = 'private', + Restricted = 'restricted', + Public = 'public', +} diff --git a/src/app/components/create-room/utils.ts b/src/app/components/create-room/utils.ts index d0a45c3d..f3e699aa 100644 --- a/src/app/components/create-room/utils.ts +++ b/src/app/components/create-room/utils.ts @@ -7,10 +7,10 @@ import { Room, } from 'matrix-js-sdk'; import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types'; -import { CreateRoomKind } from './CreateRoomKindSelector'; import { RoomType, StateEvent } from '../../../types/matrix/room'; import { getViaServers } from '../../plugins/via-servers'; import { getMxIdServer } from '../../utils/matrix'; +import { CreateRoomAccess } from './types'; export const createRoomCreationContent = ( type: RoomType | undefined, @@ -32,7 +32,7 @@ export const createRoomCreationContent = ( }; export const createRoomJoinRulesState = ( - kind: CreateRoomKind, + access: CreateRoomAccess, parent: Room | undefined, knock: boolean ) => { @@ -40,13 +40,13 @@ export const createRoomJoinRulesState = ( join_rule: knock ? JoinRule.Knock : JoinRule.Invite, }; - if (kind === CreateRoomKind.Public) { + if (access === CreateRoomAccess.Public) { content = { join_rule: JoinRule.Public, }; } - if (kind === CreateRoomKind.Restricted && parent) { + if (access === CreateRoomAccess.Restricted && parent) { content = { join_rule: knock ? ('knock_restricted' as JoinRule) : JoinRule.Restricted, allow: [ @@ -86,11 +86,23 @@ export const createRoomEncryptionState = () => ({ }, }); +export const createRoomCallState = () => ({ + type: 'org.matrix.msc3401.call', + state_key: '', + content: {}, +}); + +export const createVoiceRoomPowerLevelsOverride = () => ({ + events: { + [StateEvent.GroupCallMemberPrefix]: 0, + }, +}); + export type CreateRoomData = { version: string; type?: RoomType; parent?: Room; - kind: CreateRoomKind; + access: CreateRoomAccess; name: string; topic?: string; aliasLocalPart?: string; @@ -110,7 +122,11 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis initialState.push(createRoomParentState(data.parent)); } - initialState.push(createRoomJoinRulesState(data.kind, data.parent, data.knock)); + if (data.type === RoomType.Call) { + initialState.push(createRoomCallState()); + } + + initialState.push(createRoomJoinRulesState(data.access, data.parent, data.knock)); const options: ICreateRoomOpts = { room_version: data.version, @@ -122,6 +138,8 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis data.allowFederation, data.additionalCreators ), + power_level_content_override: + data.type === RoomType.Call ? createVoiceRoomPowerLevelsOverride() : undefined, initial_state: initialState, }; diff --git a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx index b0c64f60..377cecab 100644 --- a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx @@ -169,12 +169,13 @@ export function RoomMentionAutocomplete({ )} /> ) : ( - + )} } diff --git a/src/app/components/room-avatar/RoomAvatar.tsx b/src/app/components/room-avatar/RoomAvatar.tsx index 23f3998d..cbcd626a 100644 --- a/src/app/components/room-avatar/RoomAvatar.tsx +++ b/src/app/components/room-avatar/RoomAvatar.tsx @@ -2,7 +2,7 @@ import { JoinRule } from 'matrix-js-sdk'; import { AvatarFallback, AvatarImage, Icon, Icons, color } from 'folds'; import React, { ComponentProps, ReactEventHandler, ReactNode, forwardRef, useState } from 'react'; import * as css from './RoomAvatar.css'; -import { joinRuleToIconSrc } from '../../utils/room'; +import { getRoomIconSrc } from '../../utils/room'; import colorMXID from '../../../util/colorMXID'; type RoomAvatarProps = { @@ -44,13 +44,9 @@ export function RoomAvatar({ roomId, src, alt, renderFallback }: RoomAvatarProps export const RoomIcon = forwardRef< SVGSVGElement, Omit, 'src'> & { - joinRule: JoinRule; - space?: boolean; + joinRule?: JoinRule; + roomType?: string; } ->(({ joinRule, space, ...props }, ref) => ( - +>(({ joinRule, roomType, ...props }, ref) => ( + )); diff --git a/src/app/components/sequence-card/SequenceCard.tsx b/src/app/components/sequence-card/SequenceCard.tsx index d0e77ae6..46d5ea0f 100644 --- a/src/app/components/sequence-card/SequenceCard.tsx +++ b/src/app/components/sequence-card/SequenceCard.tsx @@ -17,6 +17,7 @@ export const SequenceCard = as< firstChild, lastChild, outlined, + mergeBorder, ...props }, ref @@ -24,7 +25,7 @@ export const SequenceCard = as< ( + ({ size, variant, className, ...props }, ref) => ( + + ) +); diff --git a/src/app/components/stacked-avatar/index.ts b/src/app/components/stacked-avatar/index.ts new file mode 100644 index 00000000..63d9f56d --- /dev/null +++ b/src/app/components/stacked-avatar/index.ts @@ -0,0 +1 @@ +export * from './StackedAvatar'; diff --git a/src/app/components/stacked-avatar/styles.css.ts b/src/app/components/stacked-avatar/styles.css.ts new file mode 100644 index 00000000..3bbf7271 --- /dev/null +++ b/src/app/components/stacked-avatar/styles.css.ts @@ -0,0 +1,59 @@ +import { ComplexStyleRule } from '@vanilla-extract/css'; +import { recipe, RecipeVariants } from '@vanilla-extract/recipes'; +import { color, config, ContainerColor, toRem } from 'folds'; + +const getVariant = (variant: ContainerColor): ComplexStyleRule => ({ + outlineColor: color[variant].Container, +}); + +export const StackedAvatar = recipe({ + base: { + backgroundColor: color.Surface.Container, + outlineStyle: 'solid', + selectors: { + '&:first-child': { + marginLeft: 0, + }, + 'button&': { + cursor: 'pointer', + }, + }, + }, + + variants: { + size: { + '200': { + marginLeft: toRem(-6), + outlineWidth: config.borderWidth.B300, + }, + '300': { + marginLeft: toRem(-9), + outlineWidth: config.borderWidth.B400, + }, + '400': { + marginLeft: toRem(-10.5), + outlineWidth: config.borderWidth.B500, + }, + '500': { + marginLeft: toRem(-13), + outlineWidth: config.borderWidth.B600, + }, + }, + variant: { + Background: getVariant('Background'), + Surface: getVariant('Surface'), + SurfaceVariant: getVariant('SurfaceVariant'), + Primary: getVariant('Primary'), + Secondary: getVariant('Secondary'), + Success: getVariant('Success'), + Warning: getVariant('Warning'), + Critical: getVariant('Critical'), + }, + }, + defaultVariants: { + size: '400', + variant: 'Surface', + }, +}); + +export type StackedAvatarVariants = RecipeVariants; diff --git a/src/app/components/user-profile/UserChips.tsx b/src/app/components/user-profile/UserChips.tsx index 53e6618b..82880634 100644 --- a/src/app/components/user-profile/UserChips.tsx +++ b/src/app/components/user-profile/UserChips.tsx @@ -323,7 +323,7 @@ export function MutualRoomsChip({ userId }: { userId: string }) { )} /> ) : ( - + )} } diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx index cbae018f..d100096b 100644 --- a/src/app/features/add-existing/AddExisting.tsx +++ b/src/app/features/add-existing/AddExisting.tsx @@ -291,7 +291,11 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM )} /> ) : ( - + )} } diff --git a/src/app/features/call-status/CallControl.tsx b/src/app/features/call-status/CallControl.tsx new file mode 100644 index 00000000..39cd975b --- /dev/null +++ b/src/app/features/call-status/CallControl.tsx @@ -0,0 +1,168 @@ +import { Box, Chip, Icon, IconButton, Icons, Text, Tooltip, TooltipProvider } from 'folds'; +import React, { useState } from 'react'; +import { StatusDivider } from './components'; +import { CallEmbed, useCallControlState } from '../../plugins/call'; + +type MicrophoneButtonProps = { + enabled: boolean; + onToggle: () => Promise; +}; +function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) { + return ( + + {enabled ? 'Turn Off Microphone' : 'Turn On Microphone'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined={!enabled} + > + + + )} + + ); +} + +type SoundButtonProps = { + enabled: boolean; + onToggle: () => void; +}; +function SoundButton({ enabled, onToggle }: SoundButtonProps) { + return ( + + {enabled ? 'Turn Off Sound' : 'Turn On Sound'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined={!enabled} + > + + + )} + + ); +} + +type VideoButtonProps = { + enabled: boolean; + onToggle: () => Promise; +}; +function VideoButton({ enabled, onToggle }: VideoButtonProps) { + return ( + + {enabled ? 'Stop Camera' : 'Start Camera'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined={enabled} + > + + + )} + + ); +} + +function ScreenShareButton() { + const [enabled, setEnabled] = useState(false); + + return ( + + {enabled ? 'Stop Screenshare' : 'Start Screenshare'} + + } + > + {(anchorRef) => ( + setEnabled(!enabled)} + outlined={enabled} + > + + + )} + + ); +} + +export function CallControl({ callEmbed }: { callEmbed: CallEmbed }) { + const { microphone, video, sound } = useCallControlState(callEmbed.control); + + return ( + + + callEmbed.control.toggleMicrophone()} + /> + callEmbed.control.toggleSound()} /> + + + + callEmbed.control.toggleVideo()} /> + {false && } + + + } + outlined + onClick={() => callEmbed.hangup()} + > + + End + + + + ); +} diff --git a/src/app/features/call-status/CallRoomName.tsx b/src/app/features/call-status/CallRoomName.tsx new file mode 100644 index 00000000..39f0e914 --- /dev/null +++ b/src/app/features/call-status/CallRoomName.tsx @@ -0,0 +1,55 @@ +import React from 'react'; +import { Room } from 'matrix-js-sdk'; +import { Chip, Text } from 'folds'; +import { useAtomValue } from 'jotai'; +import { useRoomName } from '../../hooks/useRoomMeta'; +import { RoomIcon } from '../../components/room-avatar'; +import { roomToParentsAtom } from '../../state/room/roomToParents'; +import { getAllParents, guessPerfectParent } from '../../utils/room'; +import { useOrphanSpaces } from '../../state/hooks/roomList'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { allRoomsAtom } from '../../state/room-list/roomList'; +import { mDirectAtom } from '../../state/mDirectList'; +import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom'; +import { useRoomNavigate } from '../../hooks/useRoomNavigate'; + +type CallRoomNameProps = { + room: Room; +}; +export function CallRoomName({ room }: CallRoomNameProps) { + const mx = useMatrixClient(); + const name = useRoomName(room); + const roomToParents = useAtomValue(roomToParentsAtom); + const orphanSpaces = useOrphanSpaces(mx, allRoomsAtom, roomToParents); + const mDirects = useAtomValue(mDirectAtom); + const dm = mDirects.has(room.roomId); + + const allRoomsSet = useAllJoinedRoomsSet(); + const getRoom = useGetRoom(allRoomsSet); + + const allParents = getAllParents(roomToParents, room.roomId); + const orphanParents = allParents && orphanSpaces.filter((o) => allParents.has(o)); + const perfectOrphanParent = orphanParents && guessPerfectParent(mx, room.roomId, orphanParents); + + const { navigateRoom } = useRoomNavigate(); + + return ( + + } + onClick={() => navigateRoom(room.roomId)} + > + + {name} + {!dm && perfectOrphanParent && ( + + {' •'} {getRoom(perfectOrphanParent)?.name ?? perfectOrphanParent} + + )} + + + ); +} diff --git a/src/app/features/call-status/CallStatus.tsx b/src/app/features/call-status/CallStatus.tsx new file mode 100644 index 00000000..e2a17222 --- /dev/null +++ b/src/app/features/call-status/CallStatus.tsx @@ -0,0 +1,52 @@ +import React from 'react'; +import { Box, Spinner } from 'folds'; +import classNames from 'classnames'; +import { LiveChip } from './LiveChip'; +import * as css from './styles.css'; +import { CallRoomName } from './CallRoomName'; +import { CallControl } from './CallControl'; +import { ContainerColor } from '../../styles/ContainerColor.css'; +import { useCallMembers, useCallSession } from '../../hooks/useCall'; +import { ScreenSize, useScreenSize } from '../../hooks/useScreenSize'; +import { MemberGlance } from './MemberGlance'; +import { StatusDivider } from './components'; +import { CallEmbed } from '../../plugins/call/CallEmbed'; +import { useCallJoined } from '../../hooks/useCallEmbed'; + +type CallStatusProps = { + callEmbed: CallEmbed; +}; +export function CallStatus({ callEmbed }: CallStatusProps) { + const { room } = callEmbed; + + const callSession = useCallSession(room); + const callMembers = useCallMembers(room, callSession); + const screenSize = useScreenSize(); + const callJoined = useCallJoined(callEmbed); + + return ( + + + {callJoined && callMembers.length > 0 ? ( + + + + + ) : ( + + )} + + + + + + + + ); +} diff --git a/src/app/features/call-status/LiveChip.tsx b/src/app/features/call-status/LiveChip.tsx new file mode 100644 index 00000000..34167fb6 --- /dev/null +++ b/src/app/features/call-status/LiveChip.tsx @@ -0,0 +1,137 @@ +import React, { MouseEventHandler, useState } from 'react'; +import { + Avatar, + Badge, + Box, + Chip, + config, + Icon, + Icons, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Text, + toRem, +} from 'folds'; +import { CallMembership } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; +import FocusTrap from 'focus-trap-react'; +import { Room } from 'matrix-js-sdk'; +import * as css from './styles.css'; +import { stopPropagation } from '../../utils/keyboard'; +import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room'; +import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; +import { UserAvatar } from '../../components/user-avatar'; +import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile'; +import { getMouseEventCords } from '../../utils/dom'; + +type LiveChipProps = { + room: Room; + members: CallMembership[]; + count: number; +}; +export function LiveChip({ count, room, members }: LiveChipProps) { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); + const openUserProfile = useOpenUserRoomProfile(); + + const [cords, setCords] = useState(); + + const handleOpenMenu: MouseEventHandler = (evt) => { + setCords(evt.currentTarget.getBoundingClientRect()); + }; + + return ( + setCords(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, + }} + > + + + + + {members.map((callMember) => { + const userId = callMember.sender; + if (!userId) return null; + const name = + getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; + const avatarMxc = getMemberAvatarMxc(room, userId); + const avatarUrl = avatarMxc + ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + : undefined; + + return ( + + openUserProfile( + room.roomId, + undefined, + userId, + getMouseEventCords(evt.nativeEvent), + 'Right' + ) + } + before={ + + } + /> + + } + > + + {name} + + + ); + })} + + + + + + } + > + } + after={} + radii="Pill" + onClick={handleOpenMenu} + > + + {count} Live + + + + ); +} diff --git a/src/app/features/call-status/MemberGlance.tsx b/src/app/features/call-status/MemberGlance.tsx new file mode 100644 index 00000000..f4991f93 --- /dev/null +++ b/src/app/features/call-status/MemberGlance.tsx @@ -0,0 +1,72 @@ +import { Box, config, Icon, Icons, Text } from 'folds'; +import { CallMembership } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; +import React from 'react'; +import { Room } from 'matrix-js-sdk'; +import { UserAvatar } from '../../components/user-avatar'; +import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room'; +import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; +import { StackedAvatar } from '../../components/stacked-avatar'; +import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile'; +import { getMouseEventCords } from '../../utils/dom'; + +type MemberGlanceProps = { + room: Room; + members: CallMembership[]; + max?: number; +}; +export function MemberGlance({ room, members, max = 6 }: MemberGlanceProps) { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); + const openUserProfile = useOpenUserRoomProfile(); + + const visibleMembers = members.slice(0, max); + const remainingCount = max && members.length > max ? members.length - max : 0; + + return ( + + {visibleMembers.map((callMember) => { + const userId = callMember.sender; + if (!userId) return null; + const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; + const avatarMxc = getMemberAvatarMxc(room, userId); + const avatarUrl = avatarMxc + ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + : undefined; + + return ( + + openUserProfile( + room.roomId, + undefined, + userId, + getMouseEventCords(evt.nativeEvent), + 'Top' + ) + } + > + } + /> + + ); + })} + {remainingCount > 0 && ( + + +{remainingCount} + + )} + + ); +} diff --git a/src/app/features/call-status/components.tsx b/src/app/features/call-status/components.tsx new file mode 100644 index 00000000..cd0c0daf --- /dev/null +++ b/src/app/features/call-status/components.tsx @@ -0,0 +1,9 @@ +import React from 'react'; +import { Line } from 'folds'; +import * as css from './styles.css'; + +export function StatusDivider() { + return ( + + ); +} diff --git a/src/app/features/call-status/index.ts b/src/app/features/call-status/index.ts new file mode 100644 index 00000000..99accf8b --- /dev/null +++ b/src/app/features/call-status/index.ts @@ -0,0 +1 @@ +export * from './CallStatus'; diff --git a/src/app/features/call-status/styles.css.ts b/src/app/features/call-status/styles.css.ts new file mode 100644 index 00000000..26b08f0b --- /dev/null +++ b/src/app/features/call-status/styles.css.ts @@ -0,0 +1,17 @@ +import { style } from '@vanilla-extract/css'; +import { color, config, toRem } from 'folds'; + +export const LiveChipText = style({ + color: color.Critical.Main, +}); + +export const CallStatus = style([ + { + padding: `${toRem(6)} ${config.space.S200}`, + borderTop: `${config.borderWidth.B300} solid ${color.Background.ContainerLine}`, + }, +]); + +export const ControlDivider = style({ + height: toRem(16), +}); diff --git a/src/app/features/call/CallMemberCard.tsx b/src/app/features/call/CallMemberCard.tsx new file mode 100644 index 00000000..f96b9a06 --- /dev/null +++ b/src/app/features/call/CallMemberCard.tsx @@ -0,0 +1,121 @@ +import { CallMembership, SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; +import React, { useState } from 'react'; +import { Avatar, Box, Icon, Icons, Text } from 'folds'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; +import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile'; +import { SequenceCard } from '../../components/sequence-card'; +import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room'; +import { useRoom } from '../../hooks/useRoom'; +import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; +import { UserAvatar } from '../../components/user-avatar'; +import { getMouseEventCords } from '../../utils/dom'; +import * as css from './styles.css'; + +interface MemberWithMembershipData { + membershipData?: SessionMembershipData & { + 'm.call.intent': 'video' | 'audio'; + }; +} + +type CallMemberCardProps = { + member: CallMembership; +}; +export function CallMemberCard({ member }: CallMemberCardProps) { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); + const room = useRoom(); + + const openUserProfile = useOpenUserRoomProfile(); + + const userId = member.sender; + if (!userId) return null; + + const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; + const avatarMxc = getMemberAvatarMxc(room, userId); + const avatarUrl = avatarMxc + ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + : undefined; + + const audioOnly = + (member as unknown as MemberWithMembershipData).membershipData?.['m.call.intent'] === 'audio'; + + return ( + + openUserProfile( + room.roomId, + undefined, + userId, + getMouseEventCords(evt.nativeEvent), + 'Right' + ) + } + > + + + } + /> + + + + {name} + + + {audioOnly && } + + + ); +} + +export function CallMemberRenderer({ + members, + max = 4, +}: { + members: CallMembership[]; + max?: number; +}) { + const [viewMore, setViewMore] = useState(false); + + const truncatedMembers = viewMore ? members : members.slice(0, 4); + const remaining = members.length - truncatedMembers.length; + + return ( + <> + {truncatedMembers.map((member) => ( + + ))} + {members.length > max && ( + setViewMore(!viewMore)} + > + + {viewMore ? ( + + Collapse + + ) : ( + + {remaining === 0 ? `+${remaining} Other` : `+${remaining} Others`} + + )} + + + + )} + + ); +} diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx new file mode 100644 index 00000000..b2a200fb --- /dev/null +++ b/src/app/features/call/CallView.tsx @@ -0,0 +1,105 @@ +import React, { useRef } from 'react'; +import { Badge, Box, color, Header, Scroll, Text, toRem } from 'folds'; +import { useCallEmbed, useCallJoined, useSyncCallEmbedPlacement } from '../../hooks/useCallEmbed'; +import { ContainerColor } from '../../styles/ContainerColor.css'; +import { PrescreenControls } from './PrescreenControls'; +import { usePowerLevelsContext } from '../../hooks/usePowerLevels'; +import { useRoom } from '../../hooks/useRoom'; +import { useRoomCreators } from '../../hooks/useRoomCreators'; +import { useRoomPermissions } from '../../hooks/useRoomPermissions'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { StateEvent } from '../../../types/matrix/room'; +import { useCallMembers, useCallSession } from '../../hooks/useCall'; +import { CallMemberRenderer } from './CallMemberCard'; +import * as css from './styles.css'; + +function JoinMessage({ hasParticipant }: { hasParticipant?: boolean }) { + if (hasParticipant) return null; + + return ( + + Voice chat’s empty — Be the first to hop in! + + ); +} + +function NoPermissionMessage() { + return ( + + You don't have permission to join! + + ); +} + +function AlreadyInCallMessage() { + return ( + + Already in another call — End the current call to join! + + ); +} + +export function CallView() { + const mx = useMatrixClient(); + const room = useRoom(); + + const callViewRef = useRef(null); + useSyncCallEmbedPlacement(callViewRef); + + const powerLevels = usePowerLevelsContext(); + const creators = useRoomCreators(room); + + const permissions = useRoomPermissions(creators, powerLevels); + const canJoin = permissions.event(StateEvent.GroupCallMemberPrefix, mx.getSafeUserId()); + + const callSession = useCallSession(room); + const callMembers = useCallMembers(room, callSession); + const hasParticipant = callMembers.length > 0; + + const callEmbed = useCallEmbed(); + const callJoined = useCallJoined(callEmbed); + const inOtherCall = callEmbed && callEmbed.roomId !== room.roomId; + + const currentJoined = callEmbed?.roomId === room.roomId && callJoined; + + return ( + + {!currentJoined && ( + + + + {hasParticipant && ( +
+ + Participant + + + + {callMembers.length} Live + + +
+ )} + + +
+ {!inOtherCall && + (canJoin ? ( + + ) : ( + + ))} + {inOtherCall && } +
+
+
+
+ )} +
+ ); +} diff --git a/src/app/features/call/Controls.tsx b/src/app/features/call/Controls.tsx new file mode 100644 index 00000000..39c5d87d --- /dev/null +++ b/src/app/features/call/Controls.tsx @@ -0,0 +1,145 @@ +import React from 'react'; +import { Icon, IconButton, Icons, Line, Text, Tooltip, TooltipProvider } from 'folds'; +import { useAtom } from 'jotai'; +import * as css from './styles.css'; +import { callChatAtom } from '../../state/callEmbed'; + +export function ControlDivider() { + return ( + + ); +} + +type MicrophoneButtonProps = { + enabled: boolean; + onToggle: () => void; +}; +export function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) { + return ( + + {enabled ? 'Turn Off Microphone' : 'Turn On Microphone'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined + > + + + )} + + ); +} + +type SoundButtonProps = { + enabled: boolean; + onToggle: () => void; +}; +export function SoundButton({ enabled, onToggle }: SoundButtonProps) { + return ( + + {enabled ? 'Turn Off Sound' : 'Turn On Sound'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined + > + + + )} + + ); +} + +type VideoButtonProps = { + enabled: boolean; + onToggle: () => void; +}; +export function VideoButton({ enabled, onToggle }: VideoButtonProps) { + return ( + + {enabled ? 'Stop Camera' : 'Start Camera'} + + } + > + {(anchorRef) => ( + onToggle()} + outlined + > + + + )} + + ); +} + +export function ChatButton() { + const [chat, setChat] = useAtom(callChatAtom); + + return ( + + {chat ? 'Close Chat' : 'Open Chat'} + + } + > + {(anchorRef) => ( + setChat(!chat)} + outlined + > + + + )} + + ); +} diff --git a/src/app/features/call/PrescreenControls.tsx b/src/app/features/call/PrescreenControls.tsx new file mode 100644 index 00000000..4782c9b6 --- /dev/null +++ b/src/app/features/call/PrescreenControls.tsx @@ -0,0 +1,68 @@ +import React from 'react'; +import { Box, Button, Icon, Icons, Spinner, Text } from 'folds'; +import { SequenceCard } from '../../components/sequence-card'; +import * as css from './styles.css'; +import { ChatButton, ControlDivider, MicrophoneButton, SoundButton, VideoButton } from './Controls'; +import { useIsDirectRoom, useRoom } from '../../hooks/useRoom'; +import { useCallEmbed, useCallJoined, useCallStart } from '../../hooks/useCallEmbed'; +import { useCallPreferences } from '../../state/hooks/callPreferences'; +import { CallControlState } from '../../plugins/call/CallControlState'; + +type PrescreenControlsProps = { + canJoin?: boolean; +}; +export function PrescreenControls({ canJoin }: PrescreenControlsProps) { + const room = useRoom(); + const callEmbed = useCallEmbed(); + const callJoined = useCallJoined(callEmbed); + const direct = useIsDirectRoom(); + + const inOtherCall = callEmbed && callEmbed.roomId !== room.roomId; + + const startCall = useCallStart(direct); + const joining = callEmbed?.roomId === room.roomId && !callJoined; + + const disabled = inOtherCall || !canJoin; + + const { microphone, video, sound, toggleMicrophone, toggleVideo, toggleSound } = + useCallPreferences(); + + return ( + + + + + + + + + + + + + + + ); +} diff --git a/src/app/features/call/styles.css.ts b/src/app/features/call/styles.css.ts new file mode 100644 index 00000000..1ee2892a --- /dev/null +++ b/src/app/features/call/styles.css.ts @@ -0,0 +1,20 @@ +import { style } from '@vanilla-extract/css'; +import { config, toRem } from 'folds'; + +export const CallViewContent = style({ + padding: config.space.S400, + paddingRight: 0, + minHeight: '100%', +}); + +export const ControlCard = style({ + padding: config.space.S300, +}); + +export const ControlDivider = style({ + height: toRem(24), +}); + +export const CallMemberCard = style({ + padding: config.space.S300, +}); diff --git a/src/app/features/common-settings/general/RoomJoinRules.tsx b/src/app/features/common-settings/general/RoomJoinRules.tsx index b9e75499..0d352167 100644 --- a/src/app/features/common-settings/general/RoomJoinRules.tsx +++ b/src/app/features/common-settings/general/RoomJoinRules.tsx @@ -6,9 +6,8 @@ import { useAtomValue } from 'jotai'; import { ExtendedJoinRules, JoinRulesSwitcher, - useRoomJoinRuleIcon, + useJoinRuleIcons, useRoomJoinRuleLabel, - useSpaceJoinRuleIcon, } from '../../../components/JoinRulesSwitcher'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; @@ -75,8 +74,7 @@ export function RoomJoinRules({ permissions }: RoomJoinRulesProps) { return r; }, [allowKnockRestricted, allowRestricted, allowKnock, space]); - const icons = useRoomJoinRuleIcon(); - const spaceIcons = useSpaceJoinRuleIcon(); + const icons = useJoinRuleIcons(room.getType()); const labels = useRoomJoinRuleLabel(); const [submitState, submit] = useAsyncCallback( @@ -137,7 +135,7 @@ export function RoomJoinRules({ permissions }: RoomJoinRulesProps) { } after={ ( ( { - if (kind === CreateRoomKind.Private) return Icons.HashLock; - if (kind === CreateRoomKind.Restricted) return Icons.Hash; - return Icons.HashGlobe; +const getCreateRoomAccessToIcon = (access: CreateRoomAccess, type?: CreateRoomType) => { + const isVoiceRoom = type === CreateRoomType.VoiceRoom; + + let joinRule: JoinRule = JoinRule.Public; + if (access === CreateRoomAccess.Restricted) joinRule = JoinRule.Restricted; + if (access === CreateRoomAccess.Private) joinRule = JoinRule.Knock; + + return getRoomIconSrc(Icons, isVoiceRoom ? RoomType.Call : undefined, joinRule); +}; + +const getCreateRoomTypeToIcon = (type: CreateRoomType) => { + if (type === CreateRoomType.VoiceRoom) return Icons.VolumeHigh; + return Icons.Hash; }; type CreateRoomFormProps = { - defaultKind?: CreateRoomKind; + defaultAccess?: CreateRoomAccess; + defaultType?: CreateRoomType; space?: Room; onCreate?: (roomId: string) => void; }; -export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormProps) { +export function CreateRoomForm({ + defaultAccess, + defaultType, + space, + onCreate, +}: CreateRoomFormProps) { const mx = useMatrixClient(); const alive = useAlive(); @@ -64,8 +83,9 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP const allowRestricted = space && restrictedSupported(selectedRoomVersion); - const [kind, setKind] = useState( - defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private + const [type, setType] = useState(defaultType ?? CreateRoomType.TextRoom); + const [access, setAccess] = useState( + defaultAccess ?? (allowRestricted ? CreateRoomAccess.Restricted : CreateRoomAccess.Private) ); const allowAdditionalCreators = creatorsSupported(selectedRoomVersion); const { additionalCreators, addAdditionalCreator, removeAdditionalCreator } = @@ -75,13 +95,13 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP const [knock, setKnock] = useState(false); const [advance, setAdvance] = useState(false); - const allowKnock = kind === CreateRoomKind.Private && knockSupported(selectedRoomVersion); + const allowKnock = access === CreateRoomAccess.Private && knockSupported(selectedRoomVersion); const allowKnockRestricted = - kind === CreateRoomKind.Restricted && knockRestrictedSupported(selectedRoomVersion); + access === CreateRoomAccess.Restricted && knockRestrictedSupported(selectedRoomVersion); const handleRoomVersionChange = (version: string) => { if (!restrictedSupported(version)) { - setKind(CreateRoomKind.Private); + setAccess(CreateRoomAccess.Private); } selectRoomVersion(version); }; @@ -107,19 +127,23 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP aliasInput && aliasInput.value ? replaceSpaceWithDash(aliasInput.value) : undefined; if (!roomName) return; - const publicRoom = kind === CreateRoomKind.Public; + const publicRoom = access === CreateRoomAccess.Public; let roomKnock = false; - if (allowKnock && kind === CreateRoomKind.Private) { + if (allowKnock && access === CreateRoomAccess.Private) { roomKnock = knock; } - if (allowKnockRestricted && kind === CreateRoomKind.Restricted) { + if (allowKnockRestricted && access === CreateRoomAccess.Restricted) { roomKnock = knock; } + let roomType: RoomType | undefined; + if (type === CreateRoomType.VoiceRoom) roomType = RoomType.Call; + create({ version: selectedRoomVersion, + type: roomType, parent: space, - kind, + access, name: roomName, topic: roomTopic || undefined, aliasLocalPart: publicRoom ? aliasLocalPart : undefined, @@ -136,21 +160,32 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP return ( + {!space && ( + + Type + + + )} Access - getCreateRoomAccessToIcon(roomAccess, type)} /> Name } + before={} name="nameInput" autoFocus size="500" @@ -171,7 +206,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP /> - {kind === CreateRoomKind.Public && } + {access === CreateRoomAccess.Public && } @@ -201,7 +236,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP />
)} - {kind !== CreateRoomKind.Public && ( + {access !== CreateRoomAccess.Public && ( <> - New Room + + {type === CreateRoomType.VoiceRoom ? 'New Voice Room' : 'New Chat Room'} + @@ -74,7 +77,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { direction="Column" gap="500" > - +
diff --git a/src/app/features/create-space/CreateSpace.tsx b/src/app/features/create-space/CreateSpace.tsx index 530145af..b0c12f56 100644 --- a/src/app/features/create-space/CreateSpace.tsx +++ b/src/app/features/create-space/CreateSpace.tsx @@ -33,25 +33,25 @@ import { createRoom, CreateRoomAliasInput, CreateRoomData, - CreateRoomKind, - CreateRoomKindSelector, + CreateRoomAccess, + CreateRoomAccessSelector, RoomVersionSelector, useAdditionalCreators, } from '../../components/create-room'; import { RoomType } from '../../../types/matrix/room'; -const getCreateSpaceKindToIcon = (kind: CreateRoomKind) => { - if (kind === CreateRoomKind.Private) return Icons.SpaceLock; - if (kind === CreateRoomKind.Restricted) return Icons.Space; +const getCreateSpaceAccessToIcon = (access: CreateRoomAccess) => { + if (access === CreateRoomAccess.Private) return Icons.SpaceLock; + if (access === CreateRoomAccess.Restricted) return Icons.Space; return Icons.SpaceGlobe; }; type CreateSpaceFormProps = { - defaultKind?: CreateRoomKind; + defaultAccess?: CreateRoomAccess; space?: Room; onCreate?: (roomId: string) => void; }; -export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFormProps) { +export function CreateSpaceForm({ defaultAccess, space, onCreate }: CreateSpaceFormProps) { const mx = useMatrixClient(); const alive = useAlive(); @@ -65,8 +65,8 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor const allowRestricted = space && restrictedSupported(selectedRoomVersion); - const [kind, setKind] = useState( - defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private + const [access, setAccess] = useState( + defaultAccess ?? (allowRestricted ? CreateRoomAccess.Restricted : CreateRoomAccess.Private) ); const allowAdditionalCreators = creatorsSupported(selectedRoomVersion); @@ -76,13 +76,13 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor const [knock, setKnock] = useState(false); const [advance, setAdvance] = useState(false); - const allowKnock = kind === CreateRoomKind.Private && knockSupported(selectedRoomVersion); + const allowKnock = access === CreateRoomAccess.Private && knockSupported(selectedRoomVersion); const allowKnockRestricted = - kind === CreateRoomKind.Restricted && knockRestrictedSupported(selectedRoomVersion); + access === CreateRoomAccess.Restricted && knockRestrictedSupported(selectedRoomVersion); const handleRoomVersionChange = (version: string) => { if (!restrictedSupported(version)) { - setKind(CreateRoomKind.Private); + setAccess(CreateRoomAccess.Private); } selectRoomVersion(version); }; @@ -108,12 +108,12 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor aliasInput && aliasInput.value ? replaceSpaceWithDash(aliasInput.value) : undefined; if (!roomName) return; - const publicRoom = kind === CreateRoomKind.Public; + const publicRoom = access === CreateRoomAccess.Public; let roomKnock = false; - if (allowKnock && kind === CreateRoomKind.Private) { + if (allowKnock && access === CreateRoomAccess.Private) { roomKnock = knock; } - if (allowKnockRestricted && kind === CreateRoomKind.Restricted) { + if (allowKnockRestricted && access === CreateRoomAccess.Restricted) { roomKnock = knock; } @@ -121,7 +121,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor version: selectedRoomVersion, type: RoomType.Space, parent: space, - kind, + access, name: roomName, topic: roomTopic || undefined, aliasLocalPart: publicRoom ? aliasLocalPart : undefined, @@ -139,19 +139,19 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor Access - Name } + before={} name="nameInput" autoFocus size="500" @@ -172,7 +172,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor /> - {kind === CreateRoomKind.Public && } + {access === CreateRoomAccess.Public && } @@ -202,7 +202,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor /> )} - {kind !== CreateRoomKind.Public && advance && (allowKnock || allowKnockRestricted) && ( + {access !== CreateRoomAccess.Public && advance && (allowKnock || allowKnockRestricted) && ( {(onBack) => ( - + )} @@ -218,7 +218,11 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { } > {(triggerRef) => ( - setPeopleDrawer((drawer) => !drawer)}> + setPeopleDrawer((drawer) => !drawer)} + > )} @@ -235,7 +239,12 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { } > {(triggerRef) => ( - + )} diff --git a/src/app/features/lobby/RoomItem.tsx b/src/app/features/lobby/RoomItem.tsx index 994cda05..7de59acd 100644 --- a/src/app/features/lobby/RoomItem.tsx +++ b/src/app/features/lobby/RoomItem.tsx @@ -175,6 +175,7 @@ function RoomProfileError({ roomId, suggested, inaccessibleRoom, via }: RoomProf type RoomProfileProps = { roomId: string; + roomType?: string; name: string; topic?: string; avatarUrl?: string; @@ -185,6 +186,7 @@ type RoomProfileProps = { }; function RoomProfile({ roomId, + roomType, name, topic, avatarUrl, @@ -200,9 +202,7 @@ function RoomProfile({ roomId={roomId} src={avatarUrl} alt={name} - renderFallback={() => ( - - )} + renderFallback={() => } /> @@ -338,6 +338,7 @@ export const RoomItemCard = as<'div', RoomItemCardProps>( {(localSummary) => ( ( {summary && ( { - openCreateRoomModal(item.roomId); + const handleCreateRoom = (type?: CreateRoomType) => { + openCreateRoomModal(item.roomId, type); setCords(undefined); }; @@ -281,9 +283,19 @@ function AddRoomButton({ item }: { item: HierarchyItem }) { radii="300" variant="Primary" fill="None" - onClick={handleCreateRoom} + onClick={() => handleCreateRoom(CreateRoomType.TextRoom)} > - New Room + Chat Room + + handleCreateRoom(CreateRoomType.VoiceRoom)} + after={} + > + Voice Room Existing Room diff --git a/src/app/features/message-search/SearchFilters.tsx b/src/app/features/message-search/SearchFilters.tsx index 929dd1e9..6883e363 100644 --- a/src/app/features/message-search/SearchFilters.tsx +++ b/src/app/features/message-search/SearchFilters.tsx @@ -29,7 +29,7 @@ import { SearchOrderBy } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useMatrixClient } from '../../hooks/useMatrixClient'; -import { joinRuleToIconSrc } from '../../utils/room'; +import { getRoomIconSrc } from '../../utils/room'; import { factoryRoomIdByAtoZ } from '../../utils/sort'; import { SearchItemStrGetter, @@ -274,9 +274,7 @@ function SelectRoomButton({ roomList, selectedRooms, onChange }: SelectRoomButto before={ } > @@ -392,10 +390,7 @@ export function SearchFilters({ onClick={() => onSelectedRoomsChange(selectedRooms.filter((rId) => rId !== roomId))} radii="Pill" before={ - + } after={} > diff --git a/src/app/features/message-search/SearchResultGroup.tsx b/src/app/features/message-search/SearchResultGroup.tsx index 62ef9c4b..14817cc4 100644 --- a/src/app/features/message-search/SearchResultGroup.tsx +++ b/src/app/features/message-search/SearchResultGroup.tsx @@ -203,7 +203,12 @@ export function SearchResultGroup({ src={getRoomAvatarUrl(mx, room, 96, useAuthentication)} alt={room.name} renderFallback={() => ( - + )} /> diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 33b21bff..cfb52d44 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -19,6 +19,7 @@ import { } from 'folds'; import { useFocusWithin, useHover } from 'react-aria'; import FocusTrap from 'focus-trap-react'; +import { useAtom, useAtomValue } from 'jotai'; import { NavItem, NavItemContent, NavItemOptions, NavLink } from '../../components/nav'; import { UnreadBadge, UnreadBadgeCenter } from '../../components/unread-badge'; import { RoomAvatar, RoomIcon } from '../../components/room-avatar'; @@ -51,6 +52,12 @@ import { RoomNotificationModeSwitcher } from '../../components/RoomNotificationS import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { InviteUserPrompt } from '../../components/invite-user-prompt'; +import { useRoomName } from '../../hooks/useRoomMeta'; +import { useCallMembers, useCallSession } from '../../hooks/useCall'; +import { useCallEmbed, useCallStart } from '../../hooks/useCallEmbed'; +import { callChatAtom } from '../../state/callEmbed'; +import { useCallPreferencesAtom } from '../../state/hooks/callPreferences'; +import { CallControlState } from '../../plugins/call/CallControlState'; type RoomNavItemMenuProps = { room: Room; @@ -209,6 +216,24 @@ const RoomNavItemMenu = forwardRef( } ); +function CallChatToggle() { + const [chat, setChat] = useAtom(callChatAtom); + + return ( + setChat(!chat)} + aria-pressed={chat} + aria-label="Toggle Chat" + variant="Background" + fill="None" + size="300" + radii="300" + > + + + ); +} + type RoomNavItemProps = { room: Room; selected: boolean; @@ -236,6 +261,8 @@ export function RoomNavItem({ (receipt) => receipt.userId !== mx.getUserId() ); + const roomName = useRoomName(room); + const handleContextMenu: MouseEventHandler = (evt) => { evt.preventDefault(); setMenuAnchor({ @@ -251,6 +278,23 @@ export function RoomNavItem({ }; const optionsVisible = hover || !!menuAnchor; + const callSession = useCallSession(room); + const callMembers = useCallMembers(room, callSession); + const startCall = useCallStart(direct); + const callEmbed = useCallEmbed(); + const callPref = useAtomValue(useCallPreferencesAtom()); + + const handleStartCall: MouseEventHandler = (evt) => { + // Do not join if already in call + if (callEmbed) { + return; + } + // Start call in second click + if (selected) { + evt.preventDefault(); + startCall(room, new CallControlState(callPref.microphone, callPref.video, callPref.sound)); + } + }; return ( - + @@ -275,25 +319,28 @@ export function RoomNavItem({ ? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) : getRoomAvatarUrl(mx, room, 96, useAuthentication) } - alt={room.name} + alt={roomName} renderFallback={() => ( - {nameInitials(room.name)} + {nameInitials(roomName)} )} /> ) : ( )} - {room.name} + {roomName} {!optionsVisible && !unread && !selected && typingMember.length > 0 && ( @@ -307,14 +354,30 @@ export function RoomNavItem({ )} {!optionsVisible && notificationMode !== RoomNotificationMode.Unset && ( - + + )} + {room.isCallRoom() && callMembers.length > 0 && ( + + + {callMembers.length} Live + + )} {optionsVisible && ( + {selected && (callEmbed?.roomId === room.roomId || room.isCallRoom()) && ( + + )} ( diff --git a/src/app/features/room-settings/permissions/Permissions.tsx b/src/app/features/room-settings/permissions/Permissions.tsx index 7572a71b..fe6b098b 100644 --- a/src/app/features/room-settings/permissions/Permissions.tsx +++ b/src/app/features/room-settings/permissions/Permissions.tsx @@ -23,7 +23,7 @@ export function Permissions({ requestClose }: PermissionsProps) { const canEditPowers = permissions.stateEvent(StateEvent.PowerLevelTags, mx.getSafeUserId()); const canEditPermissions = permissions.stateEvent(StateEvent.RoomPowerLevels, mx.getSafeUserId()); - const permissionGroups = usePermissionGroups(); + const permissionGroups = usePermissionGroups(room.isCallRoom()); const [powerEditor, setPowerEditor] = useState(false); diff --git a/src/app/features/room-settings/permissions/usePermissionItems.ts b/src/app/features/room-settings/permissions/usePermissionItems.ts index f3b45424..d4f5f562 100644 --- a/src/app/features/room-settings/permissions/usePermissionItems.ts +++ b/src/app/features/room-settings/permissions/usePermissionItems.ts @@ -2,7 +2,7 @@ import { useMemo } from 'react'; import { MessageEvent, StateEvent } from '../../../../types/matrix/room'; import { PermissionGroup } from '../../common-settings/permissions'; -export const usePermissionGroups = (): PermissionGroup[] => { +export const usePermissionGroups = (isCallRoom: boolean): PermissionGroup[] => { const groups: PermissionGroup[] = useMemo(() => { const messagesGroup: PermissionGroup = { name: 'Messages', @@ -46,6 +46,19 @@ export const usePermissionGroups = (): PermissionGroup[] => { ], }; + const callSettingsGroup: PermissionGroup = { + name: 'Calls', + items: [ + { + location: { + state: true, + key: StateEvent.GroupCallMemberPrefix, + }, + name: 'Join Call', + }, + ], + }; + const moderationGroup: PermissionGroup = { name: 'Moderation', items: [ @@ -203,12 +216,13 @@ export const usePermissionGroups = (): PermissionGroup[] => { return [ messagesGroup, + ...(isCallRoom ? [callSettingsGroup] : []), moderationGroup, roomOverviewGroup, roomSettingsGroup, otherSettingsGroup, ]; - }, []); + }, [isCallRoom]); return groups; }; diff --git a/src/app/features/room/CallChatView.tsx b/src/app/features/room/CallChatView.tsx new file mode 100644 index 00000000..6c32f4a0 --- /dev/null +++ b/src/app/features/room/CallChatView.tsx @@ -0,0 +1,57 @@ +import React from 'react'; +import { useSetAtom } from 'jotai'; +import { useParams } from 'react-router-dom'; +import { Box, Text, TooltipProvider, Tooltip, Icon, Icons, IconButton, toRem } from 'folds'; +import { Page, PageHeader } from '../../components/page'; +import { callChatAtom } from '../../state/callEmbed'; +import { RoomView } from './RoomView'; +import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; + +export function CallChatView() { + const { eventId } = useParams(); + const setChat = useSetAtom(callChatAtom); + const screenSize = useScreenSizeContext(); + + const handleClose = () => setChat(false); + + return ( + + + + + + Chat + + + + + Close + + } + > + {(triggerRef) => ( + + + + )} + + + + + + + + + ); +} diff --git a/src/app/features/room/Room.tsx b/src/app/features/room/Room.tsx index 24878d5e..5e5d7d78 100644 --- a/src/app/features/room/Room.tsx +++ b/src/app/features/room/Room.tsx @@ -2,6 +2,7 @@ import React, { useCallback } from 'react'; import { Box, Line } from 'folds'; import { useParams } from 'react-router-dom'; import { isKeyHotkey } from 'is-hotkey'; +import { useAtomValue } from 'jotai'; import { RoomView } from './RoomView'; import { MembersDrawer } from './MembersDrawer'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; @@ -13,6 +14,10 @@ import { useKeyDown } from '../../hooks/useKeyDown'; import { markAsRead } from '../../utils/notifications'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useRoomMembers } from '../../hooks/useRoomMembers'; +import { CallView } from '../call/CallView'; +import { RoomViewHeader } from './RoomViewHeader'; +import { callChatAtom } from '../../state/callEmbed'; +import { CallChatView } from './CallChatView'; export function Room() { const { eventId } = useParams(); @@ -24,6 +29,7 @@ export function Room() { const screenSize = useScreenSizeContext(); const powerLevels = usePowerLevels(room); const members = useRoomMembers(mx, room.roomId); + const chat = useAtomValue(callChatAtom); useKeyDown( window, @@ -37,11 +43,37 @@ export function Room() { ) ); + const callView = room.isCallRoom(); + return ( - - {screenSize === ScreenSize.Desktop && isDrawer && ( + {callView && (screenSize === ScreenSize.Desktop || !chat) && ( + + + + + + + )} + {!callView && ( + + + + + + + )} + + {callView && chat && ( + <> + {screenSize === ScreenSize.Desktop && ( + + )} + + + )} + {!callView && screenSize === ScreenSize.Desktop && isDrawer && ( <> diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index d1678b65..64043054 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -27,6 +27,7 @@ import { HTMLReactParserOptions } from 'html-react-parser'; import classNames from 'classnames'; import { ReactEditor } from 'slate-react'; import { Editor } from 'slate'; +import { SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; import to from 'await-to-js'; import { useAtomValue, useSetAtom } from 'jotai'; import { @@ -1469,6 +1470,51 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli ); }, + [StateEvent.GroupCallMemberPrefix]: (mEventId, mEvent, item) => { + const highlighted = focusItem?.index === item && focusItem.highlight; + const senderId = mEvent.getSender() ?? ''; + const senderName = getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId); + + const callJoined = mEvent.getContent().application; + + const timeJSX = ( + + } + /> + + ); + }, }, (mEventId, mEvent, item) => { if (!showHiddenEvents) return null; diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 0f837594..a4f0d7af 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useRef } from 'react'; import { Box, Text, config } from 'folds'; -import { EventType, Room } from 'matrix-js-sdk'; +import { EventType } from 'matrix-js-sdk'; import { ReactEditor } from 'slate-react'; import { isKeyHotkey } from 'is-hotkey'; import { useStateEvent } from '../../hooks/useStateEvent'; @@ -15,13 +15,13 @@ import { RoomTombstone } from './RoomTombstone'; import { RoomInput } from './RoomInput'; import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing'; import { Page } from '../../components/page'; -import { RoomViewHeader } from './RoomViewHeader'; import { useKeyDown } from '../../hooks/useKeyDown'; import { editableActiveElement } from '../../utils/dom'; import { settingsAtom } from '../../state/settings'; import { useSetting } from '../../state/hooks/settings'; import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { useRoomCreators } from '../../hooks/useRoomCreators'; +import { useRoom } from '../../hooks/useRoom'; const FN_KEYS_REGEX = /^F\d+$/; const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { @@ -30,10 +30,8 @@ const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { return false; } - // do not focus on F keys if (FN_KEYS_REGEX.test(code)) return false; - // do not focus on numlock/scroll lock if ( code.startsWith('OS') || code.startsWith('Meta') || @@ -56,12 +54,13 @@ const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { return true; }; -export function RoomView({ room, eventId }: { room: Room; eventId?: string }) { +export function RoomView({ eventId }: { eventId?: string }) { const roomInputRef = useRef(null); const roomViewRef = useRef(null); const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + const room = useRoom(); const { roomId } = room; const editor = useEditor(); @@ -93,7 +92,6 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) { return ( - (({ room, requestClose ); }); -export function RoomViewHeader() { +export function RoomViewHeader({ callView }: { callView?: boolean }) { const navigate = useNavigate(); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -263,12 +264,14 @@ export function RoomViewHeader() { const space = useSpaceOptionally(); const [menuAnchor, setMenuAnchor] = useState(); const [pinMenuAnchor, setPinMenuAnchor] = useState(); - const mDirects = useAtomValue(mDirectAtom); + const direct = useIsDirectRoom(); + + const [chat, setChat] = useAtom(callChatAtom); const pinnedEvents = useRoomPinnedEvents(room); const encryptionEvent = useStateEvent(room, StateEvent.RoomEncryption); - const ecryptedRoom = !!encryptionEvent; - const avatarMxc = useRoomAvatar(room, mDirects.has(room.roomId)); + const encryptedRoom = !!encryptionEvent; + const avatarMxc = useRoomAvatar(room, direct); const name = useRoomName(room); const topic = useRoomTopic(room); const avatarUrl = avatarMxc @@ -295,14 +298,27 @@ export function RoomViewHeader() { setPinMenuAnchor(evt.currentTarget.getBoundingClientRect()); }; + const openSettings = useOpenRoomSettings(); + const parentSpace = useSpaceOptionally(); + const handleMemberToggle = () => { + if (callView) { + openSettings(room.roomId, parentSpace?.roomId, RoomSettingsPage.MembersPage); + return; + } + setPeopleDrawer(!peopleDrawer); + }; + return ( - + {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + @@ -317,11 +333,7 @@ export function RoomViewHeader() { src={avatarUrl} alt={name} renderFallback={() => ( - + )} /> @@ -369,8 +381,9 @@ export function RoomViewHeader() { )} + - {!ecryptedRoom && ( + {!encryptedRoom && ( {(triggerRef) => ( - + )} @@ -398,6 +411,7 @@ export function RoomViewHeader() { > {(triggerRef) => ( } /> + {screenSize === ScreenSize.Desktop && ( {(triggerRef) => ( - setPeopleDrawer((drawer) => !drawer)}> + )} )} + + {callView && ( + + Chat + + } + > + {(triggerRef) => ( + setChat(!chat)}> + + + )} + + )} + {(triggerRef) => ( - + )} diff --git a/src/app/features/search/Search.tsx b/src/app/features/search/Search.tsx index fcd6233a..6027f322 100644 --- a/src/app/features/search/Search.tsx +++ b/src/app/features/search/Search.tsx @@ -373,7 +373,7 @@ export function Search({ requestClose }: SearchProps) { )} diff --git a/src/app/features/space-settings/SpaceSettings.tsx b/src/app/features/space-settings/SpaceSettings.tsx index e565fb92..b5fefc93 100644 --- a/src/app/features/space-settings/SpaceSettings.tsx +++ b/src/app/features/space-settings/SpaceSettings.tsx @@ -103,7 +103,7 @@ export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps) alt={roomName} renderFallback={() => ( { + const mx = useMatrixClient(); + + const [session, setSession] = useState(mx.matrixRTC.getRoomSession(room)); + + useEffect(() => { + const start = (roomId: string) => { + if (roomId !== room.roomId) return; + setSession(mx.matrixRTC.getRoomSession(room)); + }; + const end = (roomId: string) => { + if (roomId !== room.roomId) return; + setSession(mx.matrixRTC.getRoomSession(room)); + }; + mx.matrixRTC.on(MatrixRTCSessionManagerEvents.SessionStarted, start); + mx.matrixRTC.on(MatrixRTCSessionManagerEvents.SessionEnded, end); + return () => { + mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionStarted, start); + mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionEnded, end); + }; + }, [mx, room]); + + return session; +}; + +export const useCallMembers = (room: Room, session: MatrixRTCSession): CallMembership[] => { + const [memberships, setMemberships] = useState( + MatrixRTCSession.sessionMembershipsForRoom(room, session.sessionDescription) + ); + + useEffect(() => { + const updateMemberships = () => { + setMemberships(MatrixRTCSession.sessionMembershipsForRoom(room, session.sessionDescription)); + }; + + updateMemberships(); + + session.on(MatrixRTCSessionEvent.MembershipsChanged, updateMemberships); + return () => { + session.removeListener(MatrixRTCSessionEvent.MembershipsChanged, updateMemberships); + }; + }, [session, room]); + + return memberships; +}; diff --git a/src/app/hooks/useCallEmbed.ts b/src/app/hooks/useCallEmbed.ts new file mode 100644 index 00000000..e04182dd --- /dev/null +++ b/src/app/hooks/useCallEmbed.ts @@ -0,0 +1,130 @@ +import { createContext, RefObject, useCallback, useContext, useEffect, useState } from 'react'; +import { MatrixRTCSession } from 'matrix-js-sdk/lib/matrixrtc/MatrixRTCSession'; +import { MatrixClient, Room } from 'matrix-js-sdk'; +import { useSetAtom } from 'jotai'; +import { + CallEmbed, + ElementCallThemeKind, + ElementWidgetActions, + useClientWidgetApiEvent, +} from '../plugins/call'; +import { useMatrixClient } from './useMatrixClient'; +import { ThemeKind, useTheme } from './useTheme'; +import { callEmbedAtom } from '../state/callEmbed'; +import { useResizeObserver } from './useResizeObserver'; +import { CallControlState } from '../plugins/call/CallControlState'; + +const CallEmbedContext = createContext(undefined); + +export const CallEmbedContextProvider = CallEmbedContext.Provider; + +export const useCallEmbed = (): CallEmbed | undefined => { + const callEmbed = useContext(CallEmbedContext); + + return callEmbed; +}; + +const CallEmbedRefContext = createContext | undefined>(undefined); +export const CallEmbedRefContextProvider = CallEmbedRefContext.Provider; +export const useCallEmbedRef = (): RefObject => { + const ref = useContext(CallEmbedRefContext); + if (!ref) { + throw new Error('CallEmbedRef is not provided!'); + } + return ref; +}; + +export const createCallEmbed = ( + mx: MatrixClient, + room: Room, + dm: boolean, + themeKind: ElementCallThemeKind, + container: HTMLElement, + controlState?: CallControlState +): CallEmbed => { + const rtcSession = mx.matrixRTC.getRoomSession(room); + const ongoing = + MatrixRTCSession.sessionMembershipsForRoom(room, rtcSession.sessionDescription).length > 0; + + const intent = CallEmbed.getIntent(dm, ongoing); + const widget = CallEmbed.getWidget(mx, room, intent, themeKind); + const embed = new CallEmbed(mx, room, widget, container, controlState); + + return embed; +}; + +export const useCallStart = (dm = false) => { + const mx = useMatrixClient(); + const theme = useTheme(); + const setCallEmbed = useSetAtom(callEmbedAtom); + const callEmbedRef = useCallEmbedRef(); + + const startCall = useCallback( + (room: Room, controlState?: CallControlState) => { + const container = callEmbedRef.current; + if (!container) { + throw new Error('Failed to start call, No embed container element found!'); + } + const callEmbed = createCallEmbed(mx, room, dm, theme.kind, container, controlState); + + setCallEmbed(callEmbed); + }, + [mx, dm, theme, setCallEmbed, callEmbedRef] + ); + + return startCall; +}; + +export const useCallJoined = (embed?: CallEmbed): boolean => { + const [joined, setJoined] = useState(embed?.joined ?? false); + + useClientWidgetApiEvent( + embed?.call, + ElementWidgetActions.JoinCall, + useCallback(() => { + setJoined(true); + }, []) + ); + + useEffect(() => { + if (!embed) { + setJoined(false); + } + }, [embed]); + + return joined; +}; + +export const useCallHangupEvent = (embed: CallEmbed, callback: () => void) => { + useClientWidgetApiEvent(embed.call, ElementWidgetActions.HangupCall, callback); +}; + +export const useCallThemeSync = (embed: CallEmbed) => { + const theme = useTheme(); + + useEffect(() => { + const name: ElementCallThemeKind = theme.kind === ThemeKind.Dark ? 'dark' : 'light'; + + embed.setTheme(name); + }, [theme.kind, embed]); +}; + +export const useSyncCallEmbedPlacement = (containerViewRef: RefObject): void => { + const callEmbedRef = useCallEmbedRef(); + + const syncCallEmbedPlacement = useCallback(() => { + const embedEl = callEmbedRef.current; + const container = containerViewRef.current; + if (!embedEl || !container) return; + + embedEl.style.top = `${container.offsetTop}px`; + embedEl.style.left = `${container.offsetLeft}px`; + embedEl.style.width = `${container.clientWidth}px`; + embedEl.style.height = `${container.clientHeight}px`; + }, [callEmbedRef, containerViewRef]); + + useResizeObserver( + syncCallEmbedPlacement, + useCallback(() => containerViewRef.current, [containerViewRef]) + ); +}; diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index 8b0ae8cc..086c3a56 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -20,6 +20,8 @@ export const useRoomName = (room: Room): string => { const [name, setName] = useState(room.name); useEffect(() => { + setName(room.name); + const handleRoomNameChange: RoomEventHandlerMap[RoomEvent.Name] = () => { setName(room.name); }; diff --git a/src/app/hooks/useStateEvents.ts b/src/app/hooks/useStateEvents.ts deleted file mode 100644 index dd085693..00000000 --- a/src/app/hooks/useStateEvents.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useCallback, useMemo } from 'react'; -import { Room } from 'matrix-js-sdk'; -import { StateEvent } from '../../types/matrix/room'; -import { useForceUpdate } from './useForceUpdate'; -import { useStateEventCallback } from './useStateEventCallback'; -import { getStateEvents } from '../utils/room'; - -export const useStateEvents = (room: Room, eventType: StateEvent) => { - const [updateCount, forceUpdate] = useForceUpdate(); - - useStateEventCallback( - room.client, - useCallback( - (event) => { - if (event.getRoomId() === room.roomId && event.getType() === eventType) { - forceUpdate(); - } - }, - [room, eventType, forceUpdate] - ) - ); - - return useMemo( - () => getStateEvents(room, eventType), - // eslint-disable-next-line react-hooks/exhaustive-deps - [room, eventType, updateCount] - ); -}; diff --git a/src/app/pages/CallStatusRenderer.tsx b/src/app/pages/CallStatusRenderer.tsx new file mode 100644 index 00000000..f8e38054 --- /dev/null +++ b/src/app/pages/CallStatusRenderer.tsx @@ -0,0 +1,11 @@ +import React from 'react'; +import { useCallEmbed } from '../hooks/useCallEmbed'; +import { CallStatus } from '../features/call-status'; + +export function CallStatusRenderer() { + const callEmbed = useCallEmbed(); + + if (!callEmbed) return null; + + return ; +} diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index f8647d18..4de42081 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -68,6 +68,8 @@ import { Create } from './client/create'; import { CreateSpaceModalRenderer } from '../features/create-space'; import { SearchModalRenderer } from '../features/search'; import { getFallbackSession } from '../state/sessions'; +import { CallStatusRenderer } from './CallStatusRenderer'; +import { CallEmbedProvider } from '../components/CallEmbedProvider'; export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) => { const { hashRouter } = clientConfig; @@ -124,15 +126,18 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) - - - - } - > - - + + + + + } + > + + + + diff --git a/src/app/pages/client/ClientInitStorageAtom.tsx b/src/app/pages/client/ClientInitStorageAtom.tsx index 1abee707..5793bb6b 100644 --- a/src/app/pages/client/ClientInitStorageAtom.tsx +++ b/src/app/pages/client/ClientInitStorageAtom.tsx @@ -8,6 +8,8 @@ import { makeNavToActivePathAtom } from '../../state/navToActivePath'; import { NavToActivePathProvider } from '../../state/hooks/navToActivePath'; import { makeOpenedSidebarFolderAtom } from '../../state/openedSidebarFolder'; import { OpenedSidebarFolderProvider } from '../../state/hooks/openedSidebarFolder'; +import { makeCallPreferencesAtom } from '../../state/callPreferences'; +import { CallPreferencesProvider } from '../../state/hooks/callPreferences'; type ClientInitStorageAtomProps = { children: ReactNode; @@ -24,12 +26,16 @@ export function ClientInitStorageAtom({ children }: ClientInitStorageAtomProps) const openedSidebarFolderAtom = useMemo(() => makeOpenedSidebarFolderAtom(userId), [userId]); + const callPreferencesAtom = useMemo(() => makeCallPreferencesAtom(userId), [userId]); + return ( - {children} + + {children} + diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 4cc94d91..9592224f 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -417,7 +417,12 @@ function RoomNotificationsGroupComp({ src={getRoomAvatarUrl(mx, room, 96, useAuthentication)} alt={room.name} renderFallback={() => ( - + )} /> diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index 3f60d2a9..2a7c6199 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -84,6 +84,7 @@ import { ContainerColor } from '../../../styles/ContainerColor.css'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { BreakWord } from '../../../styles/Text.css'; import { InviteUserPrompt } from '../../../components/invite-user-prompt'; +import { useCallEmbed } from '../../../hooks/useCallEmbed'; type SpaceMenuProps = { room: Room; @@ -387,15 +388,15 @@ export function Space() { const notificationPreferences = useRoomsNotificationPreferencesContext(); const tombstoneEvent = useStateEvent(space, StateEvent.RoomTombstone); - const selectedRoomId = useSelectedRoom(); const lobbySelected = useSpaceLobbySelected(spaceIdOrAlias); const searchSelected = useSpaceSearchSelected(spaceIdOrAlias); + const callEmbed = useCallEmbed(); const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom()); const getRoom = useCallback( - (rId: string) => { + (rId: string): Room | undefined => { if (allJoinedRooms.has(rId)) { return mx.getRoom(rId) ?? undefined; } @@ -412,11 +413,11 @@ export function Space() { if (!closedCategories.has(makeNavCategoryId(space.roomId, parentId))) { return false; } - const showRoom = roomToUnread.has(roomId) || roomId === selectedRoomId; - if (showRoom) return false; - return true; + const showRoomAnyway = + roomToUnread.has(roomId) || roomId === selectedRoomId || callEmbed?.roomId === roomId; + return !showRoomAnyway; }, - [space.roomId, closedCategories, roomToUnread, selectedRoomId] + [space.roomId, closedCategories, roomToUnread, selectedRoomId, callEmbed] ), useCallback( (sId) => closedCategories.has(makeNavCategoryId(space.roomId, sId)), diff --git a/src/app/plugins/call/CallControl.ts b/src/app/plugins/call/CallControl.ts new file mode 100644 index 00000000..c2087fe0 --- /dev/null +++ b/src/app/plugins/call/CallControl.ts @@ -0,0 +1,117 @@ +import { ClientWidgetApi } from 'matrix-widget-api'; +import EventEmitter from 'events'; +import { CallControlState } from './CallControlState'; +import { ElementMediaStateDetail, ElementMediaStatePayload, ElementWidgetActions } from './types'; + +export enum CallControlEvent { + StateUpdate = 'state_update', +} + +export class CallControl extends EventEmitter implements CallControlState { + private state: CallControlState; + + private call: ClientWidgetApi; + + private iframe: HTMLIFrameElement; + + constructor(state: CallControlState, call: ClientWidgetApi, iframe: HTMLIFrameElement) { + super(); + + this.state = state; + this.call = call; + this.iframe = iframe; + } + + public getState(): CallControlState { + return this.state; + } + + public get microphone(): boolean { + return this.state.microphone; + } + + public get video(): boolean { + return this.state.video; + } + + public get sound(): boolean { + return this.state.sound; + } + + public async applyState() { + await this.setMediaState({ + audio_enabled: this.microphone, + video_enabled: this.video, + }); + this.setSound(this.sound); + this.emitStateUpdate(); + } + + private setMediaState(state: ElementMediaStatePayload) { + return this.call.transport.send(ElementWidgetActions.DeviceMute, state); + } + + private setSound(sound: boolean): void { + const callDocument = this.iframe.contentDocument ?? this.iframe.contentWindow?.document; + if (callDocument) { + callDocument.querySelectorAll('audio').forEach((el) => { + if (el instanceof HTMLAudioElement) { + // eslint-disable-next-line no-param-reassign + el.muted = !sound; + } + }); + } + } + + public onMediaState(evt: CustomEvent) { + const { data } = evt.detail; + if (!data) return; + + const state = new CallControlState( + data.audio_enabled ?? this.microphone, + data.video_enabled ?? this.video, + this.sound + ); + + this.state = state; + this.emitStateUpdate(); + + if (this.microphone && !this.sound) { + this.toggleSound(); + } + } + + public toggleMicrophone() { + const payload: ElementMediaStatePayload = { + audio_enabled: !this.microphone, + video_enabled: this.video, + }; + return this.setMediaState(payload); + } + + public toggleVideo() { + const payload: ElementMediaStatePayload = { + audio_enabled: this.microphone, + video_enabled: !this.video, + }; + return this.setMediaState(payload); + } + + public toggleSound() { + const sound = !this.sound; + + this.setSound(sound); + + const state = new CallControlState(this.microphone, this.video, sound); + this.state = state; + this.emitStateUpdate(); + + if (!this.sound && this.microphone) { + this.toggleMicrophone(); + } + } + + private emitStateUpdate() { + this.emit(CallControlEvent.StateUpdate); + } +} diff --git a/src/app/plugins/call/CallControlState.ts b/src/app/plugins/call/CallControlState.ts new file mode 100644 index 00000000..42f0b196 --- /dev/null +++ b/src/app/plugins/call/CallControlState.ts @@ -0,0 +1,13 @@ +export class CallControlState { + public readonly microphone: boolean; + + public readonly video: boolean; + + public readonly sound: boolean; + + constructor(microphone: boolean, video: boolean, sound: boolean) { + this.microphone = microphone; + this.video = video; + this.sound = sound; + } +} diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts new file mode 100644 index 00000000..b852e3ef --- /dev/null +++ b/src/app/plugins/call/CallEmbed.ts @@ -0,0 +1,358 @@ +import { + ClientEvent, + KnownMembership, + MatrixClient, + MatrixEvent, + MatrixEventEvent, + Room, + RoomStateEvent, +} from 'matrix-js-sdk'; +import { + ClientWidgetApi, + IRoomEvent, + IWidget, + Widget, + WidgetApiToWidgetAction, + WidgetDriver, +} from 'matrix-widget-api'; +import { CallWidgetDriver } from './CallWidgetDriver'; +import { trimTrailingSlash } from '../../utils/common'; +import { + ElementCallIntent, + ElementCallThemeKind, + ElementMediaStateDetail, + ElementWidgetActions, +} from './types'; +import { CallControl } from './CallControl'; +import { CallControlState } from './CallControlState'; + +export class CallEmbed { + private mx: MatrixClient; + + public readonly call: ClientWidgetApi; + + public readonly iframe: HTMLIFrameElement; + + public readonly room: Room; + + public joined = false; + + public readonly control: CallControl; + + private readonly container: HTMLElement; + + private readUpToMap: { [roomId: string]: string } = {}; // room ID to event ID + + private eventsToFeed = new WeakSet(); + + private readonly disposables: Array<() => void> = []; + + static getIntent(dm: boolean, ongoing: boolean): ElementCallIntent { + if (ongoing) { + return dm ? ElementCallIntent.JoinExistingDM : ElementCallIntent.JoinExisting; + } + + return dm ? ElementCallIntent.StartCallDM : ElementCallIntent.StartCall; + } + + static getWidget( + mx: MatrixClient, + room: Room, + intent: ElementCallIntent, + themeKind: ElementCallThemeKind + ): Widget { + const userId = mx.getSafeUserId(); + const deviceId = mx.getDeviceId() ?? ''; + const clientOrigin = window.location.origin; + const widgetId = 'call-embed'; + + const params = new URLSearchParams({ + widgetId, + parentUrl: clientOrigin, + baseUrl: mx.baseUrl, + roomId: room.roomId, + userId, + deviceId, + intent, + + skipLobby: 'true', + confineToRoom: 'true', + appPrompt: 'false', + perParticipantE2EE: room.hasEncryptionStateEvent().toString(), + lang: 'en-EN', + theme: themeKind, + }); + + const widgetUrl = new URL( + `${trimTrailingSlash(import.meta.env.BASE_URL)}/public/element-call/index.html`, + window.location.origin + ); + widgetUrl.search = params.toString(); + + const options: IWidget = { + id: widgetId, + creatorUserId: userId, + name: 'Call', + type: 'm.call', + url: widgetUrl.href, + waitForIframeLoad: false, + data: {}, + }; + + const widget: Widget = new Widget(options); + + return widget; + } + + static getIframe(url: string): HTMLIFrameElement { + const iframe = document.createElement('iframe'); + + iframe.title = 'Call Embed'; + iframe.sandbox = + 'allow-forms allow-scripts allow-same-origin allow-popups allow-modals allow-downloads'; + iframe.allow = 'microphone; camera; display-capture; autoplay; clipboard-write;'; + iframe.src = url; + + iframe.style.width = '100%'; + iframe.style.height = '100%'; + iframe.style.border = 'none'; + + return iframe; + } + + constructor( + mx: MatrixClient, + room: Room, + widget: Widget, + container: HTMLElement, + initialControlState?: CallControlState + ) { + const iframe = CallEmbed.getIframe( + widget.getCompleteUrl({ currentUserId: mx.getSafeUserId() }) + ); + container.append(iframe); + + const callWidgetDriver: WidgetDriver = new CallWidgetDriver(mx, room.roomId); + const call: ClientWidgetApi = new ClientWidgetApi(widget, iframe, callWidgetDriver); + + this.mx = mx; + this.call = call; + this.room = room; + this.iframe = iframe; + this.container = container; + + const controlState = initialControlState ?? new CallControlState(true, false, true); + this.control = new CallControl(controlState, call, iframe); + + let initialMediaEvent = true; + this.disposables.push( + this.listenEvent(ElementWidgetActions.DeviceMute, (evt) => { + if (initialMediaEvent) { + initialMediaEvent = false; + this.control.applyState(); + return; + } + this.control.onMediaState(evt); + }) + ); + + this.start(); + } + + get roomId(): string { + return this.room.roomId; + } + + public setTheme(theme: ElementCallThemeKind) { + return this.call.transport.send(WidgetApiToWidgetAction.ThemeChange, { + name: theme, + }); + } + + public hangup() { + return this.call.transport.send(ElementWidgetActions.HangupCall, {}); + } + + public listenEvent(type: string, callback: (event: CustomEvent) => void) { + this.call.on(`action:${type}`, callback); + return () => { + this.call.off(`action:${type}`, callback); + }; + } + + private start() { + // Room widgets get locked to the room they were added in + this.call.setViewedRoomId(this.roomId); + this.disposables.push( + this.listenEvent(ElementWidgetActions.JoinCall, this.onCallJoined.bind(this)) + ); + + // Populate the map of "read up to" events for this widget with the current event in every room. + // This is a bit inefficient, but should be okay. We do this for all rooms in case the widget + // requests timeline capabilities in other rooms down the road. It's just easier to manage here. + this.mx.getRooms().forEach((room) => { + // Timelines are most recent last + const events = room.getLiveTimeline()?.getEvents() || []; + const roomEvent = events[events.length - 1]; + if (!roomEvent) return; // force later code to think the room is fresh + this.readUpToMap[room.roomId] = roomEvent.getId()!; + }); + + // Attach listeners for feeding events - the underlying widget classes handle permissions for us + this.mx.on(ClientEvent.Event, this.onEvent.bind(this)); + this.mx.on(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); + this.mx.on(RoomStateEvent.Events, this.onStateUpdate.bind(this)); + this.mx.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); + } + + /** + * Stops the widget messaging for if it is started. Skips stopping if it is an active + * widget. + * @param opts + */ + public dispose(): void { + this.disposables.forEach((disposable) => { + disposable(); + }); + this.call.stop(); + this.container.removeChild(this.iframe); + + this.mx.off(ClientEvent.Event, this.onEvent.bind(this)); + this.mx.off(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); + this.mx.off(RoomStateEvent.Events, this.onStateUpdate.bind(this)); + this.mx.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); + + // Clear internal state + this.readUpToMap = {}; + this.eventsToFeed = new WeakSet(); + } + + private onCallJoined(): void { + this.joined = true; + } + + private onEvent(ev: MatrixEvent): void { + this.mx.decryptEventIfNeeded(ev); + this.feedEvent(ev); + } + + private onEventDecrypted(ev: MatrixEvent): void { + this.feedEvent(ev); + } + + private onStateUpdate(ev: MatrixEvent): void { + if (this.call === null) return; + const raw = ev.getEffectiveEvent(); + this.call.feedStateUpdate(raw as IRoomEvent).catch((e) => { + console.error('Error sending state update to widget: ', e); + }); + } + + private async onToDeviceEvent(ev: MatrixEvent): Promise { + await this.mx.decryptEventIfNeeded(ev); + if (ev.isDecryptionFailure()) return; + await this.call?.feedToDevice(ev.getEffectiveEvent() as IRoomEvent, ev.isEncrypted()); + } + + /** + * Determines whether the event has a relation to an unknown parent. + */ + private relatesToUnknown(ev: MatrixEvent): boolean { + // Replies to unknown events don't count + if (!ev.relationEventId || ev.replyEventId) return false; + const room = this.mx.getRoom(ev.getRoomId()); + return room === null || !room.findEventById(ev.relationEventId); + } + + /** + * Advances the "read up to" marker for a room to a certain event. No-ops if + * the event is before the marker. + * @returns Whether the "read up to" marker was advanced. + */ + private advanceReadUpToMarker(ev: MatrixEvent): boolean { + const evId = ev.getId(); + if (evId === undefined) return false; + const roomId = ev.getRoomId(); + if (roomId === undefined) return false; + const room = this.mx.getRoom(roomId); + if (room === null) return false; + + const upToEventId = this.readUpToMap[ev.getRoomId()!]; + if (!upToEventId) { + // There's no marker yet; start it at this event + this.readUpToMap[roomId] = evId; + return true; + } + + // Small optimization for exact match (skip the search) + if (upToEventId === evId) return false; + + // Timelines are most recent last, so reverse the order and limit ourselves to 100 events + // to avoid overusing the CPU. + const timeline = room.getLiveTimeline(); + const events = [...timeline.getEvents()].reverse().slice(0, 100); + function isRelevantTimelineEvent(timelineEvent: MatrixEvent): boolean { + return timelineEvent.getId() === upToEventId || timelineEvent.getId() === ev.getId(); + } + const possibleMarkerEv = events.find(isRelevantTimelineEvent); + if (possibleMarkerEv?.getId() === upToEventId) { + // The event must be somewhere before the "read up to" marker + return false; + } + if (possibleMarkerEv?.getId() === ev.getId()) { + // The event is after the marker; advance it + this.readUpToMap[roomId] = evId; + return true; + } + + // We can't say for sure whether the widget has seen the event; let's + // just assume that it has + return false; + } + + /** + * Determines whether the event comes from a room that we've been invited to + * (in which case we likely don't have the full timeline). + */ + private isFromInvite(ev: MatrixEvent): boolean { + const room = this.mx.getRoom(ev.getRoomId()); + return room?.getMyMembership() === KnownMembership.Invite; + } + + private feedEvent(ev: MatrixEvent): void { + if (this.call === null) return; + if ( + // If we had decided earlier to feed this event to the widget, but + // it just wasn't ready, give it another try + this.eventsToFeed.delete(ev) || + // Skip marker timeline check for events with relations to unknown parent because these + // events are not added to the timeline here and will be ignored otherwise: + // https://github.com/matrix-org/matrix-js-sdk/blob/d3dfcd924201d71b434af3d77343b5229b6ed75e/src/models/room.ts#L2207-L2213 + this.relatesToUnknown(ev) || + // Skip marker timeline check for rooms where membership is + // 'invite', otherwise the membership event from the invitation room + // will advance the marker and new state events will not be + // forwarded to the widget. + this.isFromInvite(ev) || + // Check whether this event would be before or after our "read up to" marker. If it's + // before, or we can't decide, then we assume the widget will have already seen the event. + // If the event is after, or we don't have a marker for the room, + // then the marker will advance and we'll send it through. + // This approach of "read up to" prevents widgets receiving decryption spam from startup or + // receiving ancient events from backfill and such. + this.advanceReadUpToMarker(ev) + ) { + // If the event is still being decrypted, remember that we want to + // feed it to the widget (even if not strictly in the order given by + // the timeline) and get back to it later + if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) { + this.eventsToFeed.add(ev); + } else { + const raw = ev.getEffectiveEvent(); + this.call.feedEvent(raw as IRoomEvent).catch((e) => { + console.error('Error sending event to widget: ', e); + }); + } + } + } +} diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts new file mode 100644 index 00000000..babe90ef --- /dev/null +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -0,0 +1,340 @@ +import { + type Capability, + type ISendDelayedEventDetails, + type ISendEventDetails, + type IReadEventRelationsResult, + type IRoomEvent, + WidgetDriver, + type IWidgetApiErrorResponseDataDetails, + type ISearchUserDirectoryResult, + type IGetMediaConfigResult, + type UpdateDelayedEventAction, + OpenIDRequestState, + SimpleObservable, + IOpenIDUpdate, +} from 'matrix-widget-api'; +import { + EventType, + type IContent, + MatrixError, + type MatrixEvent, + Direction, + type SendDelayedEventResponse, + type StateEvents, + type TimelineEvents, + MatrixClient, +} from 'matrix-js-sdk'; +import { getCallCapabilities } from './utils'; +import { downloadMedia, mxcUrlToHttp } from '../../utils/matrix'; + +export class CallWidgetDriver extends WidgetDriver { + private allowedCapabilities: Set; + + private readonly mx: MatrixClient; + + public constructor(mx: MatrixClient, private inRoomId: string) { + super(); + this.mx = mx; + + const deviceId = mx.getDeviceId(); + if (!deviceId) throw new Error('Failed to initialize CallWidgetDriver! Device ID not found.'); + + this.allowedCapabilities = getCallCapabilities(inRoomId, mx.getSafeUserId(), deviceId); + } + + public async validateCapabilities(requested: Set): Promise> { + const allow = Array.from(requested).filter((cap) => this.allowedCapabilities.has(cap)); + return new Set(allow); + } + + public async sendEvent( + eventType: string, + content: IContent, + stateKey: string | null = null, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + let r: { event_id: string } | null; + if (typeof stateKey === 'string') { + r = await client.sendStateEvent( + roomId, + eventType as keyof StateEvents, + content as StateEvents[keyof StateEvents], + stateKey + ); + } else if (eventType === EventType.RoomRedaction) { + // special case: extract the `redacts` property and call redact + r = await client.redactEvent(roomId, content.redacts); + } else { + r = await client.sendEvent( + roomId, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + } + + return { roomId, eventId: r.event_id }; + } + + public async sendDelayedEvent( + delay: number | null, + parentDelayId: string | null, + eventType: string, + content: IContent, + stateKey: string | null = null, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + let delayOpts; + if (delay !== null) { + delayOpts = { + delay, + ...(parentDelayId !== null && { parent_delay_id: parentDelayId }), + }; + } else if (parentDelayId !== null) { + delayOpts = { + parent_delay_id: parentDelayId, + }; + } else { + throw new Error('Must provide at least one of delay or parentDelayId'); + } + + let r: SendDelayedEventResponse | null; + if (stateKey !== null) { + // state event + r = await client._unstable_sendDelayedStateEvent( + roomId, + delayOpts, + eventType as keyof StateEvents, + content as StateEvents[keyof StateEvents], + stateKey + ); + } else { + // message event + r = await client._unstable_sendDelayedEvent( + roomId, + delayOpts, + null, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + } + + return { + roomId, + delayId: r.delay_id, + }; + } + + public async updateDelayedEvent( + delayId: string, + action: UpdateDelayedEventAction + ): Promise { + const client = this.mx; + + if (!client) throw new Error('Not in a room or not attached to a client'); + + await client._unstable_updateDelayedEvent(delayId, action); + } + + public async sendToDevice( + eventType: string, + encrypted: boolean, + contentMap: { [userId: string]: { [deviceId: string]: object } } + ): Promise { + const client = this.mx; + + if (encrypted) { + const crypto = client.getCrypto(); + if (!crypto) throw new Error('E2EE not enabled'); + + // attempt to re-batch these up into a single request + const invertedContentMap: { [content: string]: { userId: string; deviceId: string }[] } = {}; + + // eslint-disable-next-line no-restricted-syntax + for (const userId of Object.keys(contentMap)) { + const userContentMap = contentMap[userId]; + // eslint-disable-next-line no-restricted-syntax + for (const deviceId of Object.keys(userContentMap)) { + const content = userContentMap[deviceId]; + const stringifiedContent = JSON.stringify(content); + invertedContentMap[stringifiedContent] = invertedContentMap[stringifiedContent] || []; + invertedContentMap[stringifiedContent].push({ userId, deviceId }); + } + } + + await Promise.all( + Object.entries(invertedContentMap).map(async ([stringifiedContent, recipients]) => { + const batch = await crypto.encryptToDeviceMessages( + eventType, + recipients, + JSON.parse(stringifiedContent) + ); + + await client.queueToDevice(batch); + }) + ); + } else { + await client.queueToDevice({ + eventType, + batch: Object.entries(contentMap).flatMap(([userId, userContentMap]) => + Object.entries(userContentMap).map(([deviceId, content]) => ({ + userId, + deviceId, + payload: content, + })) + ), + }); + } + } + + public async readRoomTimeline( + roomId: string, + eventType: string, + msgtype: string | undefined, + stateKey: string | undefined, + limit: number, + since: string | undefined + ): Promise { + const safeLimit = + limit > 0 ? Math.min(limit, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary + + const room = this.mx.getRoom(roomId); + if (room === null) return []; + const results: MatrixEvent[] = []; + const events = room.getLiveTimeline().getEvents(); + + for (let i = events.length - 1; i >= 0; i -= 1) { + const ev = events[i]; + if (results.length >= safeLimit) break; + if (since !== undefined && ev.getId() === since) break; + + if ( + ev.getType() === eventType && + !ev.isState() && + (eventType !== EventType.RoomMessage || !msgtype || msgtype === ev.getContent().msgtype) && + (ev.getStateKey() === undefined || stateKey === undefined || ev.getStateKey() === stateKey) + ) { + results.push(ev); + } + } + + return results.map((e) => e.getEffectiveEvent() as IRoomEvent); + } + + public async askOpenID(observer: SimpleObservable): Promise { + return observer.update({ + state: OpenIDRequestState.Allowed, + token: await this.mx.getOpenIdToken(), + }); + } + + public async readRoomState( + roomId: string, + eventType: string, + stateKey: string | undefined + ): Promise { + const room = this.mx.getRoom(roomId); + if (room === null) return []; + const state = room.getLiveTimeline().getState(Direction.Forward); + if (state === undefined) return []; + + if (stateKey === undefined) + return state.getStateEvents(eventType).map((e) => e.getEffectiveEvent() as IRoomEvent); + const event = state.getStateEvents(eventType, stateKey); + return event === null ? [] : [event.getEffectiveEvent() as IRoomEvent]; + } + + public async readEventRelations( + eventId: string, + roomId?: string, + relationType?: string, + eventType?: string, + from?: string, + to?: string, + limit?: number, + direction?: 'f' | 'b' + ): Promise { + const client = this.mx; + const dir = direction as Direction; + const targetRoomId = roomId ?? this.inRoomId ?? undefined; + + if (typeof targetRoomId !== 'string') { + throw new Error('Error while reading the current room'); + } + + const { events, nextBatch, prevBatch } = await client.relations( + targetRoomId, + eventId, + relationType ?? null, + eventType ?? null, + { from, to, limit, dir } + ); + + return { + chunk: events.map((e) => e.getEffectiveEvent() as IRoomEvent), + nextBatch: nextBatch ?? undefined, + prevBatch: prevBatch ?? undefined, + }; + } + + public async searchUserDirectory( + searchTerm: string, + limit?: number + ): Promise { + const client = this.mx; + + const { limited, results } = await client.searchUserDirectory({ term: searchTerm, limit }); + + return { + limited, + results: results.map((r) => ({ + userId: r.user_id, + displayName: r.display_name, + avatarUrl: r.avatar_url, + })), + }; + } + + public async getMediaConfig(): Promise { + const client = this.mx; + + return client.getMediaConfig(); + } + + public async uploadFile(file: XMLHttpRequestBodyInit): Promise<{ contentUri: string }> { + const client = this.mx; + + const uploadResult = await client.uploadContent(file); + + return { contentUri: uploadResult.content_uri }; + } + + public async downloadFile(contentUri: string): Promise<{ file: XMLHttpRequestBodyInit }> { + const httpUrl = mxcUrlToHttp(this.mx, contentUri, true); + if (!httpUrl) { + throw new Error('Call widget failed to download file! No http url!'); + } + const blob = await downloadMedia(httpUrl); + return { file: blob }; + } + + public getKnownRooms(): string[] { + return this.mx.getVisibleRooms().map((r) => r.roomId); + } + + // eslint-disable-next-line class-methods-use-this + public processError(error: unknown): IWidgetApiErrorResponseDataDetails | undefined { + return error instanceof MatrixError + ? { matrix_api_error: error.asWidgetApiErrorData() } + : undefined; + } +} diff --git a/src/app/plugins/call/hooks.ts b/src/app/plugins/call/hooks.ts new file mode 100644 index 00000000..f5b3ff93 --- /dev/null +++ b/src/app/plugins/call/hooks.ts @@ -0,0 +1,49 @@ +import { + ClientWidgetApi, + IWidgetApiAcknowledgeResponseData, + IWidgetApiRequestData, +} from 'matrix-widget-api'; +import { useCallback, useEffect, useState } from 'react'; +import { CallControl, CallControlEvent } from './CallControl'; +import { CallControlState } from './CallControlState'; + +export const useClientWidgetApiEvent = ( + api: ClientWidgetApi | undefined, + type: string, + callback: (event: CustomEvent) => void +) => { + useEffect(() => { + api?.on(`action:${type}`, callback); + return () => { + api?.off(`action:${type}`, callback); + }; + }, [api, type, callback]); +}; + +export const useSendClientWidgetApiAction = (api: ClientWidgetApi) => { + const sendWidgetAction = useCallback( + async ( + action: string, + data: T + ): Promise => api.transport.send(action, data), + [api] + ); + + return sendWidgetAction; +}; + +export const useCallControlState = (control: CallControl): CallControlState => { + const [state, setState] = useState(control.getState()); + + useEffect(() => { + const handleUpdate = () => { + setState(control.getState()); + }; + control.on(CallControlEvent.StateUpdate, handleUpdate); + return () => { + control.off(CallControlEvent.StateUpdate, handleUpdate); + }; + }, [control]); + + return state; +}; diff --git a/src/app/plugins/call/index.ts b/src/app/plugins/call/index.ts new file mode 100644 index 00000000..a4c6bb36 --- /dev/null +++ b/src/app/plugins/call/index.ts @@ -0,0 +1,3 @@ +export * from './CallEmbed'; +export * from './hooks'; +export * from './types'; diff --git a/src/app/plugins/call/types.ts b/src/app/plugins/call/types.ts new file mode 100644 index 00000000..4f4fc381 --- /dev/null +++ b/src/app/plugins/call/types.ts @@ -0,0 +1,25 @@ +export enum ElementCallIntent { + StartCall = 'start_call', + JoinExisting = 'join_existing', + StartCallDM = 'start_call_dm', + JoinExistingDM = 'join_existing_dm', + StartCallDMVoice = 'start_call_dm_voice', + JoinExistingDMVoice = 'join_existing_dm_voice', +} + +export type ElementCallThemeKind = 'light' | 'dark'; + +export type ElementMediaStatePayload = { + audio_enabled?: boolean; + video_enabled?: boolean; +}; +export type ElementMediaStateDetail = { + data?: ElementMediaStatePayload; +}; + +export enum ElementWidgetActions { + JoinCall = 'io.element.join', + HangupCall = 'im.vector.hangup', + Close = 'io.element.close', + DeviceMute = 'io.element.device_mute', +} diff --git a/src/app/plugins/call/utils.ts b/src/app/plugins/call/utils.ts new file mode 100644 index 00000000..0ea72b3c --- /dev/null +++ b/src/app/plugins/call/utils.ts @@ -0,0 +1,118 @@ +import { + type Capability, + EventDirection, + MatrixCapabilities, + WidgetEventCapability, +} from 'matrix-widget-api'; +import { EventType } from 'matrix-js-sdk'; + +export function getCallCapabilities( + roomId: string, + userId: string, + deviceId: string +): Set { + const capabilities: Set = new Set(); + + capabilities.add(MatrixCapabilities.Screenshots); + capabilities.add(MatrixCapabilities.AlwaysOnScreen); + capabilities.add(MatrixCapabilities.MSC3846TurnServers); + capabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent); + capabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent); + capabilities.add(`org.matrix.msc2762.timeline:${roomId}`); + capabilities.add(`org.matrix.msc2762.state:${roomId}`); + + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomMember).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call').raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomEncryption).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomName).raw + ); + + capabilities.add( + WidgetEventCapability.forStateEvent( + EventDirection.Send, + 'org.matrix.msc3401.call.member', + userId + ).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent( + EventDirection.Send, + 'org.matrix.msc3401.call.member', + `_${userId}_${deviceId}_m.call` + ).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent( + EventDirection.Send, + 'org.matrix.msc3401.call.member', + `${userId}_${deviceId}_m.call` + ).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent( + EventDirection.Send, + 'org.matrix.msc3401.call.member', + `_${userId}_${deviceId}` + ).raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent( + EventDirection.Send, + 'org.matrix.msc3401.call.member', + `${userId}_${deviceId}` + ).raw + ); + + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call.member') + .raw + ); + capabilities.add( + WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomCreate).raw + ); + + capabilities.add( + WidgetEventCapability.forRoomEvent( + EventDirection.Receive, + 'org.matrix.msc4075.rtc.notification' + ).raw + ); + + [ + 'io.element.call.encryption_keys', + 'org.matrix.rageshake_request', + EventType.Reaction, + EventType.RoomRedaction, + 'io.element.call.reaction', + 'org.matrix.msc4310.rtc.decline', + ].forEach((type) => { + capabilities.add(WidgetEventCapability.forRoomEvent(EventDirection.Send, type).raw); + capabilities.add(WidgetEventCapability.forRoomEvent(EventDirection.Receive, type).raw); + }); + + [ + EventType.CallInvite, + EventType.CallCandidates, + EventType.CallAnswer, + EventType.CallHangup, + EventType.CallReject, + EventType.CallSelectAnswer, + EventType.CallNegotiate, + EventType.CallSDPStreamMetadataChanged, + EventType.CallSDPStreamMetadataChangedPrefix, + EventType.CallReplaces, + EventType.CallEncryptionKeysPrefix, + ].forEach((type) => { + capabilities.add(WidgetEventCapability.forToDeviceEvent(EventDirection.Send, type).raw); + capabilities.add(WidgetEventCapability.forToDeviceEvent(EventDirection.Receive, type).raw); + }); + + return capabilities; +} diff --git a/src/app/state/callEmbed.ts b/src/app/state/callEmbed.ts new file mode 100644 index 00000000..a9f89300 --- /dev/null +++ b/src/app/state/callEmbed.ts @@ -0,0 +1,20 @@ +import { atom } from 'jotai'; +import { CallEmbed } from '../plugins/call'; + +const baseCallEmbedAtom = atom(undefined); + +export const callEmbedAtom = atom( + (get) => get(baseCallEmbedAtom), + (get, set, callEmbed) => { + const prevCallEmbed = get(baseCallEmbedAtom); + if (callEmbed === prevCallEmbed) return; + + if (prevCallEmbed) { + prevCallEmbed.dispose(); + } + + set(baseCallEmbedAtom, callEmbed); + } +); + +export const callChatAtom = atom(false); diff --git a/src/app/state/callPreferences.ts b/src/app/state/callPreferences.ts new file mode 100644 index 00000000..a8e82067 --- /dev/null +++ b/src/app/state/callPreferences.ts @@ -0,0 +1,39 @@ +import { WritableAtom } from 'jotai'; +import { + atomWithLocalStorage, + getLocalStorageItem, + setLocalStorageItem, +} from './utils/atomWithLocalStorage'; + +export type CallPreferences = { + microphone: boolean; + video: boolean; + sound: boolean; +}; + +const CALL_PREFERENCES = 'callPreferences'; + +const DEFAULT_PREFERENCES: CallPreferences = { + microphone: true, + video: false, + sound: true, +}; + +export type CallPreferencesAtom = WritableAtom; + +export const makeCallPreferencesAtom = (userId: string): CallPreferencesAtom => { + const storeKey = `${CALL_PREFERENCES}${userId}`; + + const callPreferencesAtom = atomWithLocalStorage( + storeKey, + (key) => { + const v = getLocalStorageItem(key, DEFAULT_PREFERENCES); + return v; + }, + (key, value) => { + setLocalStorageItem(key, value); + } + ); + + return callPreferencesAtom; +}; diff --git a/src/app/state/createRoomModal.ts b/src/app/state/createRoomModal.ts index 81af5d5b..f32e7665 100644 --- a/src/app/state/createRoomModal.ts +++ b/src/app/state/createRoomModal.ts @@ -1,7 +1,9 @@ import { atom } from 'jotai'; +import { CreateRoomType } from '../components/create-room/types'; export type CreateRoomModalState = { spaceId?: string; + type?: CreateRoomType; }; export const createRoomModalAtom = atom(undefined); diff --git a/src/app/state/hooks/callPreferences.ts b/src/app/state/hooks/callPreferences.ts new file mode 100644 index 00000000..829ed4b4 --- /dev/null +++ b/src/app/state/hooks/callPreferences.ts @@ -0,0 +1,61 @@ +import { createContext, useCallback, useContext } from 'react'; +import { useAtom } from 'jotai'; +import { CallPreferences, CallPreferencesAtom } from '../callPreferences'; + +const CallPreferencesAtomContext = createContext(null); +export const CallPreferencesProvider = CallPreferencesAtomContext.Provider; + +export const useCallPreferencesAtom = (): CallPreferencesAtom => { + const atom = useContext(CallPreferencesAtomContext); + if (!atom) { + throw new Error('CallPreferencesAtom not provided!'); + } + + return atom; +}; + +export const useCallPreferences = (): CallPreferences & { + toggleMicrophone: () => void; + toggleVideo: () => void; + toggleSound: () => void; +} => { + const callPrefAtom = useCallPreferencesAtom(); + const [pref, setPref] = useAtom(callPrefAtom); + + const toggleMicrophone = useCallback(() => { + const microphone = !pref.microphone; + + setPref({ + microphone, + video: pref.video, + sound: !pref.sound && microphone ? true : pref.sound, + }); + }, [setPref, pref]); + + const toggleVideo = useCallback(() => { + const video = !pref.video; + + setPref({ + microphone: pref.microphone, + video, + sound: pref.sound, + }); + }, [setPref, pref]); + + const toggleSound = useCallback(() => { + const sound = !pref.sound; + + setPref({ + microphone: !sound ? false : pref.microphone, + video: pref.video, + sound, + }); + }, [setPref, pref]); + + return { + ...pref, + toggleMicrophone, + toggleVideo, + toggleSound, + }; +}; diff --git a/src/app/state/hooks/createRoomModal.ts b/src/app/state/hooks/createRoomModal.ts index 15db7289..2663e5dc 100644 --- a/src/app/state/hooks/createRoomModal.ts +++ b/src/app/state/hooks/createRoomModal.ts @@ -1,6 +1,7 @@ import { useCallback } from 'react'; import { useAtomValue, useSetAtom } from 'jotai'; import { createRoomModalAtom, CreateRoomModalState } from '../createRoomModal'; +import { CreateRoomType } from '../../components/create-room/types'; export const useCreateRoomModalState = (): CreateRoomModalState | undefined => { const data = useAtomValue(createRoomModalAtom); @@ -19,13 +20,13 @@ export const useCloseCreateRoomModal = (): CloseCallback => { return close; }; -type OpenCallback = (space?: string) => void; +type OpenCallback = (space?: string, type?: CreateRoomType) => void; export const useOpenCreateRoomModal = (): OpenCallback => { const setSettings = useSetAtom(createRoomModalAtom); const open: OpenCallback = useCallback( - (spaceId) => { - setSettings({ spaceId }); + (spaceId, type) => { + setSettings({ spaceId, type }); }, [setSettings] ); diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index c282a0a2..05dfeb29 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -161,7 +161,8 @@ export const getOrphanParents = (roomToParents: RoomToParents, roomId: string): export const isMutedRule = (rule: IPushRule) => // Check for empty actions (new spec) or dont_notify (deprecated) - (rule.actions.length === 0 || rule.actions[0] === 'dont_notify') && rule.conditions?.[0]?.kind === 'event_match'; + (rule.actions.length === 0 || rule.actions[0] === 'dont_notify') && + rule.conditions?.[0]?.kind === 'event_match'; export const findMutedRule = (overrideRules: IPushRule[], roomId: string) => overrideRules.find((rule) => rule.rule_id === roomId && isMutedRule(rule)); @@ -257,24 +258,44 @@ export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => { return unreadInfos; }; -export const joinRuleToIconSrc = ( +export const getRoomIconSrc = ( icons: Record, - joinRule: JoinRule, - space: boolean -): IconSrc | undefined => { - if (joinRule === JoinRule.Restricted) { - return space ? icons.Space : icons.Hash; + roomType?: string, + joinRule?: JoinRule +): IconSrc => { + if (roomType === RoomType.Space) { + if (joinRule === JoinRule.Public) return icons.SpaceGlobe; + if ( + joinRule === JoinRule.Invite || + joinRule === JoinRule.Knock || + joinRule === JoinRule.Private + ) { + return icons.SpaceLock; + } + return icons.Space; } - if (joinRule === JoinRule.Knock) { - return space ? icons.SpaceLock : icons.HashLock; + + if (roomType === RoomType.Call) { + if (joinRule === JoinRule.Public) return icons.VolumeHighGlobe; + if ( + joinRule === JoinRule.Invite || + joinRule === JoinRule.Knock || + joinRule === JoinRule.Private + ) { + return icons.VolumeHighLock; + } + return icons.VolumeHigh; } - if (joinRule === JoinRule.Invite) { - return space ? icons.SpaceLock : icons.HashLock; + + if (joinRule === JoinRule.Public) return icons.HashGlobe; + if ( + joinRule === JoinRule.Invite || + joinRule === JoinRule.Knock || + joinRule === JoinRule.Private + ) { + return icons.HashLock; } - if (joinRule === JoinRule.Public) { - return space ? icons.SpaceGlobe : icons.HashGlobe; - } - return undefined; + return icons.Hash; }; export const getRoomAvatarUrl = ( diff --git a/src/types/matrix/room.ts b/src/types/matrix/room.ts index b866fd77..c73c0f0b 100644 --- a/src/types/matrix/room.ts +++ b/src/types/matrix/room.ts @@ -32,6 +32,8 @@ export enum StateEvent { RoomGuestAccess = 'm.room.guest_access', RoomServerAcl = 'm.room.server_acl', RoomTombstone = 'm.room.tombstone', + GroupCallPrefix = 'org.matrix.msc3401.call', + GroupCallMemberPrefix = 'org.matrix.msc3401.call.member', SpaceChild = 'm.space.child', SpaceParent = 'm.space.parent', @@ -50,6 +52,7 @@ export enum MessageEvent { export enum RoomType { Space = 'm.space', + Call = 'org.matrix.msc3417.call', } export type MSpaceChildContent = { diff --git a/vite.config.js b/vite.config.js index dfa02fc4..a5af94d8 100644 --- a/vite.config.js +++ b/vite.config.js @@ -13,6 +13,10 @@ import buildConfig from './build.config'; const copyFiles = { targets: [ + { + src: 'node_modules/@element-hq/element-call-embedded/dist/*', + dest: 'public/element-call', + }, { src: 'node_modules/pdfjs-dist/build/pdf.worker.min.mjs', dest: '', @@ -47,7 +51,10 @@ function serverMatrixSdkCryptoWasm(wasmFilePath) { configureServer(server) { server.middlewares.use((req, res, next) => { if (req.url === wasmFilePath) { - const resolvedPath = path.join(path.resolve(), "/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm"); + const resolvedPath = path.join( + path.resolve(), + '/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm' + ); if (fs.existsSync(resolvedPath)) { res.setHeader('Content-Type', 'application/wasm'); @@ -102,8 +109,8 @@ export default defineConfig({ }, devOptions: { enabled: true, - type: 'module' - } + type: 'module', + }, }), ], optimizeDeps: { From 52f9bac58f7225ab5c9c802ffeaeaae491cc9ec2 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 01:51:50 -0600 Subject: [PATCH 089/124] reduced motion toggle --- .changeset/y_reduced_motion_option.md | 5 +++ src/app/features/room/RoomTimeline.tsx | 9 ++-- .../features/settings/cosmetics/Themes.tsx | 8 ++++ src/app/pages/ThemeManager.tsx | 9 +++- src/app/state/settings.ts | 2 + src/index.css | 41 +++++++++++++++++++ 6 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 .changeset/y_reduced_motion_option.md diff --git a/.changeset/y_reduced_motion_option.md b/.changeset/y_reduced_motion_option.md new file mode 100644 index 00000000..4cec37f5 --- /dev/null +++ b/.changeset/y_reduced_motion_option.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Added reduced motion setting. Let us know if any elements were missed! diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 38063d24..7cb5a9e1 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -571,6 +571,7 @@ export function RoomTimeline({ const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; const [showHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents'); const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); + const [reducedMotion] = useSetting(settingsAtom, 'reducedMotion'); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); @@ -814,7 +815,7 @@ export function RoomTimeline({ if (typeof absoluteIndex === 'number') { const scrolled = scrollToItem(absoluteIndex, { - behavior: 'smooth', + behavior: reducedMotion ? 'instant' : 'smooth', align: 'center', stopInView: true, }); @@ -828,7 +829,7 @@ export function RoomTimeline({ loadEventTimeline(evtId); } }, - [room, timeline, scrollToItem, loadEventTimeline] + [room, timeline, scrollToItem, loadEventTimeline, reducedMotion] ); useLiveTimelineRefresh( @@ -1067,7 +1068,7 @@ export function RoomTimeline({ if (scrollToBottomCount > 0) { const scrollEl = scrollRef.current; if (scrollEl) { - const behavior = scrollToBottomRef.current.smooth ? 'smooth' : 'instant'; + const behavior = scrollToBottomRef.current.smooth && !reducedMotion ? 'smooth' : 'instant'; scrollToBottom(scrollEl, behavior); // On Android WebView, layout may still settle after the initial scroll. // Fire a second instant scroll after a short delay to guarantee we @@ -1078,7 +1079,7 @@ export function RoomTimeline({ } } } - }, [scrollToBottomCount]); + }, [scrollToBottomCount, reducedMotion]); // Remove unreadInfo on mark as read useEffect(() => { diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 6203ad8b..043b0f0f 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -246,6 +246,7 @@ function ThemeSettings() { const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); const [underlineLinks, setUnderlineLinks] = useSetting(settingsAtom, 'underlineLinks'); + const [reducedMotion, setReducedMotion] = useSetting(settingsAtom, 'reducedMotion'); return ( @@ -305,6 +306,13 @@ function ThemeSettings() { after={} /> + + } + /> + ); } diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 2b335012..90a7e578 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -32,6 +32,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { const activeTheme = useActiveTheme(); const [saturation] = useSetting(settingsAtom, 'saturationLevel'); const [underlineLinks] = useSetting(settingsAtom, 'underlineLinks'); + const [reducedMotion] = useSetting(settingsAtom, 'reducedMotion'); useEffect(() => { document.body.className = ''; @@ -44,6 +45,12 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { document.body.classList.remove('force-underline-links'); } + if (reducedMotion) { + document.body.classList.add('reduced-motion'); + } else { + document.body.classList.remove('reduced-motion'); + } + if (saturation === 0) { document.body.style.filter = 'grayscale(1)'; } else if (saturation && saturation < 100) { @@ -51,7 +58,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { } else { document.body.style.filter = ''; } - }, [activeTheme, saturation, underlineLinks]); + }, [activeTheme, saturation, underlineLinks, reducedMotion]); return {children}; } diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 5daaad09..88f9c908 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -81,6 +81,7 @@ export interface Settings { hideReads: boolean; emojiSuggestThreshold: number; underlineLinks: boolean; + reducedMotion: boolean; // furry stuff renderAnimals: boolean; @@ -151,6 +152,7 @@ const defaultSettings: Settings = { hideReads: false, emojiSuggestThreshold: 2, underlineLinks: false, + reducedMotion: false, // furry stuff renderAnimals: true, diff --git a/src/index.css b/src/index.css index cebe1da7..b0edbc4f 100755 --- a/src/index.css +++ b/src/index.css @@ -175,8 +175,49 @@ pre { font-variant-ligatures: contextual; } +/* Accessibility Overrides :D */ + .force-underline-links a { text-decoration: underline !important; text-decoration-thickness: 1px; text-underline-offset: 2px; } + +body.reduced-motion * { + animation-duration: 0.001ms !important; + transition-duration: 0.001ms !important; +} + +body.reduced-motion button:hover, +body.reduced-motion a:hover, +body.reduced-motion [role='button']:hover { + transform: none !important; + scale: 1 !important; +} + +body.reduced-motion div[class*='Sidebar_SidebarItem']:hover, +body.reduced-motion div[class*='Sidebar_SidebarItem']:hover button, +body.reduced-motion div[class*='Sidebar_SidebarItem']:hover img { + transform: none !important; + scale: 1 !important; + translate: none !important; + margin: 0 !important; + padding: 0 !important; +} + +body.reduced-motion div[class*='Sidebar_SidebarStack']:hover { + width: revert !important; + translate: none !important; + transform: none !important; +} + +body.reduced-motion div[class*='layout_MessageBase'] { + animation: none !important; + transition: none !important; + transform: none !important; +} + +body.reduced-motion div[class*='RoomTimeline_messageList'], +body.reduced-motion div[class*='RoomTimeline_messageList'] > * { + scroll-behavior: auto !important; +} From ab3aafa48f03c30e121eb21e15cb9ed063fa6e46 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 02:07:58 -0600 Subject: [PATCH 090/124] improve reduced motion --- src/index.css | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/index.css b/src/index.css index b0edbc4f..f2f2547b 100755 --- a/src/index.css +++ b/src/index.css @@ -221,3 +221,14 @@ body.reduced-motion div[class*='RoomTimeline_messageList'], body.reduced-motion div[class*='RoomTimeline_messageList'] > * { scroll-behavior: auto !important; } + +body.reduced-motion span[class*='layout_AvatarBase']:hover, +body.reduced-motion span[class*='layout_AvatarBase']:hover *, +body.reduced-motion button[class*='styles_MessageAvatar']:hover, +body.reduced-motion button[class*='styles_MessageAvatar']:hover * { + transform: none !important; + scale: 1 !important; + translate: none !important; + animation: none !important; + margin: 0 !important; +} From 5e39237e16448280ee6488177fa2d71b2971249f Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 02:56:21 -0600 Subject: [PATCH 091/124] added settings for disabling autoplay of gifs (& banners), stickers, and emojis. --- .changeset/y_autoplay.md | 5 ++ src/app/components/ClientSideHoverFreeze.tsx | 76 ++++++++++++++++++ src/app/components/RenderMessageContent.tsx | 23 +++++- src/app/components/user-profile/UserHero.tsx | 40 ++++++++-- .../user-profile/UserRoomProfile.tsx | 3 + src/app/features/room/RoomTimeline.tsx | 27 ++++++- .../features/settings/cosmetics/Themes.tsx | 26 ++++++ src/app/plugins/react-custom-html-parser.tsx | 80 ++++++++++++------- src/app/state/settings.ts | 6 ++ 9 files changed, 248 insertions(+), 38 deletions(-) create mode 100644 .changeset/y_autoplay.md create mode 100644 src/app/components/ClientSideHoverFreeze.tsx diff --git a/.changeset/y_autoplay.md b/.changeset/y_autoplay.md new file mode 100644 index 00000000..7d24ecbe --- /dev/null +++ b/.changeset/y_autoplay.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Added settings for disabling autoplay of gifs (& banners), stickers, and emojis. diff --git a/src/app/components/ClientSideHoverFreeze.tsx b/src/app/components/ClientSideHoverFreeze.tsx new file mode 100644 index 00000000..5a516d13 --- /dev/null +++ b/src/app/components/ClientSideHoverFreeze.tsx @@ -0,0 +1,76 @@ +import { useEffect, useRef, useState } from 'react'; + +export function ClientSideHoverFreeze({ + children, + src, + className, +}: { + children: React.ReactNode; + src: string; + className?: string; +}) { + const [isHovered, setIsHovered] = useState(false); + const canvasRef = useRef(null); + const [isCanvasReady, setIsCanvasReady] = useState(false); + useEffect(() => { + let isMounted = true; + const img = new window.Image(); + img.crossOrigin = 'anonymous'; + img.src = src; + + img.onload = () => { + if (isMounted && canvasRef.current) { + canvasRef.current.width = img.naturalWidth || img.width; + canvasRef.current.height = img.naturalHeight || img.height; + const ctx = canvasRef.current.getContext('2d'); + ctx?.drawImage(img, 0, 0); + setIsCanvasReady(true); + } + }; + return () => { + isMounted = false; + }; + }, [src]); + + return ( +
setIsHovered(true)} + onMouseLeave={() => setIsHovered(false)} + onFocus={() => setIsHovered(true)} + onBlur={() => setIsHovered(false)} + className={className} + style={{ + position: 'relative', + display: 'inline-flex', + cursor: 'pointer', + verticalAlign: 'middle', + overflow: 'hidden', + borderRadius: 'inherit', + }} + > +
+ {children} +
+ +
+ ); +} diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 8ba8f6dc..6811b116 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -1,6 +1,8 @@ import { memo, useMemo, useCallback } from 'react'; import { MsgType } from '$types/matrix-sdk'; import { testMatrixTo } from '$plugins/matrix-to'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { HTMLReactParserOptions } from 'html-react-parser'; import { Opts } from 'linkifyjs'; import { config } from 'folds'; @@ -30,6 +32,7 @@ import { Image, MediaControl, Video } from './media'; import { ImageViewer } from './image-viewer'; import { PdfViewer } from './Pdf-viewer'; import { TextViewer } from './text-viewer'; +import { ClientSideHoverFreeze } from './ClientSideHoverFreeze'; type RenderMessageContentProps = { displayName: string; @@ -70,6 +73,8 @@ function RenderMessageContentInternal({ }: RenderMessageContentProps) { const content = useMemo(() => getContent(), [getContent]); + const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); + const renderBody = useCallback( (props: any) => ( } + renderImage={(p) => { + if (isGif && !autoplayGifs && p.src) { + return ( + + + + ); + } + return ; + }} renderViewer={(p) => } /> )} diff --git a/src/app/components/user-profile/UserHero.tsx b/src/app/components/user-profile/UserHero.tsx index dfc62f24..0acdc361 100644 --- a/src/app/components/user-profile/UserHero.tsx +++ b/src/app/components/user-profile/UserHero.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useMemo, useState } from 'react'; import { Avatar, Box, @@ -27,6 +27,7 @@ import { useBlobCache } from '$hooks/useBlobCache'; import { ImageViewer } from '$components/image-viewer'; import { AvatarPresence, PresenceBadge } from '$components/presence'; import { UserAvatar } from '$components/user-avatar'; +import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import * as css from './styles.css'; type UserHeroProps = { @@ -34,8 +35,9 @@ type UserHeroProps = { avatarUrl?: string; bannerUrl?: string; presence?: UserPresence; + autoplayGifs?: boolean; }; -export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroProps) { +export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs }: UserHeroProps) { const [viewAvatar, setViewAvatar] = useState(); const [isFullStatus, setIsFullStatus] = useState(false); @@ -45,6 +47,25 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroPro const coverUrl = cachedBannerUrl || cachedAvatarUrl; const isFallbackCover = !cachedBannerUrl && !!cachedAvatarUrl; + const isAnimated = useMemo(() => { + if (!coverUrl) return false; + const url = coverUrl.toLowerCase(); + const isStatic = url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.png'); + + return !isStatic || url.includes('gif') || url.includes('webp'); + }, [coverUrl]); + + const bannerClasses = classNames(css.UserHeroCover, isFallbackCover && css.UserHeroCoverFallback); + + const renderCoverImage = () => ( + {`${userId} + ); + const status = presence?.status; const isExpandable = (status?.length ?? 0) > 70; @@ -57,12 +78,15 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroPro }} > {coverUrl && ( - {`${userId} + <> + {isAnimated && !autoplayGifs ? ( + + {renderCoverImage()} + + ) : ( + renderCoverImage() + )} + )}
diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index 3878bba5..8a108f21 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -259,6 +259,8 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps const ignoredUsers = useIgnoredUsers(); const ignored = ignoredUsers.includes(userId); + const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); + const room = useRoom(); const powerLevels = usePowerLevels(room); const creators = useRoomCreators(room); @@ -348,6 +350,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps avatarUrl={avatarUrl} bannerUrl={bannerHttpUrl ?? undefined} presence={presence && presence.lastActiveTs !== 0 ? presence : undefined} + autoplayGifs={autoplayGifs} /> diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 7cb5a9e1..f0719bc0 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -129,6 +129,7 @@ import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { profilesCacheAtom } from '$state/userRoomProfile'; +import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import * as css from './RoomTimeline.css'; import { EncryptedContent, Event, Message, Reactions } from './message'; @@ -576,6 +577,9 @@ export function RoomTimeline({ const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); + const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); + const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); + const ignoredUsersList = useIgnoredUsers(); const ignoredUsersSet = useMemo(() => new Set(ignoredUsersList), [ignoredUsersList]); const nicknames = useAtomValue(nicknamesAtom); @@ -658,6 +662,7 @@ export function RoomTimeline({ handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, nicknames, + autoplayEmojis, }), [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication, nicknames] ); @@ -1479,7 +1484,16 @@ export function RoomTimeline({ } + renderImage={(p) => { + if (!autoplayStickers && p.src) { + return ( + + + + ); + } + return ; + }} renderViewer={(p) => } /> )} @@ -1599,7 +1613,16 @@ export function RoomTimeline({ } + renderImage={(p) => { + if (!autoplayStickers && p.src) { + return ( + + + + ); + } + return ; + }} renderViewer={(p) => } /> )} diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 043b0f0f..baf73762 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -247,6 +247,9 @@ function ThemeSettings() { const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); const [underlineLinks, setUnderlineLinks] = useSetting(settingsAtom, 'underlineLinks'); const [reducedMotion, setReducedMotion] = useSetting(settingsAtom, 'reducedMotion'); + const [autoplayGifs, setAutoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); + const [autoplayStickers, setAutoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); + const [autoplayEmojis, setAutoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); return ( @@ -313,6 +316,29 @@ function ThemeSettings() { after={} /> + + } + /> + + + + } + /> + + + } + /> + ); } diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index dc3bf484..f7bb1081 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -43,6 +43,7 @@ import { testMatrixTo, } from './matrix-to'; import { getHexcodeForEmoji, getShortcodeFor } from './emoji'; +import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; const ReactPrism = lazy(() => import('./react-prism/ReactPrism')); @@ -341,6 +342,7 @@ export const getReactCustomHtmlParser = ( handleMentionClick?: ReactEventHandler; useAuthentication?: boolean; nicknames?: Nicknames; + autoplayEmojis?: boolean; } ): HTMLReactParserOptions => { const opts: HTMLReactParserOptions = { @@ -547,25 +549,39 @@ export const getReactCustomHtmlParser = ( const siblingCount = domNode.parent?.children.length ?? 0; + // seperate style for bundled emojis // seperate style for bundled emojis if (siblingCount > 5) { return ( - - {props.alt || props.title ? `:${props.alt || props.title}:` : '?'} - - } - /> + {!params.autoplayEmojis ? ( + + + {props.alt || props.title || '?'} + + } + /> + + ) : ( + + {props.alt || props.title || '?'} + + } + /> + )} ); @@ -575,19 +591,29 @@ export const getReactCustomHtmlParser = ( return ( - - {props.alt || props.title ? `:${props.alt || props.title}:` : '?'} - - } - /> + {!params.autoplayEmojis ? ( + + + {props.alt || props.title || '?'} + + } + /> + + ) : ( + {props.alt || props.title || '?'} + } + /> + )} ); diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 88f9c908..6de1ad16 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -82,6 +82,9 @@ export interface Settings { emojiSuggestThreshold: number; underlineLinks: boolean; reducedMotion: boolean; + autoplayGifs: boolean; + autoplayStickers: boolean; + autoplayEmojis: boolean; // furry stuff renderAnimals: boolean; @@ -153,6 +156,9 @@ const defaultSettings: Settings = { emojiSuggestThreshold: 2, underlineLinks: false, reducedMotion: false, + autoplayGifs: true, + autoplayStickers: true, + autoplayEmojis: true, // furry stuff renderAnimals: true, From c90794c5a53d0147f7f544c58e375ae7fd1a335c Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 02:58:56 -0600 Subject: [PATCH 092/124] lint fixes --- src/app/features/room/RoomTimeline.tsx | 11 ++++++++++- src/app/plugins/react-custom-html-parser.tsx | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index f0719bc0..d07c62a3 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -664,7 +664,16 @@ export function RoomTimeline({ nicknames, autoplayEmojis, }), - [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication, nicknames] + [ + mx, + room, + linkifyOpts, + autoplayEmojis, + spoilerClickHandler, + mentionClickHandler, + useAuthentication, + nicknames, + ] ); const parseMemberEvent = useMemberEventParser(); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index f7bb1081..12a86926 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -36,6 +36,7 @@ import { findAndReplace } from '$utils/findAndReplace'; import { onEnterOrSpace } from '$utils/keyboard'; import { copyToClipboard } from '$utils/dom'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import { parseMatrixToRoom, parseMatrixToRoomEvent, @@ -43,7 +44,6 @@ import { testMatrixTo, } from './matrix-to'; import { getHexcodeForEmoji, getShortcodeFor } from './emoji'; -import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; const ReactPrism = lazy(() => import('./react-prism/ReactPrism')); From 24b901461c00893ba07a785568374449ed4479f3 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 03:40:44 -0600 Subject: [PATCH 093/124] Create 000_merge_upstream.md --- .changeset/000_merge_upstream.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/000_merge_upstream.md diff --git a/.changeset/000_merge_upstream.md b/.changeset/000_merge_upstream.md new file mode 100644 index 00000000..d04b7f25 --- /dev/null +++ b/.changeset/000_merge_upstream.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Merge Voice Call updates from upstream. From b7eecceb85aa60abc80b6854cdfa9e05ff2e2db8 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 03:45:11 -0600 Subject: [PATCH 094/124] Update package-lock.json --- package-lock.json | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 401de6d5..e5937fee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12778,7 +12778,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", @@ -12803,10 +12803,9 @@ } }, "node_modules/matrix-widget-api": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.17.0.tgz", - "integrity": "sha512-5FHoo3iEP3Bdlv5jsYPWOqj+pGdFQNLWnJLiB0V7Ygne7bb+Gsj3ibyFyHWC6BVw+Z+tSW4ljHpO17I9TwStwQ==", - "license": "Apache-2.0", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.13.0.tgz", + "integrity": "sha512-+LrvwkR1izL4h2euX8PDrvG/3PZZDEd6As+lmnR3jAVwbFJtU5iTnwmZGnCca9ddngCvXvAHkcpJBEPyPTZneQ==","license": "Apache-2.0", "dependencies": { "@types/events": "^3.0.0", "events": "^3.2.0" From 5111dd5afde5aa58d381b0820080be8bd1e0f05f Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 03:47:45 -0600 Subject: [PATCH 095/124] fix package.json --- package.json | 2 +- src/app/features/call-status/LiveChip.tsx | 2 +- src/app/features/call-status/MemberGlance.tsx | 2 +- src/app/features/call/CallMemberCard.tsx | 2 +- src/app/features/call/CallView.tsx | 2 +- src/app/features/room-nav/RoomNavItem.tsx | 13 ++++++++----- src/app/features/room-settings/RoomSettings.tsx | 9 ++++++--- src/app/features/room/RoomView.tsx | 2 +- src/app/features/room/RoomViewHeader.tsx | 2 +- src/app/hooks/useRoomMeta.ts | 2 +- src/app/plugins/call/CallWidgetDriver.ts | 5 ++++- 11 files changed, 26 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index bd3fea49..233e6f71 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "knip": "knip", "knope": "knope", "document-change": "knope document-change", - "postinstall": "node scripts/install-knope.js"\ + "postinstall": "node scripts/install-knope.js" }, "keywords": [], "author": "7w1", diff --git a/src/app/features/call-status/LiveChip.tsx b/src/app/features/call-status/LiveChip.tsx index 34167fb6..39ac415d 100644 --- a/src/app/features/call-status/LiveChip.tsx +++ b/src/app/features/call-status/LiveChip.tsx @@ -77,7 +77,7 @@ export function LiveChip({ count, room, members }: LiveChipProps) { getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; const avatarMxc = getMemberAvatarMxc(room, userId); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined) : undefined; return ( diff --git a/src/app/features/call-status/MemberGlance.tsx b/src/app/features/call-status/MemberGlance.tsx index f4991f93..fa231208 100644 --- a/src/app/features/call-status/MemberGlance.tsx +++ b/src/app/features/call-status/MemberGlance.tsx @@ -32,7 +32,7 @@ export function MemberGlance({ room, members, max = 6 }: MemberGlanceProps) { const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; const avatarMxc = getMemberAvatarMxc(room, userId); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined) : undefined; return ( diff --git a/src/app/features/call/CallMemberCard.tsx b/src/app/features/call/CallMemberCard.tsx index f96b9a06..3f409ce0 100644 --- a/src/app/features/call/CallMemberCard.tsx +++ b/src/app/features/call/CallMemberCard.tsx @@ -34,7 +34,7 @@ export function CallMemberCard({ member }: CallMemberCardProps) { const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; const avatarMxc = getMemberAvatarMxc(room, userId); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined) : undefined; const audioOnly = diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx index c3500fc6..3165fc14 100644 --- a/src/app/features/call/CallView.tsx +++ b/src/app/features/call/CallView.tsx @@ -102,4 +102,4 @@ export function CallView() { )} ); -} \ No newline at end of file +} diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 716d353d..d36698d9 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -271,7 +271,7 @@ export function RoomNavItem({ const { hoverProps } = useHover({ onHoverChange: setHover }); const { focusWithinProps } = useFocusWithin({ onFocusWithinChange: setHover }); const [menuAnchor, setMenuAnchor] = useState(); - + const unread = useRoomUnread(room.roomId, roomToUnreadAtom); const hasRoomUnread = useRoomHasUnread(room); const typingMember = useRoomTypingMember(room.roomId).filter( @@ -318,7 +318,10 @@ export function RoomNavItem({ if (room.isCallRoom()) { if (!isMobile) { if (!isActiveCall && !callEmbed) { - startCall(room, new CallControlState(callPref.microphone, callPref.video, callPref.sound)); + startCall( + room, + new CallControlState(callPref.microphone, callPref.video, callPref.sound) + ); } else { navigateRoom(room.roomId); } @@ -343,7 +346,7 @@ export function RoomNavItem({ if (unread) { unreadCount = unread.highlight > 0 ? unread.highlight : unread.total; } - + const ariaLabel = [ roomName, room.isCallRoom() @@ -520,7 +523,7 @@ export function RoomNavItem({ )} - + {room.isCallRoom() && ( {callMembers.map((callMembership) => ( @@ -534,4 +537,4 @@ export function RoomNavItem({ )} ); -} \ No newline at end of file +} diff --git a/src/app/features/room-settings/RoomSettings.tsx b/src/app/features/room-settings/RoomSettings.tsx index eae5de27..8707cefa 100644 --- a/src/app/features/room-settings/RoomSettings.tsx +++ b/src/app/features/room-settings/RoomSettings.tsx @@ -147,12 +147,15 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) { variant="Background" radii="400" aria-pressed={activePage === item.page} - before={} + before={ + + } onClick={() => setActivePage(item.page)} > ); -} \ No newline at end of file +} diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 097d517d..789171a7 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -193,4 +193,4 @@ export function RoomView({ eventId }: { eventId?: string }) { )} ); -} \ No newline at end of file +} diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index 52a696f0..b88acdbf 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -729,4 +729,4 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { ); -} \ No newline at end of file +} diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index edbc5805..eee1385f 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -62,4 +62,4 @@ export const useRoomJoinRule = (room: Room): RoomJoinRulesEventContent | undefin const mEvent = useStateEvent(room, StateEvent.RoomJoinRules); const joinRuleContent = mEvent?.getContent(); return joinRuleContent; -}; \ No newline at end of file +}; diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index babe90ef..61b0e4f0 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -32,7 +32,10 @@ export class CallWidgetDriver extends WidgetDriver { private readonly mx: MatrixClient; - public constructor(mx: MatrixClient, private inRoomId: string) { + public constructor( + mx: MatrixClient, + private inRoomId: string + ) { super(); this.mx = mx; From c6bb4915bc188a96ab5861ccfaf8c78c986c1907 Mon Sep 17 00:00:00 2001 From: Ajay Bura <32841439+ajbura@users.noreply.github.com> Date: Sat, 7 Mar 2026 20:47:45 +1100 Subject: [PATCH 096/124] Downgrade matrix-widget-api from 1.17.0 to 1.13.0 (#2736) Some user was having Disconnection Error --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4648a9fd..ceb7e8c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "linkify-react": "4.3.2", "linkifyjs": "4.3.2", "matrix-js-sdk": "38.2.0", - "matrix-widget-api": "1.17.0", + "matrix-widget-api": "1.13.0", "millify": "6.1.0", "pdfjs-dist": "4.2.67", "prismjs": "1.30.0", @@ -8674,9 +8674,9 @@ } }, "node_modules/matrix-widget-api": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.17.0.tgz", - "integrity": "sha512-5FHoo3iEP3Bdlv5jsYPWOqj+pGdFQNLWnJLiB0V7Ygne7bb+Gsj3ibyFyHWC6BVw+Z+tSW4ljHpO17I9TwStwQ==", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.13.0.tgz", + "integrity": "sha512-+LrvwkR1izL4h2euX8PDrvG/3PZZDEd6As+lmnR3jAVwbFJtU5iTnwmZGnCca9ddngCvXvAHkcpJBEPyPTZneQ==", "license": "Apache-2.0", "dependencies": { "@types/events": "^3.0.0", diff --git a/package.json b/package.json index 4eeead2d..e6204a21 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "linkify-react": "4.3.2", "linkifyjs": "4.3.2", "matrix-js-sdk": "38.2.0", - "matrix-widget-api": "1.17.0", + "matrix-widget-api": "1.13.0", "millify": "6.1.0", "pdfjs-dist": "4.2.67", "prismjs": "1.30.0", From 48da99d30eeebb5996a7db9fb3ca9705740c6af8 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 7 Mar 2026 03:51:44 -0600 Subject: [PATCH 097/124] mergeeee --- src/app/features/room/RoomTimeline.tsx | 3 ++- src/app/pages/client/ClientInitStorageAtom.tsx | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 5b8ccf41..74f60593 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1849,7 +1849,8 @@ export function RoomTimeline({ highlight={highlighted} messageSpacing={messageSpacing} canDelete={canRedact || mEvent.getSender() === mx.getUserId()} - hideReadReceipts={hideActivity} + hideReadReceipts={hideReads} + onReplyClick={handleReplyClick} showDeveloperTools={showDeveloperTools} > Date: Sat, 7 Mar 2026 03:55:01 -0600 Subject: [PATCH 098/124] remove unused files --- src/app/features/call/CallView.css.ts | 37 --- src/app/features/call/CallViewUser.tsx | 73 ----- src/app/hooks/useCallMemberships.ts | 34 --- .../client/call/PersistentCallContainer.tsx | 266 ------------------ 4 files changed, 410 deletions(-) delete mode 100644 src/app/features/call/CallView.css.ts delete mode 100644 src/app/features/call/CallViewUser.tsx delete mode 100644 src/app/hooks/useCallMemberships.ts delete mode 100644 src/app/pages/client/call/PersistentCallContainer.tsx diff --git a/src/app/features/call/CallView.css.ts b/src/app/features/call/CallView.css.ts deleted file mode 100644 index 5a976829..00000000 --- a/src/app/features/call/CallView.css.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { style } from '@vanilla-extract/css'; -import { DefaultReset, config } from 'folds'; -import { ContainerColor } from '$styles/ContainerColor.css'; - -export const CallViewUserGrid = style({ - display: 'flex', - flexWrap: 'wrap', - justifyContent: 'center', - alignItems: 'center', - marginInline: '20px', - gap: config.space.S400, -}); - -export const CallViewUser = style([ - DefaultReset, - ContainerColor({ variant: 'SurfaceVariant' }), - { - height: '90px', - width: '150px', - borderRadius: config.radii.R500, - }, -]); - -export const UserLink = style({ - color: 'inherit', - minWidth: 0, - cursor: 'pointer', - flexGrow: 0, - transition: 'all ease-out 200ms', - ':hover': { - transform: 'translateY(-3px)', - textDecoration: 'unset', - }, - ':focus': { - outline: 'none', - }, -}); diff --git a/src/app/features/call/CallViewUser.tsx b/src/app/features/call/CallViewUser.tsx deleted file mode 100644 index 2de556b5..00000000 --- a/src/app/features/call/CallViewUser.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import { as, Avatar, Box, Icon, Icons, Text } from 'folds'; -import { MouseEventHandler } from 'react'; -import classNames from 'classnames'; -import { Room, CallMembership } from '$types/matrix-sdk'; -import { UserAvatar } from '$components/user-avatar'; -import { useMatrixClient } from '$hooks/useMatrixClient'; -import { getMxIdLocalPart } from '$utils/matrix'; -import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room'; -import { useAtomValue } from 'jotai'; -import { nicknamesAtom } from '$state/nicknames'; -import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; -import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; -import { useSpaceOptionally } from '$hooks/useSpace'; -import * as css from './CallView.css'; - -type CallViewUserProps = { - room: Room; - callMembership: CallMembership; -}; - -export const UserProfileButton = as<'button'>( - ({ as: AsUserProfileButton = 'button', className, ...props }, ref) => ( - - ) -); - -export const CallViewUserBase = as<'div'>(({ className, ...props }, ref) => ( - -)); - -export function CallViewUser({ room, callMembership }: CallViewUserProps) { - const mx = useMatrixClient(); - const useAuthentication = useMediaAuthentication(); - const openProfile = useOpenUserRoomProfile(); - const space = useSpaceOptionally(); - const userId = callMembership.sender ?? ''; - const avatarMxcUrl = getMemberAvatarMxc(room, userId); - const avatarUrl = avatarMxcUrl - ? mx.mxcUrlToHttp(avatarMxcUrl, 32, 32, 'crop', undefined, false, useAuthentication) - : undefined; - const nicknames = useAtomValue(nicknamesAtom); - const getName = getMemberDisplayName(room, userId, nicknames) ?? getMxIdLocalPart(userId); - - const handleUserClick: MouseEventHandler = (evt) => { - openProfile(room.roomId, space?.roomId, userId, evt.currentTarget.getBoundingClientRect()); - }; - - return ( - - - - - } - /> - - - {getName} - - - - - ); -} diff --git a/src/app/hooks/useCallMemberships.ts b/src/app/hooks/useCallMemberships.ts deleted file mode 100644 index 9d1cd088..00000000 --- a/src/app/hooks/useCallMemberships.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - MatrixClient, - MatrixRTCSession, - MatrixRTCSessionEvent, - CallMembership, -} from '$types/matrix-sdk'; -import { useEffect, useState } from 'react'; - -export const useCallMembers = (mx: MatrixClient, roomId: string): CallMembership[] => { - const [memberships, setMemberships] = useState([]); - const room = mx.getRoom(roomId); - useEffect(() => { - if (!room) { - setMemberships([]); - return undefined; - } - - const mxr = mx.matrixRTC.getRoomSession(room); - - const updateMemberships = () => { - if (!room.isCallRoom()) return; - setMemberships(MatrixRTCSession.callMembershipsForRoom(room)); - }; - - updateMemberships(); - - mxr.on(MatrixRTCSessionEvent.MembershipsChanged, updateMemberships); - return () => { - mxr.removeListener(MatrixRTCSessionEvent.MembershipsChanged, updateMemberships); - }; - }, [mx, room, roomId]); - - return memberships; -}; diff --git a/src/app/pages/client/call/PersistentCallContainer.tsx b/src/app/pages/client/call/PersistentCallContainer.tsx deleted file mode 100644 index f6548bc7..00000000 --- a/src/app/pages/client/call/PersistentCallContainer.tsx +++ /dev/null @@ -1,266 +0,0 @@ -import { - createContext, - MutableRefObject, - ReactNode, - useCallback, - useEffect, - useMemo, - useRef, -} from 'react'; -import { ClientWidgetApi } from 'matrix-widget-api'; -import { MatrixRTCSession } from 'matrix-js-sdk/lib/matrixrtc/MatrixRTCSession'; -import { Box } from 'folds'; -import { - createVirtualWidget, - SmallWidget, - getWidgetData, - getWidgetUrl, - getCallIntentParams, -} from '$features/call/SmallWidget'; -import { useMatrixClient } from '$hooks/useMatrixClient'; -import { useClientConfig } from '$hooks/useClientConfig'; -import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; -import { ThemeKind, useTheme } from '$hooks/useTheme'; -import { useCallState } from './CallProvider'; - -interface PersistentCallContainerProps { - children: ReactNode; -} - -export const CallRefContext = createContext | null>( - null -); - -export function PersistentCallContainer({ children }: PersistentCallContainerProps) { - const callIframeRef = useRef(null); - const callWidgetApiRef = useRef(null); - const callSmallWidgetRef = useRef(null); - // After any lobby join, reload EC with join_existing for proper in-call view. - const hasReloadedAfterLobbyRef = useRef(false); - const postLobbyIntentRef = useRef<'join_existing' | null>(null); - - const { - activeCallRoomId, - viewedCallRoomId, - isChatOpen, - isActiveCallReady, - registerActiveClientWidgetApi, - activeClientWidget, - resetActiveCallReady, - hangUp, - } = useCallState(); - const mx = useMatrixClient(); - const clientConfig = useClientConfig(); - const screenSize = useScreenSizeContext(); - const theme = useTheme(); - const isMobile = screenSize === ScreenSize.Mobile; - - /* eslint-disable no-param-reassign */ - - const setupWidget = useCallback( - ( - widgetApiRef: MutableRefObject, - smallWidgetRef: MutableRefObject, - iframeRef: MutableRefObject, - skipLobby: boolean, - themeKind: ThemeKind | null, - intentOverride?: 'join_existing' - ) => { - if (mx?.getUserId()) { - if (activeCallRoomId && !isActiveCallReady) { - const roomIdToSet = activeCallRoomId; - const room = mx.getRoom(roomIdToSet); - const { intent: intentParam, callIntentParam } = getCallIntentParams(room); - const effectiveIntent = intentOverride ?? intentParam; - - const widgetId = `element-call-${roomIdToSet}-${Date.now()}`; - const newUrl = getWidgetUrl( - mx, - roomIdToSet, - clientConfig.elementCallUrl ?? '', - widgetId, - { - skipLobby: (intentOverride === 'join_existing' ? true : skipLobby).toString(), - returnToLobby: 'true', - perParticipantE2EE: 'true', - theme: themeKind, - intent: effectiveIntent, - callIntent: callIntentParam, - } - ); - - if ( - callSmallWidgetRef.current?.roomId && - activeClientWidget?.roomId && - activeClientWidget.roomId === callSmallWidgetRef.current?.roomId - ) { - return; - } - - if ( - iframeRef.current && - (!iframeRef.current.src || iframeRef.current.src !== newUrl.toString()) - ) { - iframeRef.current.src = newUrl.toString(); - } - - const iframeElement = iframeRef.current; - if (!iframeElement) { - return; - } - - const userId = mx.getUserId() ?? ''; - const app = createVirtualWidget( - mx, - widgetId, - userId, - 'Element Call', - 'm.call', - newUrl, - false, - getWidgetData( - mx, - roomIdToSet, - {}, - { skipLobby: true, intent: effectiveIntent, callIntent: callIntentParam } - ), - roomIdToSet - ); - - const smallWidget = new SmallWidget(app); - smallWidgetRef.current = smallWidget; - - const widgetApiInstance = smallWidget.startMessaging(iframeElement); - widgetApiRef.current = widgetApiInstance; - registerActiveClientWidgetApi( - roomIdToSet, - widgetApiRef.current, - smallWidget, - iframeElement - ); - } - } - }, - [ - mx, - activeCallRoomId, - isActiveCallReady, - clientConfig.elementCallUrl, - activeClientWidget, - registerActiveClientWidgetApi, - ] - ); - - // After any lobby join, poll until EC's call member state event has propagated to the room, - // then reload EC with intent=join_existing + skipLobby=true so it auto-joins the existing - // session and shows the full in-call grid. Hangs up if the session never appears. - // Applies to all room types: DM/group (start_call) and voice rooms (join_existing) both - // hit the same timing issue where the in-call grid is not shown after the first join. - useEffect(() => { - if (!activeCallRoomId) { - hasReloadedAfterLobbyRef.current = false; - return undefined; - } - if (isActiveCallReady && !hasReloadedAfterLobbyRef.current) { - const room = mx?.getRoom(activeCallRoomId); - if (room) { - hasReloadedAfterLobbyRef.current = true; - const POLL_INTERVAL_MS = 200; - const TIMEOUT_MS = 10000; - const startTime = Date.now(); - const pollTimer = setInterval(() => { - if (MatrixRTCSession.callMembershipsForRoom(room).length > 0) { - clearInterval(pollTimer); - callSmallWidgetRef.current?.stopMessaging(); - callWidgetApiRef.current = null; - callSmallWidgetRef.current = null; - registerActiveClientWidgetApi(activeCallRoomId, null, null, null); - postLobbyIntentRef.current = 'join_existing'; - resetActiveCallReady(); - } else if (Date.now() - startTime >= TIMEOUT_MS) { - clearInterval(pollTimer); - hangUp(); - } - }, POLL_INTERVAL_MS); - return () => clearInterval(pollTimer); - } - } - return undefined; - }, [ - isActiveCallReady, - activeCallRoomId, - mx, - registerActiveClientWidgetApi, - resetActiveCallReady, - hangUp, - ]); - - useEffect(() => { - if (activeCallRoomId) { - const intentOverride = postLobbyIntentRef.current ?? undefined; - postLobbyIntentRef.current = null; - setupWidget( - callWidgetApiRef, - callSmallWidgetRef, - callIframeRef, - true, - theme.kind, - intentOverride - ); - } - }, [ - theme, - setupWidget, - callWidgetApiRef, - callSmallWidgetRef, - callIframeRef, - registerActiveClientWidgetApi, - activeCallRoomId, - viewedCallRoomId, - isActiveCallReady, - ]); - - const memoizedIframeRef = useMemo(() => callIframeRef, [callIframeRef]); - - return ( - - - - -