From dd254457a10449d9130a22a1bd9a07c4fb20acee Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 26 Jul 2026 00:09:58 +0200 Subject: [PATCH 1/2] refactor: share cross-cutting hooks and fix the menu, thread and sheet regressions --- .changeset/fix-menu-and-thread-regressions.md | 5 + playwright.config.ts | 3 + src/app/components/AccountDataEditor.tsx | 19 +- src/app/components/AsyncButton.tsx | 41 + src/app/components/AsyncError.tsx | 28 + src/app/components/CallEmbedProvider.tsx | 2 +- src/app/components/DeviceVerification.tsx | 19 +- .../components/DeviceVerificationSetup.tsx | 18 +- src/app/components/LogoutDialog.tsx | 19 +- src/app/components/ManualVerification.tsx | 7 +- src/app/components/Modal500.test.tsx | 18 - src/app/components/Modal500.tsx | 22 - src/app/components/ResponsiveMenu.css.ts | 39 + src/app/components/ResponsiveMenu.test.tsx | 241 +++ src/app/components/ResponsiveMenu.tsx | 37 +- src/app/components/RoomSummaryLoader.tsx | 2 +- src/app/components/SecretStorage.tsx | 34 +- .../avatar-upload-tile/AvatarUploadTile.tsx | 121 ++ .../DirectInvitePrompt.tsx | 12 +- src/app/components/editor/Editor.tsx | 2 +- .../autocomplete/RoomMentionAutocomplete.tsx | 2 +- .../autocomplete/UserMentionAutocomplete.tsx | 2 +- src/app/components/editor/output.ts | 2 +- src/app/components/editor/utils.ts | 2 +- .../components/event-history/EventHistory.tsx | 4 +- .../components/event-readers/EventReaders.tsx | 4 +- .../components/image-editor/ImageEditor.tsx | 2 +- .../image-pack-view/ImagePackContent.tsx | 2 +- .../components/image-viewer/ImageViewer.tsx | 3 +- .../invite-user-prompt/InviteUserPrompt.tsx | 23 +- .../knock-room-prompt/KnockRoomPrompt.tsx | 22 +- .../leave-space-prompt/LeaveSpacePrompt.tsx | 40 +- src/app/components/member-tile/MemberTile.tsx | 2 +- .../message-preview/MessagePreview.tsx | 3 +- src/app/components/message/FileHeader.tsx | 2 +- .../components/message/MsgTypeRenderers.tsx | 2 +- src/app/components/message/PollEvent.tsx | 16 +- src/app/components/message/Reaction.tsx | 2 +- src/app/components/message/Reply.test.tsx | 2 +- src/app/components/message/Reply.tsx | 6 +- .../message/modals/MessageEditHistory.tsx | 2 +- .../message/modals/MessageForward.tsx | 19 +- .../message/modals/MessageSource.tsx | 2 +- src/app/components/message/modals/Options.tsx | 9 +- .../modal-overlay/ModalOverlay.test.tsx | 225 +++ .../components/modal-overlay/ModalOverlay.tsx | 34 +- src/app/components/nav/NavCategoryHeader.tsx | 2 +- src/app/components/nav/NavMenu.tsx | 50 + .../components/page/PageNavHeaderWithMenu.tsx | 69 + src/app/components/page/PageNavShell.tsx | 57 + .../components/page/PersistentRoomHost.tsx | 2 +- src/app/components/page/SidebarPanel.tsx | 25 +- src/app/components/page/index.tsx | 1 + src/app/components/room-card/RoomCard.tsx | 3 +- src/app/components/room-intro/RoomIntro.tsx | 5 +- .../components/setting-tile/SettingToggle.tsx | 48 + src/app/components/setting-tile/index.ts | 1 + src/app/components/sidebar/SidebarTab.tsx | 68 + src/app/components/sidebar/index.ts | 1 + .../typing-indicator/TypingIndicator.tsx | 2 +- .../components/url-preview/ClientPreview.tsx | 2 +- src/app/components/user-profile/UserChips.tsx | 2 +- src/app/components/user-profile/UserHero.tsx | 4 +- .../user-profile/UserModeration.tsx | 57 +- .../user-profile/UserRoomProfile.tsx | 2 +- src/app/components/user-profile/styles.css.ts | 6 + src/app/cs-api.ts | 2 - src/app/cs-errorcode.ts | 27 +- src/app/features/add-existing/AddExisting.tsx | 2 +- src/app/features/call-status/CallRoomName.tsx | 2 +- src/app/features/call-status/LiveChip.tsx | 2 +- src/app/features/call-status/MemberGlance.tsx | 2 +- .../features/call-status/MemberSpeaking.tsx | 2 +- src/app/features/call/CallMemberCard.tsx | 2 +- src/app/features/call/CallView.tsx | 2 +- .../call}/IncomingCallModal.css.ts | 0 .../call}/IncomingCallModal.test.tsx | 6 +- .../call}/IncomingCallModal.tsx | 8 +- .../call/callStartCapabilities.test.ts} | 2 +- .../call}/useCallSignaling.ts | 4 +- .../call}/useCallStartCapabilities.ts | 0 .../common-settings/cosmetics/Cosmetics.tsx | 105 +- .../developer-tools/DevelopTools.tsx | 2 +- .../developer-tools/SendRoomEvent.tsx | 20 +- .../developer-tools/StateEventEditor.tsx | 19 +- .../emojis-stickers/RoomPacks.tsx | 19 +- .../general/RoomEncryption.tsx | 20 +- .../general/RoomHistoryVisibility.tsx | 15 +- .../common-settings/general/RoomJoinRules.tsx | 12 +- .../common-settings/general/RoomProfile.tsx | 22 +- .../common-settings/general/RoomPublish.tsx | 18 +- .../common-settings/general/RoomUpgrade.tsx | 12 +- .../common-settings/members/Members.tsx | 2 +- .../permissions/PermissionGroups.tsx | 11 +- src/app/features/create-chat/CreateChat.tsx | 13 +- src/app/features/create-room/CreateRoom.tsx | 13 +- src/app/features/create-space/CreateSpace.tsx | 13 +- src/app/features/lobby/Lobby.tsx | 2 +- src/app/features/lobby/RoomItem.tsx | 2 +- src/app/features/lobby/SpaceItem.tsx | 2 +- src/app/features/lobby/SpaceNavItem.tsx | 2 +- src/app/features/navigate/RoomSearch.tsx | 8 +- src/app/features/room-nav/RoomNavItem.tsx | 218 +-- src/app/features/room-nav/RoomNavUser.tsx | 2 +- .../room-settings/RoomSettings.test.tsx | 230 +++ .../room-settings/RoomSettingsRenderer.tsx | 21 +- .../abbreviations/RoomAbbreviations.tsx | 2 +- src/app/features/room/MembersDrawer.tsx | 2 +- src/app/features/room/RoomInput.tsx | 2 +- src/app/features/room/RoomMenu.tsx | 205 +++ src/app/features/room/RoomTimeline.tsx | 196 +-- src/app/features/room/RoomTombstone.tsx | 26 +- src/app/features/room/RoomViewFollowing.tsx | 4 +- src/app/features/room/RoomViewHeader.tsx | 315 +--- src/app/features/room/RoomViewTyping.tsx | 4 +- src/app/features/room/ThreadBrowser.tsx | 18 +- src/app/features/room/ThreadDrawer.test.ts | 2 +- src/app/features/room/ThreadDrawer.tsx | 398 ++--- src/app/features/room/message/Message.tsx | 67 +- .../features/room/message/MessageEditor.tsx | 3 +- .../room/poll-modals/PollResponses.tsx | 4 +- .../room/reaction-viewer/ReactionViewer.tsx | 4 +- .../room/room-pin-menu/RoomPinMenu.tsx | 2 +- .../features/settings/SettingsRoute.test.tsx | 4 +- .../settings/SettingsShallowRouteRenderer.tsx | 13 +- .../settings/account/AnimalCosmetics.tsx | 19 +- src/app/features/settings/account/Profile.tsx | 115 +- .../settings/account/StatusEditor.tsx | 9 +- .../features/settings/cosmetics/Cosmetics.tsx | 180 +-- .../cosmetics/LanguageSpecificPronouns.tsx | 2 +- .../cosmetics/ThemeCatalogSettings.tsx | 75 +- .../features/settings/cosmetics/Themes.tsx | 194 ++- src/app/features/settings/desktop/Desktop.tsx | 133 +- .../developer-tools/SentrySettings.tsx | 11 +- .../developer-tools/SyncDiagnostics.tsx | 2 +- .../features/settings/devices/LocalBackup.tsx | 23 +- .../settings/experimental/Experimental.tsx | 22 +- .../settings/general/CallSoundSettings.tsx | 88 +- src/app/features/settings/general/General.tsx | 540 +++---- .../settings/notifications/AllMessages.tsx | 42 +- .../DeregisterPushNotifications.tsx | 12 +- .../NotificationModeSwitcher.tsx | 50 + .../notifications/SpecialMessages.tsx | 43 +- .../notifications/SystemNotification.tsx | 241 +-- .../notifications/UnifiedPushNotifications.ts | 3 +- .../settings/settingTileFocusCoverage.test.ts | 133 +- src/app/features/settings/settingsLink.ts | 2 +- .../share-target/ShareTargetFeature.tsx | 21 +- src/app/hooks/commands/moderation.ts | 2 +- src/app/hooks/media/index.ts | 1 - src/app/hooks/media/useMediaPlaybackRate.ts | 6 - .../useTimelineEventRenderer.test.tsx.snap | 12 +- .../hooks/timeline/useProcessedTimeline.ts | 2 +- src/app/hooks/timeline/useTimelineActions.ts | 35 +- .../useTimelineEventRenderer.test.tsx | 204 ++- .../timeline/useTimelineEventRenderer.tsx | 10 +- .../timeline/useTimelineRendererContext.ts | 232 +++ src/app/hooks/timeline/useTimelineSync.ts | 37 +- src/app/hooks/useAsyncCallback.ts | 2 +- src/app/hooks/useGroupDMMembers.ts | 2 +- src/app/hooks/useIgnoredUsers.ts | 2 +- src/app/hooks/useImagePackRooms.ts | 2 +- src/app/hooks/useKeyBackup.ts | 29 +- src/app/hooks/useLocalRoomSummary.ts | 2 +- src/app/hooks/useMatrixEvent.ts | 24 + src/app/hooks/useMemberEventParser.tsx | 2 +- src/app/hooks/useMembership.ts | 21 +- src/app/hooks/useMenuAnchor.test.ts | 295 ++++ src/app/hooks/useMenuAnchor.ts | 41 +- src/app/hooks/useMessageTargetRooms.ts | 28 + src/app/hooks/useNotificationJumper.ts | 2 +- src/app/hooks/usePowerLevels.ts | 2 +- src/app/hooks/useRecentEmoji.ts | 17 +- src/app/hooks/useRoomAbbreviations.ts | 2 +- src/app/hooks/useRoomAliases.ts | 2 +- src/app/hooks/useRoomCreators.ts | 2 +- src/app/hooks/useRoomLatestRenderedEvent.ts | 2 +- src/app/hooks/useRoomMenuActions.ts | 125 ++ src/app/hooks/useRoomNavigate.ts | 2 +- src/app/hooks/useRoomState.ts | 20 +- src/app/hooks/useRoomWidgets.ts | 2 +- src/app/hooks/useSidebarItems.ts | 2 +- src/app/hooks/useSidebarWidth.ts | 29 + src/app/hooks/useSpaceHierarchy.ts | 66 +- src/app/hooks/useStateEvent.ts | 2 +- src/app/pages/auth/login/OidcLogin.tsx | 10 +- .../pages/client/BackgroundNotifications.tsx | 7 +- src/app/pages/client/ClientNonUIFeatures.tsx | 2 +- src/app/pages/client/ClientRoot.tsx | 32 +- src/app/pages/client/SpecVersions.tsx | 19 +- .../client/client-non-ui/notifications.tsx | 10 +- src/app/pages/client/direct/Direct.tsx | 337 ++--- src/app/pages/client/explore/Explore.tsx | 241 ++- src/app/pages/client/home/Home.tsx | 569 +++---- src/app/pages/client/inbox/Bookmarks.tsx | 2 +- src/app/pages/client/inbox/Inbox.tsx | 155 +- src/app/pages/client/inbox/Invites.tsx | 100 +- src/app/pages/client/inbox/Notifications.tsx | 2 +- .../pages/client/sidebar/DirectDMsList.tsx | 2 +- src/app/pages/client/sidebar/DirectTab.tsx | 101 +- src/app/pages/client/sidebar/HomeTab.tsx | 97 +- src/app/pages/client/space/RoomProvider.tsx | 2 +- src/app/pages/client/space/Space.tsx | 375 +++-- src/app/plugins/custom-emoji/utils.ts | 2 +- src/app/plugins/react-custom-html-parser.tsx | 2 +- src/app/plugins/recent-emoji.ts | 2 +- src/app/plugins/via-servers.ts | 2 +- src/app/state/backupRestore.ts | 4 +- src/app/state/bookmarks.ts | 15 +- src/app/state/callEmbed.ts | 2 +- src/app/state/hooks/desktopSettings.ts | 2 +- src/app/state/hooks/roomList.ts | 2 +- src/app/state/list.ts | 3 +- src/app/state/mDirectList.ts | 5 +- src/app/state/modal.ts | 2 +- src/app/state/nativeNotificationReplies.ts | 2 +- src/app/state/room/roomInputDrafts.ts | 17 +- src/app/state/room/roomToOpenThread.ts | 2 +- src/app/state/room/roomToParents.ts | 4 +- src/app/state/room/roomToThreadBrowser.ts | 2 +- src/app/state/room/roomToUnread.ts | 82 +- src/app/state/sessions.ts | 2 +- src/app/state/shareTarget.ts | 2 +- src/app/state/typingMembers.ts | 2 +- src/app/state/upload.ts | 2 +- src/app/styles/Text.css.ts | 2 +- src/app/styles/overrides/TauriDesktop.css | 2 + src/app/theme/cache.ts | 12 +- src/app/theme/catalog.ts | 8 +- src/app/utils/ASCIILexicalTable.ts | 50 - src/app/utils/common.ts | 11 + src/app/utils/key-symbol.ts | 6 - src/app/utils/matrix.ts | 3 +- src/app/utils/mediaUrl.test.ts | 136 ++ src/app/utils/room.reply.test.ts | 6 +- src/app/utils/room.spaceLeave.test.ts | 2 +- src/app/utils/room.ts | 1344 ----------------- src/app/utils/room.unread.test.ts | 2 +- src/app/utils/room/display.ts | 109 ++ src/app/utils/room/hierarchy.ts | 255 ++++ src/app/utils/room/relations.ts | 625 ++++++++ src/app/utils/room/unread.ts | 363 +++++ src/app/utils/roomVisibility.ts | 2 +- src/app/utils/settingsSync.ts | 13 +- src/app/utils/timeline.ts | 2 +- src/client/slidingSync.ts | 25 - src/types/matrix/accountData.ts | 2 - src/types/matrix/common.ts | 7 - src/types/matrix/room.ts | 5 - tests/e2e/touch.spec.ts | 182 +++ 250 files changed, 6678 insertions(+), 5614 deletions(-) create mode 100644 .changeset/fix-menu-and-thread-regressions.md create mode 100644 src/app/components/AsyncButton.tsx create mode 100644 src/app/components/AsyncError.tsx delete mode 100644 src/app/components/Modal500.test.tsx delete mode 100644 src/app/components/Modal500.tsx create mode 100644 src/app/components/ResponsiveMenu.css.ts create mode 100644 src/app/components/ResponsiveMenu.test.tsx create mode 100644 src/app/components/avatar-upload-tile/AvatarUploadTile.tsx create mode 100644 src/app/components/modal-overlay/ModalOverlay.test.tsx create mode 100644 src/app/components/nav/NavMenu.tsx create mode 100644 src/app/components/page/PageNavHeaderWithMenu.tsx create mode 100644 src/app/components/page/PageNavShell.tsx create mode 100644 src/app/components/setting-tile/SettingToggle.tsx create mode 100644 src/app/components/sidebar/SidebarTab.tsx rename src/app/{components => features/call}/IncomingCallModal.css.ts (100%) rename src/app/{components => features/call}/IncomingCallModal.test.tsx (96%) rename src/app/{components => features/call}/IncomingCallModal.tsx (98%) rename src/app/{hooks/useCallStartCapabilities.test.ts => features/call/callStartCapabilities.test.ts} (96%) rename src/app/{hooks => features/call}/useCallSignaling.ts (99%) rename src/app/{hooks => features/call}/useCallStartCapabilities.ts (100%) create mode 100644 src/app/features/room-settings/RoomSettings.test.tsx create mode 100644 src/app/features/room/RoomMenu.tsx create mode 100644 src/app/features/settings/notifications/NotificationModeSwitcher.tsx delete mode 100644 src/app/hooks/media/useMediaPlaybackRate.ts create mode 100644 src/app/hooks/timeline/useTimelineRendererContext.ts create mode 100644 src/app/hooks/useMatrixEvent.ts create mode 100644 src/app/hooks/useMenuAnchor.test.ts create mode 100644 src/app/hooks/useMessageTargetRooms.ts create mode 100644 src/app/hooks/useRoomMenuActions.ts create mode 100644 src/app/hooks/useSidebarWidth.ts create mode 100644 src/app/utils/mediaUrl.test.ts delete mode 100644 src/app/utils/room.ts create mode 100644 src/app/utils/room/display.ts create mode 100644 src/app/utils/room/hierarchy.ts create mode 100644 src/app/utils/room/relations.ts create mode 100644 src/app/utils/room/unread.ts create mode 100644 tests/e2e/touch.spec.ts diff --git a/.changeset/fix-menu-and-thread-regressions.md b/.changeset/fix-menu-and-thread-regressions.md new file mode 100644 index 000000000..3ff9f6c86 --- /dev/null +++ b/.changeset/fix-menu-and-thread-regressions.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix context menus, message long-press, bottom sheet swipe-to-dismiss, thread reactions, thread root replies, and the direct conversation invite prompt. diff --git a/playwright.config.ts b/playwright.config.ts index 756b4bcea..141f02d42 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -27,12 +27,15 @@ export default defineConfig({ reducedMotion: 'reduce', }, projects: [ + // touch.spec.ts drives page.touchscreen, which throws unless hasTouch is set. { name: 'desktop', + testIgnore: /touch\.spec\.ts/, use: { ...devices['Desktop Chrome'], viewport: { width: 1280, height: 800 } }, }, { name: 'mobile', + testIgnore: /touch\.spec\.ts/, use: { ...devices['Desktop Chrome'], viewport: { width: 390, height: 844 } }, }, // hasTouch + isMobile: covers long-press, swipe-to-dismiss and tap targets, diff --git a/src/app/components/AccountDataEditor.tsx b/src/app/components/AccountDataEditor.tsx index 90ed7907c..02c322632 100644 --- a/src/app/components/AccountDataEditor.tsx +++ b/src/app/components/AccountDataEditor.tsx @@ -8,7 +8,6 @@ import { Button, TextArea as TextAreaComponent, color, - Spinner, Chip, Scroll, config, @@ -18,6 +17,8 @@ import type { MatrixError } from '$types/matrix-sdk'; import { Cursor } from '$plugins/text-area'; import { syntaxErrorPosition } from '$utils/dom'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { useAlive } from '$hooks/useAlive'; import { useTextAreaCodeEditor } from '$hooks/useTextAreaCodeEditor'; import { Page, PageHeader } from './page'; @@ -134,16 +135,18 @@ function AccountDataEdit({ required /> - + + ); +} diff --git a/src/app/components/AsyncError.tsx b/src/app/components/AsyncError.tsx new file mode 100644 index 000000000..d71a31c2d --- /dev/null +++ b/src/app/components/AsyncError.tsx @@ -0,0 +1,28 @@ +import { Text, color } from 'folds'; +import type { AsyncState } from '$hooks/useAsyncCallback'; +import { AsyncStatus } from '$hooks/useAsyncCallback'; + +type AsyncErrorProps = { + state: AsyncState; + prefix?: string; + size?: 'T200' | 'T300'; + bold?: boolean; +}; + +export function AsyncError({ state, prefix, size = 'T200', bold }: AsyncErrorProps) { + if (state.status !== AsyncStatus.Error) return null; + + const message = prefix + ? `${prefix}! ${state.error instanceof Error ? state.error.message : String(state.error)}` + : state.error instanceof Error + ? state.error.message + : String(state.error); + + const content = bold ? {message} : message; + + return ( + + {content} + + ); +} diff --git a/src/app/components/CallEmbedProvider.tsx b/src/app/components/CallEmbedProvider.tsx index 0ddd51afd..78b2b5ee0 100644 --- a/src/app/components/CallEmbedProvider.tsx +++ b/src/app/components/CallEmbedProvider.tsx @@ -15,7 +15,7 @@ import { useClientWidgetApiEvent, ElementWidgetActions } from '$plugins/call'; import { callChatAtom, callEmbedAtom, callEmbedStartErrorAtom } from '$state/callEmbed'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; -import { IncomingCallModal } from './IncomingCallModal'; +import { IncomingCallModal } from '$features/call/IncomingCallModal'; import { toCallEmbedStartError } from '$plugins/call/callEmbedError'; function CallUtils({ embed }: { embed: CallEmbed }) { diff --git a/src/app/components/DeviceVerification.tsx b/src/app/components/DeviceVerification.tsx index 0ec686025..852e1397f 100644 --- a/src/app/components/DeviceVerification.tsx +++ b/src/app/components/DeviceVerification.tsx @@ -3,6 +3,7 @@ import { VerificationPhase, VerificationMethod } from '$types/matrix-sdk'; import type { CSSProperties } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { Box, Button, config, Dialog, Header, IconButton, Spinner, Text } from 'folds'; +import { AsyncButton } from '$components/AsyncButton'; import { composerIcon, X } from '$components/icons/phosphor'; import * as Sentry from '@sentry/react'; import { @@ -63,15 +64,16 @@ function VerificationAccept({ onAccept }: VerificationAcceptProps) { return ( Click accept to start the verification process. - + ); } @@ -136,15 +138,16 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) { ))} - + - {setupState.status === AsyncStatus.Error && ( - - {setupState.error ? setupState.error.message : 'Unexpected Error!'} - - )} + + {nextAuthData !== null && uiaAction && ( void; @@ -78,20 +80,17 @@ export const LogoutDialog = forwardRef( /> ))} You’re about to log out. Are you sure? - {logoutState.status === AsyncStatus.Error && ( - - Failed to logout! {logoutState.error.message} - - )} + - + diff --git a/src/app/components/ManualVerification.tsx b/src/app/components/ManualVerification.tsx index e22934e55..5ce90cc6e 100644 --- a/src/app/components/ManualVerification.tsx +++ b/src/app/components/ManualVerification.tsx @@ -9,6 +9,7 @@ import { storePrivateKey } from '$client/secretStorageKeys'; import { stopPropagation } from '$utils/keyboard'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncError } from '$components/AsyncError'; import { SettingTile } from './setting-tile'; import { SecretStorageRecoveryKey, SecretStorageRecoveryPassphrase } from './SecretStorage'; @@ -178,11 +179,7 @@ export function ManualVerificationTile({ onDecodedRecoveryKey={handleDecodedRecoveryKey} /> )} - {verifyState.status === AsyncStatus.Error && ( - - {verifyState.error.message} - - )} + )} diff --git a/src/app/components/Modal500.test.tsx b/src/app/components/Modal500.test.tsx deleted file mode 100644 index 4827d1731..000000000 --- a/src/app/components/Modal500.test.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { render } from '@testing-library/react'; -import { describe, expect, it, vi } from 'vitest'; -import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; -import { Modal500 } from './Modal500'; - -describe('Modal500', () => { - it('does not throw when rendered without tabbable children', () => { - expect(() => - render( - - void>()}> -
Empty modal content
-
-
- ) - ).not.toThrow(); - }); -}); diff --git a/src/app/components/Modal500.tsx b/src/app/components/Modal500.tsx deleted file mode 100644 index a4951efad..000000000 --- a/src/app/components/Modal500.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import type { ReactNode } from 'react'; -import { useRef } from 'react'; -import { Modal } from 'folds'; -import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; - -type Modal500Props = { - requestClose: () => void; - children: ReactNode; -}; - -/** A size-500 modal on desktop that fills the viewport on a phone. */ -export function Modal500({ requestClose, children }: Modal500Props) { - const modalRef = useRef(null); - - return ( - - - {children} - - - ); -} diff --git a/src/app/components/ResponsiveMenu.css.ts b/src/app/components/ResponsiveMenu.css.ts new file mode 100644 index 000000000..072ed868b --- /dev/null +++ b/src/app/components/ResponsiveMenu.css.ts @@ -0,0 +1,39 @@ +import { globalStyle, style } from '@vanilla-extract/css'; +import { config, toRem } from 'folds'; + +export const SheetContent = style({ + width: '100%', + maxHeight: '100%', + display: 'flex', + flexDirection: 'column', +}); + +// Targets the caller's menu element, which may be any component. Reaching it by +// selector rather than cloneElement keeps it working when the caller does not +// forward className. +globalStyle(`${SheetContent} > *:last-child`, { + // !important beats the inline maxWidth/width the callers set for their desktop popout. + width: '100% !important', + maxWidth: 'none !important', + maxHeight: '100%', + position: 'relative', + display: 'flex', + flexDirection: 'column', + borderBottomLeftRadius: '0 !important', + borderBottomRightRadius: '0 !important', + borderBottom: 'none !important', + borderTopLeftRadius: `${toRem(20)} !important`, + borderTopRightRadius: `${toRem(20)} !important`, + paddingBottom: `calc(${config.space.S400} + var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))) !important`, +}); + +globalStyle(`${SheetContent} > *:last-child::after`, { + content: '""', + position: 'absolute', + top: '100%', + left: 0, + right: 0, + height: '300px', + backgroundColor: 'inherit', + border: 'none', +}); diff --git a/src/app/components/ResponsiveMenu.test.tsx b/src/app/components/ResponsiveMenu.test.tsx new file mode 100644 index 000000000..8f1af0b97 --- /dev/null +++ b/src/app/components/ResponsiveMenu.test.tsx @@ -0,0 +1,241 @@ +// oxlint-disable typescript/no-explicit-any +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; +import { ResponsiveMenu } from './ResponsiveMenu'; +import type { RectCords } from 'folds'; + +// ── Mocks ─────────────────────────────────────────────────────────────────── + +vi.mock('folds', () => ({ + Box: ({ children, direction }: any) => ( +
+ {children} +
+ ), + PopOut: ({ content, children, 'aria-expanded': ariaExpanded }: any) => ( +
+
{content}
+
{children}
+
+ ), +})); + +vi.mock('focus-trap-react', () => ({ + default: ({ children, focusTrapOptions }: any) => ( +
+ {children} +
+ ), +})); + +vi.mock('./MobileSwipeDownModal', () => ({ + MobileSwipeDownModal: ({ children, requestClose }: any) => ( +
+ {children(
drag-handle
, { + onTouchStart: vi.fn<() => void>(), + onTouchMove: vi.fn<() => void>(), + onTouchEnd: vi.fn<() => void>(), + })} +
+ ), +})); + +vi.mock('$features/room/message/styles.css', () => ({ + MessageOptionsMenu: 'mock-message-options-menu', +})); + +vi.mock('$utils/keyboard', () => ({ + stopPropagation: () => false, +})); + +afterEach(() => { + cleanup(); +}); + +// ── Helper: render wrapped in a ScreenSizeProvider ────────────────────────── + +function renderMenu(props: { + anchor: RectCords; + menu: React.ReactNode; + children?: React.ReactNode; + returnFocusOnDeactivate?: boolean; +}) { + return render( + + void>()} {...props} /> + + ); +} + +function renderMenuMobile(props: { + anchor: RectCords; + menu: React.ReactNode; + children?: React.ReactNode; +}) { + return render( + + void>()} {...props} /> + + ); +} + +const anchorRect: RectCords = { x: 100, y: 200, width: 80, height: 40 }; + +const SampleMenu = () =>
Menu Items
; + +// ── Tests ─────────────────────────────────────────────────────────────────── + +describe('ResponsiveMenu', () => { + describe('desktop branch (PopOut)', () => { + it('renders the trigger children and the menu inside PopOut when anchor is set', () => { + renderMenu({ + anchor: anchorRect, + menu: , + children: , + }); + + expect(screen.getByTestId('trigger-btn')).toBeInTheDocument(); + expect(screen.getByTestId('popout')).toHaveAttribute('data-aria-expanded', 'true'); + // Menu should be inside the popout content + expect(screen.getByTestId('sample-menu')).toBeInTheDocument(); + }); + + it('hides the menu content when anchor is undefined (gate)', () => { + render( + + void>()} + anchor={undefined} + menu={} + > + + + + ); + + expect(screen.getByTestId('trigger-btn')).toBeInTheDocument(); + // The menu should NOT be in the DOM because anchor is undefined + expect(screen.queryByTestId('sample-menu')).not.toBeInTheDocument(); + }); + + it('wraps the menu in a FocusTrap on desktop', () => { + renderMenu({ + anchor: anchorRect, + menu: , + }); + + expect(screen.getByTestId('focus-trap')).toBeInTheDocument(); + expect(screen.getByTestId('sample-menu')).toBeInTheDocument(); + }); + + it('honours returnFocusOnDeactivate', () => { + render( + + void>()} + anchor={anchorRect} + menu={} + returnFocusOnDeactivate={true} + /> + + ); + + expect(screen.getByTestId('focus-trap')).toHaveAttribute('data-return-focus', 'true'); + }); + + it('passes clickOutsideDeactivates to FocusTrap', () => { + renderMenu({ anchor: anchorRect, menu: }); + + expect(screen.getByTestId('focus-trap')).toHaveAttribute('data-click-outside', 'true'); + }); + }); + + describe('mobile branch (sheet)', () => { + it('renders a MobileSwipeDownModal with drag handle on mobile', () => { + renderMenuMobile({ anchor: anchorRect, menu: }); + + expect(screen.getByTestId('mobile-swipe-down')).toBeInTheDocument(); + expect(screen.getByTestId('drag-handle')).toBeInTheDocument(); + }); + + it('does not render the sheet when anchor is undefined', () => { + render( + + void>()} + anchor={undefined} + menu={} + > + + + + ); + + expect(screen.getByTestId('trigger-btn')).toBeInTheDocument(); + expect(screen.queryByTestId('mobile-swipe-down')).not.toBeInTheDocument(); + }); + + it('wraps the menu in a FocusTrap on mobile', () => { + renderMenuMobile({ anchor: anchorRect, menu: }); + + expect(screen.getByTestId('focus-trap')).toBeInTheDocument(); + expect(screen.getByTestId('sample-menu')).toBeInTheDocument(); + }); + + it('renders menu children inside the mobile sheet', () => { + renderMenuMobile({ anchor: anchorRect, menu: }); + + // The SampleMenu is rendered inside the sheet + expect(screen.getByTestId('sample-menu')).toBeInTheDocument(); + expect(screen.getByTestId('mobile-swipe-down')).toBeInTheDocument(); + expect(screen.getByTestId('drag-handle')).toBeInTheDocument(); + expect(screen.getByTestId('focus-trap')).toBeInTheDocument(); + }); + }); + + describe('escape closes on both branches', () => { + it('passes escapeDeactivates callback to FocusTrap on desktop', () => { + renderMenu({ anchor: anchorRect, menu: }); + + // stopPropagation returns false — it's a function, so the attribute + // serializes as either 'false' (boolean) or the function string. + // FocusTrap receives it — verify the FocusTrap is present with + // a non-empty escapeDeactivates. + const trap = screen.getByTestId('focus-trap'); + const escapeAttr = trap.getAttribute('data-escape-deactivates'); + expect(escapeAttr).toBeTruthy(); + }); + + it('wires requestClose as onDeactivate on mobile too', () => { + const requestClose = vi.fn<() => void>(); + render( + + } /> + + ); + + expect(screen.getByTestId('mobile-swipe-down')).toHaveAttribute('data-request-close', 'true'); + }); + }); + + describe('initialFocus', () => { + it('has initialFocus=false by default on desktop', () => { + renderMenu({ anchor: anchorRect, menu: }); + + expect(screen.getByTestId('focus-trap')).toHaveAttribute('data-initial-focus', 'false'); + }); + + it('has initialFocus=false by default on mobile', () => { + renderMenuMobile({ anchor: anchorRect, menu: }); + + expect(screen.getByTestId('focus-trap')).toHaveAttribute('data-initial-focus', 'false'); + }); + }); +}); diff --git a/src/app/components/ResponsiveMenu.tsx b/src/app/components/ResponsiveMenu.tsx index 9e1808081..e23ca81b3 100644 --- a/src/app/components/ResponsiveMenu.tsx +++ b/src/app/components/ResponsiveMenu.tsx @@ -1,22 +1,11 @@ import type { ReactNode } from 'react'; import type { RectCords } from 'folds'; -import { PopOut } from 'folds'; +import { Box, PopOut } from 'folds'; import FocusTrap from 'focus-trap-react'; import { ScreenSize, useScreenSizeOptionally } from '$hooks/useScreenSize'; import { stopPropagation } from '$utils/keyboard'; import { MobileSwipeDownModal } from './MobileSwipeDownModal'; - -type DragHandlers = { - onTouchStart: (e: React.TouchEvent) => void; - onTouchMove: (e: React.TouchEvent) => void; - onTouchEnd: () => void; -}; - -/** - * Given the sheet's drag handle on mobile, and nothing on desktop. Only - * `RoomViewHeader` needs this; every other menu passes a plain node. - */ -type MenuRenderer = (dragHandle: ReactNode, dragHandlers: DragHandlers | undefined) => ReactNode; +import * as css from './ResponsiveMenu.css'; type ComponentPosition = 'Top' | 'Right' | 'Bottom' | 'Left'; type ComponentAlign = 'Start' | 'Center' | 'End'; @@ -24,7 +13,7 @@ type ComponentAlign = 'Start' | 'Center' | 'End'; type ResponsiveMenuProps = { anchor: RectCords | undefined; requestClose: () => void; - menu: ReactNode | MenuRenderer; + menu: ReactNode; /** The element the menu hangs off on desktop. */ children?: ReactNode; position?: ComponentPosition; @@ -79,9 +68,17 @@ export function ResponsiveMenu({ {(dragHandle, dragHandlers) => ( -
- {typeof menu === 'function' ? menu(dragHandle, dragHandlers) : menu} -
+ + {dragHandle} + {menu} +
)}
@@ -100,11 +97,7 @@ export function ResponsiveMenu({ content={ // Gated so a call site that builds its menu inline does that work on open, // not on every render of the trigger. - anchor ? ( - - {typeof menu === 'function' ? menu(null, undefined) : menu} - - ) : null + anchor ? {menu} : null } > {children} diff --git a/src/app/components/RoomSummaryLoader.tsx b/src/app/components/RoomSummaryLoader.tsx index 42764659d..7b075709b 100644 --- a/src/app/components/RoomSummaryLoader.tsx +++ b/src/app/components/RoomSummaryLoader.tsx @@ -6,7 +6,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import type { LocalRoomSummary } from '$hooks/useLocalRoomSummary'; import { useLocalRoomSummary } from '$hooks/useLocalRoomSummary'; -export type IRoomSummary = Awaited>; +type IRoomSummary = Awaited>; type RoomSummaryLoaderProps = { roomIdOrAlias: string; diff --git a/src/app/components/SecretStorage.tsx b/src/app/components/SecretStorage.tsx index 0b6c26f65..2b44d6a98 100644 --- a/src/app/components/SecretStorage.tsx +++ b/src/app/components/SecretStorage.tsx @@ -1,6 +1,6 @@ import type { FormEventHandler } from 'react'; import { useCallback } from 'react'; -import { Box, Text, Button, Spinner, color } from 'folds'; +import { Box, Text } from 'folds'; import { decodeRecoveryKey, deriveRecoveryKeyFromPassphrase } from '$types/matrix-sdk'; import type { SecretStorageKeyContent, @@ -8,6 +8,8 @@ import type { } from '$types/matrix/accountData'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; import { useAlive } from '$hooks/useAlive'; import { PasswordInput } from './password-input'; @@ -91,25 +93,22 @@ export function SecretStorageRecoveryPassphrase({ /> - + - {driveKeyState.status === AsyncStatus.Error && ( - - {driveKeyState.error.message} - - )} + ); } @@ -181,25 +180,22 @@ export function SecretStorageRecoveryKey({ /> - + - {driveKeyState.status === AsyncStatus.Error && ( - - {driveKeyState.error.message} - - )} + ); } diff --git a/src/app/components/avatar-upload-tile/AvatarUploadTile.tsx b/src/app/components/avatar-upload-tile/AvatarUploadTile.tsx new file mode 100644 index 000000000..2b2c9cd0b --- /dev/null +++ b/src/app/components/avatar-upload-tile/AvatarUploadTile.tsx @@ -0,0 +1,121 @@ +import { type ReactNode, useCallback, useMemo, useState } from 'react'; +import { Box, Text, Button, Modal } from 'folds'; +import { SettingTile } from '$components/setting-tile'; +import { useObjectURL } from '$hooks/useObjectURL'; +import type { UploadSuccess } from '$state/upload'; +import { createUploadAtom } from '$state/upload'; +import { useFilePicker } from '$hooks/useFilePicker'; +import { CompactUploadCardRenderer } from '$components/upload-card'; +import { ImageEditor } from '$components/image-editor'; +import { ModalWide } from '$styles/Modal.css'; +import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; +import { confirm } from '$components/confirm/confirm'; + +export type AvatarUploadTileProps = { + title: string; + focusId?: string; + after: ReactNode; + disableSetAvatar?: boolean; + removeDisabled?: boolean; + onUpload: (mxc: string) => void; + onRemove: () => void; + confirmTitle: string; + confirmDescription: string; +}; + +export function AvatarUploadTile({ + title, + focusId, + after, + disableSetAvatar = false, + removeDisabled = false, + onUpload, + onRemove, + confirmTitle, + confirmDescription, +}: AvatarUploadTileProps) { + const [imageFile, setImageFile] = useState(); + const imageFileURL = useObjectURL(imageFile); + const uploadAtom = useMemo(() => { + if (imageFile) return createUploadAtom(imageFile); + return undefined; + }, [imageFile]); + + const pickFile = useFilePicker(setImageFile, false); + + const handleRemoveUpload = useCallback(() => { + setImageFile(undefined); + }, []); + + const handleUploaded = useCallback( + (upload: UploadSuccess) => { + onUpload(upload.mxc); + handleRemoveUpload(); + }, + [onUpload, handleRemoveUpload] + ); + + const handleRemoveAvatar = useCallback(async () => { + const ok = await confirm({ + title: confirmTitle, + description: confirmDescription, + action: 'Remove', + variant: 'Critical', + }); + if (ok) { + onRemove(); + } + }, [confirmTitle, confirmDescription, onRemove]); + + return ( + + {uploadAtom ? ( + + + + ) : ( + + + {!removeDisabled && ( + + )} + + )} + + {imageFileURL && ( + + + + + + )} + + ); +} diff --git a/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx b/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx index 805cbb0ac..e35b13242 100644 --- a/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx +++ b/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx @@ -1,5 +1,6 @@ -import { Box, Button, Spinner, Text, color, config } from 'folds'; +import { Box, Button, Text, color, config } from 'folds'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; +import { AsyncButton } from '$components/AsyncButton'; type DirectInvitePromptProps = { onCancel: () => void; @@ -31,17 +32,18 @@ export function DirectInvitePrompt({ )} - + diff --git a/src/app/components/editor/Editor.tsx b/src/app/components/editor/Editor.tsx index 7832151e6..447ebc7a0 100644 --- a/src/app/components/editor/Editor.tsx +++ b/src/app/components/editor/Editor.tsx @@ -60,7 +60,7 @@ const insertPastedText = (editor: Editor, text: string): void => { }); }; -export type EditorChangeHandler = (value: Descendant[]) => void; +type EditorChangeHandler = (value: Descendant[]) => void; const MAX_MULTILINE_MEASURE_RETRIES = 2; const MULTILINE_HEIGHT_EPSILON = 1; const TRAILING_SPACE_SENTINEL = '\u200B'; diff --git a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx index 827ccc5e7..7a2df9761 100644 --- a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx @@ -7,7 +7,7 @@ import type { MatrixClient } from '$types/matrix-sdk'; import { JoinRule } from '$types/matrix-sdk'; import { useAtomValue } from 'jotai'; -import { getDirectRoomAvatarUrl } from '$utils/room'; +import { getDirectRoomAvatarUrl } from '$utils/room/display'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { isRoomAlias } from '$utils/matrix'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; diff --git a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx index 5082e9425..e05197723 100644 --- a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx @@ -12,7 +12,7 @@ import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { onTabPress } from '$utils/keyboard'; import { useKeyDown } from '$hooks/useKeyDown'; import { getMxIdLocalPart, isUserId } from '$utils/matrix'; -import { getAvatarUrl, getMemberDisplayName, getMemberSearchStr } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName, getMemberSearchStr } from '$utils/room/display'; import { UserAvatar } from '$components/user-avatar'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 6f65b9a92..04e2de348 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -5,7 +5,7 @@ import { sanitizeText } from '$utils/sanitize'; import { markdownToHtml, injectDataMd } from '$plugins/markdown'; import { sanitizeForRegex } from '$utils/regex'; import { getMxIdLocalPart, isUserId } from '$utils/matrix'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; import type { CustomElement } from './slate'; import { BlockType } from './types'; import { getMarkdownCodeSpanRanges, isInsideMarkdownCodeSpan } from './utils'; diff --git a/src/app/components/editor/utils.ts b/src/app/components/editor/utils.ts index 48fc960b9..1776f9fb0 100644 --- a/src/app/components/editor/utils.ts +++ b/src/app/components/editor/utils.ts @@ -4,7 +4,7 @@ import { ReactEditor } from 'slate-react'; import type { Room } from '$types/matrix-sdk'; import type { Nicknames } from '$state/nicknames'; import { getMxIdLocalPart, isUserId } from '$utils/matrix'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; import { BlockType } from './types'; import type { CommandElement, diff --git a/src/app/components/event-history/EventHistory.tsx b/src/app/components/event-history/EventHistory.tsx index 4dfeda3d9..7fc644262 100644 --- a/src/app/components/event-history/EventHistory.tsx +++ b/src/app/components/event-history/EventHistory.tsx @@ -13,7 +13,7 @@ import { config, } from 'folds'; import type { IContent, MatrixEvent, Room } from '$types/matrix-sdk'; -import { getAvatarUrl, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -50,7 +50,7 @@ import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUr import * as css from './EventHistory.css'; import { EventType } from '$types/matrix-sdk'; -export type EventHistoryProps = { +type EventHistoryProps = { room: Room; mEvents: MatrixEvent[]; requestClose: () => void; diff --git a/src/app/components/event-readers/EventReaders.tsx b/src/app/components/event-readers/EventReaders.tsx index bf45212e1..6bc4842eb 100644 --- a/src/app/components/event-readers/EventReaders.tsx +++ b/src/app/components/event-readers/EventReaders.tsx @@ -3,7 +3,7 @@ import { useEffect, useState } from 'react'; import { Avatar, Box, Header, IconButton, MenuItem, Scroll, Text, as, config } from 'folds'; import type { Room } from '$types/matrix-sdk'; import { useRoomEventReaders } from '$hooks/useRoomEventReaders'; -import { getAvatarUrl, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -18,7 +18,7 @@ import { UserAvatar } from '$components/user-avatar'; import { composerIcon, userFallbackIcon, X } from '$components/icons/phosphor'; import * as css from './EventReaders.css'; -export type EventReadersProps = { +type EventReadersProps = { room: Room; eventId: string; requestClose: () => void; diff --git a/src/app/components/image-editor/ImageEditor.tsx b/src/app/components/image-editor/ImageEditor.tsx index 8e2854648..f55ff6602 100644 --- a/src/app/components/image-editor/ImageEditor.tsx +++ b/src/app/components/image-editor/ImageEditor.tsx @@ -3,7 +3,7 @@ import { Box, Chip, Header, IconButton, Text, as } from 'folds'; import { ArrowLeft, sizedIcon } from '$components/icons/phosphor'; import * as css from './ImageEditor.css'; -export type ImageEditorProps = { +type ImageEditorProps = { name: string; url: string; requestClose: () => void; diff --git a/src/app/components/image-pack-view/ImagePackContent.tsx b/src/app/components/image-pack-view/ImagePackContent.tsx index d162f745f..51380bac9 100644 --- a/src/app/components/image-pack-view/ImagePackContent.tsx +++ b/src/app/components/image-pack-view/ImagePackContent.tsx @@ -19,7 +19,7 @@ import { UsageSwitcher } from './UsageSwitcher'; import { ImagePackProfile, ImagePackProfileEdit } from './PackMeta'; import * as css from './style.css'; -export type ImagePackContentProps = { +type ImagePackContentProps = { imagePack: ImagePack; canEdit?: boolean; onUpdate?: (packContent: PackContent) => Promise; diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index e40c13695..df2c519a1 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -26,7 +26,7 @@ import { copyImageToClipboard } from '$utils/dom'; import { getDownloadFilename, saveFileToDevice } from '$utils/download'; import { ResponsiveMenu } from '$components/ResponsiveMenu'; -export type ImageViewerProps = { +type ImageViewerProps = { alt: string; filename?: string; src: string; @@ -108,6 +108,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( anchor={menu.anchor} requestClose={menu.close} align="Start" + offset={0} menu={ diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index def031d64..851eaa581 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -10,9 +10,6 @@ import { Text, IconButton, Input, - Button, - Spinner, - color, TextArea, Dialog, Menu, @@ -30,9 +27,10 @@ import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { highlightText, makeHighlightRegex } from '$plugins/react-custom-html-parser'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { composerIcon, X } from '$components/icons/phosphor'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { BreakWord } from '$styles/Text.css'; import { useAlive } from '$hooks/useAlive'; import { getMxIdServer } from '$utils/mxIdHelper'; import { KnownMembership } from '$types/matrix-sdk'; @@ -275,18 +273,17 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { resize="None" /> - {inviteState.status === AsyncStatus.Error && ( - - {inviteState.error.message} - - )} - + diff --git a/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx b/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx index 8718dde05..5ff3896c3 100644 --- a/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx +++ b/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx @@ -1,12 +1,14 @@ import type { FormEventHandler } from 'react'; import { useCallback, useEffect } from 'react'; -import { config, Box, Text, Input, color, Button, Spinner } from 'folds'; +import { config, Box, Text, Input } from 'folds'; import type { MatrixError } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { createDebugLogger } from '$utils/debugLogger'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; const debugLog = createDebugLogger('KnockRoomPrompt'); @@ -65,21 +67,15 @@ export function KnockRoomPrompt({ roomId, via, onDone, onCancel }: KnockRoomProp - {knockState.status === AsyncStatus.Error && ( - - Failed to knock! {knockState.error.message} - - )} + - + ); diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx index 6abdcc854..e2fa5cc38 100644 --- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx +++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx @@ -1,11 +1,13 @@ import { useCallback, useEffect, useMemo } from 'react'; -import { config, Box, Text, color, Button, Spinner } from 'folds'; +import { config, Box, Text } from 'folds'; import type { MatrixError } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { getJoinedSpaceChildrenSummary, getRecursiveSpaceLeaveOrder } from '$utils/room'; +import { getJoinedSpaceChildrenSummary, getRecursiveSpaceLeaveOrder } from '$utils/room/hierarchy'; import { rateLimitedActions } from '$utils/matrix'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; type LeaveSpacePromptProps = { roomId: string; @@ -85,41 +87,39 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP {formatJoinedContentsMessage(roomCount, subspaceCount)} )} - {leaveState.status === AsyncStatus.Error && ( - - Failed to leave space! {leaveState.error.message} - - )} - {leaveAllState.status === AsyncStatus.Error && ( - - Failed to leave space, rooms, and subspaces! {leaveAllState.error.message} - - )} + + - + {joinedChildrenCount > 0 && ( - + )} diff --git a/src/app/components/member-tile/MemberTile.tsx b/src/app/components/member-tile/MemberTile.tsx index ca53b3e9a..c8be93ad3 100644 --- a/src/app/components/member-tile/MemberTile.tsx +++ b/src/app/components/member-tile/MemberTile.tsx @@ -2,7 +2,7 @@ import type { ReactNode } from 'react'; import { as, Avatar, Box, Text } from 'folds'; import { userFallbackIcon } from '$components/icons/phosphor'; import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; -import { getAvatarUrl, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; import { useAtomValue } from 'jotai'; diff --git a/src/app/components/message-preview/MessagePreview.tsx b/src/app/components/message-preview/MessagePreview.tsx index 20ab4c84a..fa97eb4bc 100644 --- a/src/app/components/message-preview/MessagePreview.tsx +++ b/src/app/components/message-preview/MessagePreview.tsx @@ -55,7 +55,8 @@ import { nicknamesAtom } from '$state/nicknames'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; import type { GetContentCallback } from '$types/matrix/room'; -import { getEditedEvent, getMemberAvatarMxc, getMemberDisplayName } from '$utils/room'; +import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room/display'; +import { getEditedEvent } from '$utils/room/relations'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import * as customHtmlCss from '$styles/CustomHtml.css'; diff --git a/src/app/components/message/FileHeader.tsx b/src/app/components/message/FileHeader.tsx index f53e1f233..dc03532e6 100644 --- a/src/app/components/message/FileHeader.tsx +++ b/src/app/components/message/FileHeader.tsx @@ -53,7 +53,7 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow ); } -export type FileHeaderProps = { +type FileHeaderProps = { body: string; mimeType: string; after?: ReactNode; diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index fd67b1a45..2e09ed75b 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -3,7 +3,7 @@ import { ArrowSquareOut, sizedIcon, Link } from '$components/icons/phosphor'; import { Box, Chip, Text, toRem } from 'folds'; import { type IContent, type IPreviewUrlResponse, type MatrixClient } from '$types/matrix-sdk'; import { isJumboEmojiText } from '$utils/emojiDetection'; -import { trimReplyFromBody } from '$utils/room'; +import { trimReplyFromBody } from '$utils/room/display'; import type { IAudioContent, IAudioInfo, diff --git a/src/app/components/message/PollEvent.tsx b/src/app/components/message/PollEvent.tsx index fa3f6abb1..7060af819 100644 --- a/src/app/components/message/PollEvent.tsx +++ b/src/app/components/message/PollEvent.tsx @@ -15,6 +15,7 @@ import * as css from './PollEvent.css'; import { useCallback, useEffect, useState } from 'react'; import { PollResponsesViewer } from '$features/room/poll-modals'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; type PollEventProps = { content: Record; @@ -100,8 +101,8 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { const [isEnded, setIsEnded] = useState(getEndIndex(sortedChildEvents) !== -1); const [updateCounter, setUpdateCounter] = useState(0); - useEffect(() => { - const handleUpdate = (event: MatrixEvent) => { + const handleUpdate = useCallback( + (event: MatrixEvent) => { const relation = event.getRelation(); if ( relation?.event_id === eventId || @@ -110,12 +111,11 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { ) { setUpdateCounter((c) => c + 1); } - }; - room.on(RoomEvent.Timeline, handleUpdate); - return () => { - room.off(RoomEvent.Timeline, handleUpdate); - }; - }, [room, eventId]); + }, + [eventId] + ); + + useMatrixEvent(room, RoomEvent.Timeline, handleUpdate); // ensure a new sorted array is only generated when a new list is made useEffect(() => { diff --git a/src/app/components/message/Reaction.tsx b/src/app/components/message/Reaction.tsx index 188888738..393cba9bb 100644 --- a/src/app/components/message/Reaction.tsx +++ b/src/app/components/message/Reaction.tsx @@ -4,7 +4,7 @@ import { sizedIcon, Warning } from '$components/icons/phosphor'; import classNames from 'classnames'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { getHexcodeForEmoji, getShortcodeFor } from '$plugins/emoji'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; import { eventWithShortcode, getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { useAtomValue } from 'jotai'; import { nicknamesAtom } from '$state/nicknames'; diff --git a/src/app/components/message/Reply.test.tsx b/src/app/components/message/Reply.test.tsx index def400b46..c41422eee 100644 --- a/src/app/components/message/Reply.test.tsx +++ b/src/app/components/message/Reply.test.tsx @@ -75,7 +75,7 @@ vi.mock('$features/settings/useSettingsLinkBaseUrl', () => ({ useSettingsLinkBaseUrl: () => 'https://app.sable.moe', })); -vi.mock('$utils/room', async (importActual) => { +vi.mock('$utils/room/display', async (importActual) => { const actual = (await importActual()) as object; return { ...actual, diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index da9ce00d7..1d0cdd662 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -25,12 +25,10 @@ import { } from '$components/icons/phosphor'; import { getMemberDisplayName, - getReactionKey, - getReactionShortcode, - getRedactionTargetId, trimReplyFromBody, trimReplyFromFormattedBody, -} from '$utils/room'; +} from '$utils/room/display'; +import { getReactionKey, getReactionShortcode, getRedactionTargetId } from '$utils/room/relations'; import { getMxIdLocalPart } from '$utils/matrix'; import { randomNumberBetween } from '$utils/common'; import { sanitizeCustomHtml } from '$utils/sanitize'; diff --git a/src/app/components/message/modals/MessageEditHistory.tsx b/src/app/components/message/modals/MessageEditHistory.tsx index 5b4e33f1f..4132f8317 100644 --- a/src/app/components/message/modals/MessageEditHistory.tsx +++ b/src/app/components/message/modals/MessageEditHistory.tsx @@ -3,7 +3,7 @@ import type { Room, MatrixEvent } from '$types/matrix-sdk'; import { useSetAtom } from 'jotai'; import { MenuItem, Text } from 'folds'; import { Clock, menuIcon } from '$components/icons/phosphor'; -import { getEventEdits } from '$utils/room'; +import { getEventEdits } from '$utils/room/relations'; import { modalAtom, ModalType } from '$state/modal'; import * as css from '$features/room/message/styles.css'; import { EventHistory } from '$components/event-history'; diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx index 70ef9265f..9752dec20 100644 --- a/src/app/components/message/modals/MessageForward.tsx +++ b/src/app/components/message/modals/MessageForward.tsx @@ -4,18 +4,17 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { modalAtom, ModalType } from '$state/modal'; import { MenuItem, Text, as } from 'folds'; import { ArrowRight, menuIcon } from '$components/icons/phosphor'; -import { useAtomValue, useSetAtom } from 'jotai'; +import { useSetAtom } from 'jotai'; import type { MatrixEvent, Room } from '$types/matrix-sdk'; import { useCallback, useEffect, useMemo, useState } from 'react'; -import { allRoomsAtom } from '$state/room-list/roomList'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; -import { factoryRoomIdByActivity } from '$utils/sort'; +import { useMessageTargetRooms } from '$hooks/useMessageTargetRooms'; import * as css from '$features/room/message/styles.css'; import { sanitizeCustomHtml, sanitizeText } from '$utils/sanitize'; import { createDebugLogger } from '$utils/debugLogger'; import * as Sentry from '@sentry/react'; import { isRoomPrivate } from '$utils/roomVisibility'; -import { canForwardEvent } from '$utils/room'; +import { canForwardEvent } from '$utils/room/relations'; import * as prefix from '$unstable/prefixes'; import { SearchWrapper } from '$features/navigate'; import { useDismissOnBack } from '$utils/androidBack'; @@ -100,7 +99,6 @@ export function MessageForwardInternal({ const forwardable = canForwardEvent(mEvent); const [isForwarding, setIsForwarding] = useState(false); const [forwardError, setForwardError] = useState(null); - const allRooms = useAtomValue(allRoomsAtom); const allJoinedRooms = useAllJoinedRoomsSet(); const getRoom = useGetRoom(allJoinedRooms); @@ -112,16 +110,7 @@ export function MessageForwardInternal({ useDismissOnBack(onClose); // possible targets to forward the message to - const forwardTargets = useMemo( - () => - allRooms - .filter((id) => { - const target = getRoom(id); - return !!target && !target.isSpaceRoom() && target.maySendMessage(); - }) - .sort(factoryRoomIdByActivity(mx)), - [allRooms, getRoom, mx] - ); + const forwardTargets = useMessageTargetRooms(); const forwardToRoom = useCallback( (targetRoomId: string) => { diff --git a/src/app/components/message/modals/MessageSource.tsx b/src/app/components/message/modals/MessageSource.tsx index 51cdc1ce8..9b4fb21a9 100644 --- a/src/app/components/message/modals/MessageSource.tsx +++ b/src/app/components/message/modals/MessageSource.tsx @@ -4,7 +4,7 @@ import { useSetAtom } from 'jotai'; import { MenuItem, Text } from 'folds'; import { CodeBlock, menuIcon } from '$components/icons/phosphor'; import { TextViewer } from '$components/text-viewer'; -import { getEventEdits } from '$utils/room'; +import { getEventEdits } from '$utils/room/relations'; import { modalAtom, ModalType } from '$state/modal'; import * as css from '$features/room/message/styles.css'; diff --git a/src/app/components/message/modals/Options.tsx b/src/app/components/message/modals/Options.tsx index 6b3c24350..454dda3b3 100644 --- a/src/app/components/message/modals/Options.tsx +++ b/src/app/components/message/modals/Options.tsx @@ -1,6 +1,11 @@ import type { RoomPinnedEventsEventContent, StateEvents } from '$types/matrix-sdk'; import { type Room, type MatrixEvent, type Relations, EventType } from '$types/matrix-sdk'; -import { canEditEvent, canForwardEvent, getEventEdits, isThreadRelationEvent } from '$utils/room'; +import { + canEditEvent, + canForwardEvent, + getEventEdits, + isThreadRelationEvent, +} from '$utils/room/relations'; import { MessageReportItem } from './MessageReport'; import type { RectCords } from 'folds'; import { as, Box, config, IconButton, Line, Menu, MenuItem, PopOut, Text } from 'folds'; @@ -323,7 +328,7 @@ const MessageFavoriteGifItem = as< ); }); -export type OptionEmojiMenuProps = { +type OptionEmojiMenuProps = { mEvent: MatrixEvent; closeMenu: () => void; onReactionToggle?: (targetEventId: string, key: string, shortcode?: string) => void; diff --git a/src/app/components/modal-overlay/ModalOverlay.test.tsx b/src/app/components/modal-overlay/ModalOverlay.test.tsx new file mode 100644 index 000000000..36713dd2c --- /dev/null +++ b/src/app/components/modal-overlay/ModalOverlay.test.tsx @@ -0,0 +1,225 @@ +// oxlint-disable typescript/no-explicit-any +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; + +// ── Mocks ─────────────────────────────────────────────────────────────────── + +/** + * Mock FocusTrap that simulates Escape behavior. When escapeDeactivates is + * truthy, pressing Escape calls onDeactivate. This lets us test the + * escapeDeactivates prop without dealing with jsdom's incompatible tabbable + * library (which doesn't find tabbable elements at all in jsdom v29). + */ +vi.mock('focus-trap-react', () => { + const React = require('react'); + const FocusTrapComponent = ({ children, focusTrapOptions }: any) => { + const opts = focusTrapOptions ?? {}; + const { escapeDeactivates, onDeactivate } = opts; + + React.useEffect(() => { + const handleKeyDown = (e: any) => { + if (e.key === 'Escape') { + const esc = escapeDeactivates; + const deactivate = typeof esc === 'function' ? esc(e) : esc === true || esc === undefined; + if (deactivate) { + onDeactivate?.(); + e.stopPropagation(); + } + } + }; + document.addEventListener('keydown', handleKeyDown); + return () => { + document.removeEventListener('keydown', handleKeyDown); + }; + }, [escapeDeactivates, onDeactivate]); + + return React.createElement('div', { 'data-testid': 'focus-trap' }, children); + }; + + return { default: FocusTrapComponent, FocusTrap: FocusTrapComponent }; +}); + +vi.mock('folds', () => ({ + Box: ({ children, direction }: any) => ( +
+ {children} +
+ ), + Overlay: ({ open, backdrop, children }: any) => ( +
+
{backdrop}
+ {children} +
+ ), + OverlayBackdrop: () =>
backdrop
, + OverlayCenter: ({ children }: any) =>
{children}
, +})); + +vi.mock('$components/MobileSwipeDownModal', () => ({ + MobileSwipeDownModal: ({ children }: any) => ( +
+ {children(
drag-handle
, { + onTouchStart: vi.fn<() => void>(), + onTouchMove: vi.fn<() => void>(), + onTouchEnd: vi.fn<() => void>(), + })} +
+ ), +})); + +vi.mock('$utils/androidBack', () => ({ + useDismissOnBack: vi.fn<() => void>(), +})); + +vi.mock('$utils/keyboard', () => ({ + stopPropagation: () => false, +})); + +vi.mock('$features/room/message/styles.css', () => ({ + MessageOptionsMenu: 'mock-message-options-menu', + MessageMobileDragHandle: 'mock-mobile-drag-handle', + MessageMobileDragIndicator: 'mock-mobile-drag-indicator', + MessageMobileOptionsWrapped: 'mock-mobile-options-wrapped', + MessageMobileOptionsContainer: 'mock-mobile-options-container', +})); + +import { ModalOverlay } from './ModalOverlay'; + +afterEach(() => { + cleanup(); +}); + +// ── Render helpers ────────────────────────────────────────────────────────── + +function desktop(props: Partial[0]> = {}) { + return render( + + void>()} {...props}> +
Modal Content
+
+
+ ); +} + +function mobile(props: Partial[0]> = {}) { + return render( + + void>()} {...props}> +
Modal Content
+
+
+ ); +} + +// ── Tests ─────────────────────────────────────────────────────────────────── + +describe('ModalOverlay', () => { + describe('escapeDeactivates', () => { + it('calls requestClose on Escape when escapeDeactivates is true', async () => { + const requestClose = vi.fn<() => void>(); + const user = userEvent.setup(); + + render( + + +
Content
+
+
+ ); + + await user.keyboard('{Escape}'); + expect(requestClose).toHaveBeenCalledOnce(); + }); + + it('does NOT call requestClose on Escape when escapeDeactivates is false', async () => { + const requestClose = vi.fn<() => void>(); + const user = userEvent.setup(); + + render( + + +
Content
+
+
+ ); + + await user.keyboard('{Escape}'); + expect(requestClose).not.toHaveBeenCalled(); + }); + + it('does NOT call requestClose with default escapeDeactivates (stopPropagation)', async () => { + // stopPropagation returns false, so Escape should NOT trigger close + const requestClose = vi.fn<() => void>(); + const user = userEvent.setup(); + + render( + + +
Content
+
+
+ ); + + await user.keyboard('{Escape}'); + expect(requestClose).not.toHaveBeenCalled(); + }); + }); + + describe('presentation', () => { + it('renders centred overlay on desktop (default)', () => { + desktop(); + + expect(screen.getByTestId('overlay')).toBeInTheDocument(); + expect(screen.getByTestId('overlay-center')).toBeInTheDocument(); + expect(screen.getByTestId('overlay-backdrop-inner')).toBeInTheDocument(); + expect(screen.getByTestId('modal-child')).toBeInTheDocument(); + expect(screen.getByTestId('focus-trap')).toBeInTheDocument(); + }); + + it('renders overlay with open=false on desktop', () => { + desktop({ open: false }); + + expect(screen.getByTestId('overlay')).toHaveAttribute('data-open', 'false'); + }); + + it('renders centred overlay on mobile when mobile="centred"', () => { + mobile({ mobile: 'centred' }); + + expect(screen.getByTestId('overlay')).toBeInTheDocument(); + expect(screen.getByTestId('overlay-center')).toBeInTheDocument(); + expect(screen.queryByTestId('mobile-swipe-down')).not.toBeInTheDocument(); + }); + + it('renders fullscreen overlay on mobile when mobile="fullscreen"', () => { + mobile({ mobile: 'fullscreen' }); + + expect(screen.getByTestId('overlay')).toBeInTheDocument(); + // Fullscreen does NOT render OverlayCenter or backdrop + expect(screen.queryByTestId('overlay-center')).not.toBeInTheDocument(); + expect(screen.queryByTestId('overlay-backdrop-inner')).not.toBeInTheDocument(); + expect(screen.queryByTestId('mobile-swipe-down')).not.toBeInTheDocument(); + // Focus-trap wraps the fullscreen content + expect(screen.getByTestId('focus-trap')).toBeInTheDocument(); + expect(screen.getByTestId('modal-child')).toBeInTheDocument(); + }); + + it('renders sheet via MobileSwipeDownModal on mobile when mobile="sheet"', () => { + mobile({ mobile: 'sheet' }); + + expect(screen.getByTestId('mobile-swipe-down')).toBeInTheDocument(); + expect(screen.getByTestId('drag-handle')).toBeInTheDocument(); + expect(screen.queryByTestId('overlay')).not.toBeInTheDocument(); + expect(screen.queryByTestId('overlay-center')).not.toBeInTheDocument(); + }); + + it('defaults to centred on mobile', () => { + mobile(); + + expect(screen.getByTestId('overlay')).toBeInTheDocument(); + expect(screen.getByTestId('overlay-center')).toBeInTheDocument(); + expect(screen.queryByTestId('mobile-swipe-down')).not.toBeInTheDocument(); + }); + }); +}); diff --git a/src/app/components/modal-overlay/ModalOverlay.tsx b/src/app/components/modal-overlay/ModalOverlay.tsx index cf961d715..857b80ec9 100644 --- a/src/app/components/modal-overlay/ModalOverlay.tsx +++ b/src/app/components/modal-overlay/ModalOverlay.tsx @@ -1,9 +1,11 @@ import type { ComponentProps, MutableRefObject, ReactNode } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Overlay, OverlayBackdrop, OverlayCenter } from 'folds'; +import { Box, Overlay, OverlayBackdrop, OverlayCenter } from 'folds'; import { ScreenSize, useScreenSizeOptionally } from '$hooks/useScreenSize'; import { stopPropagation } from '$utils/keyboard'; import { useDismissOnBack } from '$utils/androidBack'; +import { MobileSwipeDownModal } from '$components/MobileSwipeDownModal'; +import * as messageCss from '$features/room/message/styles.css'; type FocusTrapOptions = ComponentProps['focusTrapOptions']; @@ -12,8 +14,10 @@ type ModalOverlayProps = { requestClose: () => void; /** Set false for overlays that must be dismissed deliberately, not by a stray click. */ dismissOnClickOutside?: boolean; - /** `fullscreen` drops the centred modal on phones and fills the viewport instead. */ - mobile?: 'centred' | 'fullscreen'; + /** `centred` keeps the desktop-style dialog on phones. + * `fullscreen` drops the centred modal and fills the viewport. + * `sheet` rises as a bottom sheet with a swipe-down-to-dismiss handle. */ + mobile?: 'centred' | 'fullscreen' | 'sheet'; /** The modal element, used as the focus fallback and as the fullscreen wrapper. */ contentRef?: MutableRefObject; /** Set false for flows that Escape must not abort, such as device verification. */ @@ -58,6 +62,30 @@ export function ModalOverlay({ ); } + if (open && isMobile && mobile === 'sheet') { + const focusTrapOptions = { + initialFocus: false, + fallbackFocus: () => document.body, + onDeactivate: requestClose, + clickOutsideDeactivates: dismissOnClickOutside, + escapeDeactivates, + }; + return ( + + {(dragHandle) => ( + +
+ + {dragHandle} + {children} + +
+
+ )} +
+ ); + } + return ( }> diff --git a/src/app/components/nav/NavCategoryHeader.tsx b/src/app/components/nav/NavCategoryHeader.tsx index 9c09ca186..3a0e44b55 100644 --- a/src/app/components/nav/NavCategoryHeader.tsx +++ b/src/app/components/nav/NavCategoryHeader.tsx @@ -3,7 +3,7 @@ import classNames from 'classnames'; import { Header, as } from 'folds'; import * as css from './styles.css'; -export type NavCategoryHeaderProps = { +type NavCategoryHeaderProps = { children: ReactNode; }; export const NavCategoryHeader = as<'div', NavCategoryHeaderProps>( diff --git a/src/app/components/nav/NavMenu.tsx b/src/app/components/nav/NavMenu.tsx new file mode 100644 index 000000000..5681e1a22 --- /dev/null +++ b/src/app/components/nav/NavMenu.tsx @@ -0,0 +1,50 @@ +import type { ReactNode } from 'react'; +import { forwardRef } from 'react'; +import { Box, Menu, MenuItem, Text, config, toRem } from 'folds'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { useRoomsUnread } from '$state/hooks/unread'; +import { markAsRead } from '$utils/notifications'; +import { Checks, menuIcon } from '$components/icons/phosphor'; + +type NavMenuProps = { + rooms: string[]; + requestClose: () => void; + children?: ReactNode; +}; + +export const NavMenu = forwardRef( + ({ rooms, requestClose, children }, ref) => { + const mx = useMatrixClient(); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); + const unread = useRoomsUnread(rooms, roomToUnreadAtom); + + const handleMarkAsRead = () => { + if (!unread) return; + rooms.forEach((rId) => markAsRead(mx, rId, hideReads)); + requestClose(); + }; + + return ( + + + + + Mark as Read + + + {children} + + + ); + } +); +NavMenu.displayName = 'NavMenu'; diff --git a/src/app/components/page/PageNavHeaderWithMenu.tsx b/src/app/components/page/PageNavHeaderWithMenu.tsx new file mode 100644 index 000000000..1a85c828c --- /dev/null +++ b/src/app/components/page/PageNavHeaderWithMenu.tsx @@ -0,0 +1,69 @@ +import type { ReactNode } from 'react'; +import type { RectCords } from 'folds'; +import { Box, IconButton, Text } from 'folds'; +import { composerIcon, DotsThreeOutlineVerticalIcon } from '$components/icons/phosphor'; +import { PageNavHeader } from '$components/page'; +import { ResponsiveMenu } from '$components/ResponsiveMenu'; + +type PageNavHeaderWithMenuProps = { + hideText?: boolean; + title: string; + collapsedIcon: ReactNode; + menu: ReactNode; + anchor: RectCords | undefined; + requestClose: () => void; + triggerProps: { + onClick: React.MouseEventHandler; + }; +}; + +export function PageNavHeaderWithMenu({ + hideText, + title, + collapsedIcon, + menu, + anchor, + requestClose, + triggerProps, +}: PageNavHeaderWithMenuProps) { + return ( + <> + + {hideText ? ( + + + {collapsedIcon} + + + ) : ( + + + + {title} + + + + + {composerIcon(DotsThreeOutlineVerticalIcon, { + weight: anchor ? 'fill' : 'regular', + })} + + + + )} + + + + ); +} diff --git a/src/app/components/page/PageNavShell.tsx b/src/app/components/page/PageNavShell.tsx new file mode 100644 index 000000000..23b7a5571 --- /dev/null +++ b/src/app/components/page/PageNavShell.tsx @@ -0,0 +1,57 @@ +import type { Dispatch, ReactNode, SetStateAction } from 'react'; +import { Box, toRem } from 'folds'; +import { PageNav } from '$components/page'; +import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; +import { UserQuickTools } from '$pages/client/sidebar/UserQuickTools'; + +type PageNavShellProps = { + header: ReactNode; + children: ReactNode; + curWidth: number; + setCurWidth: Dispatch>; + roomSidebarWidth: number; + setRoomSidebarWidth: (width: number) => void; + setIsResizingSidebar: (is: boolean) => void; + isMobile: boolean; + oldSidebar: boolean; +}; + +export function PageNavShell({ + header, + children, + curWidth, + setCurWidth, + roomSidebarWidth, + setRoomSidebarWidth, + setIsResizingSidebar, + isMobile, + oldSidebar, +}: PageNavShellProps) { + return ( + + + {header} + {children} + + {!isMobile && ( + + )} + {!oldSidebar && !isMobile && } + + ); +} diff --git a/src/app/components/page/PersistentRoomHost.tsx b/src/app/components/page/PersistentRoomHost.tsx index 85a14d1d7..c4ba84953 100644 --- a/src/app/components/page/PersistentRoomHost.tsx +++ b/src/app/components/page/PersistentRoomHost.tsx @@ -11,7 +11,7 @@ import { resolveSection, type SectionNav } from '$pages/pathUtils'; import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths'; import { isRoomAlias, isRoomId } from '$utils/matrix'; -export type DisplayedRoom = { +type DisplayedRoom = { roomIdOrAlias: string; eventId?: string; }; diff --git a/src/app/components/page/SidebarPanel.tsx b/src/app/components/page/SidebarPanel.tsx index 4df42f0e4..c7d42ccbc 100644 --- a/src/app/components/page/SidebarPanel.tsx +++ b/src/app/components/page/SidebarPanel.tsx @@ -1,10 +1,6 @@ -import { useEffect, useState } from 'react'; -import { useSetAtom } from 'jotai'; import { Box, Text, color, config, toRem } from 'folds'; import { SquaresFour, sizedIcon } from '$components/icons/phosphor'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; -import { isResizingSidebarAtom } from '$state/isResizingSidebar'; +import { useSidebarWidth } from '$hooks/useSidebarWidth'; import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; import { UserQuickTools } from '$pages/client/sidebar/UserQuickTools'; import { PageNav, PageNavHeader } from './Page'; @@ -14,14 +10,15 @@ import { PageNav, PageNavHeader } from './Page'; * an icon once dragged narrow enough for the title to stop fitting. */ export function SidebarPanel({ title }: { title: string }) { - const setIsResizingSidebar = useSetAtom(isResizingSidebarAtom); - const [roomSidebarWidth, setRoomSidebarWidth] = useSetting(settingsAtom, 'roomSidebarWidth'); - const [oldSidebar] = useSetting(settingsAtom, 'oldSidebar'); - const [curWidth, setCurWidth] = useState(roomSidebarWidth); - - useEffect(() => { - setCurWidth(roomSidebarWidth); - }, [roomSidebarWidth]); + const { + curWidth, + setCurWidth, + roomSidebarWidth, + setRoomSidebarWidth, + setIsResizingSidebar, + hideText, + oldSidebar, + } = useSidebarWidth(); return ( - {curWidth <= 80 ? ( + {hideText ? ( sizedIcon(SquaresFour, '200', { filled: true }) ) : ( diff --git a/src/app/components/page/index.tsx b/src/app/components/page/index.tsx index a4f72b5e2..970af9783 100644 --- a/src/app/components/page/index.tsx +++ b/src/app/components/page/index.tsx @@ -1,3 +1,4 @@ export * from './Page'; export * from './MessageSearchHeader'; export * from './SettingsSectionPage'; +export * from './PageNavHeaderWithMenu'; diff --git a/src/app/components/room-card/RoomCard.tsx b/src/app/components/room-card/RoomCard.tsx index c23e0fccd..f900bdcd4 100644 --- a/src/app/components/room-card/RoomCard.tsx +++ b/src/app/components/room-card/RoomCard.tsx @@ -13,7 +13,8 @@ import { onEnterOrSpace } from '$utils/keyboard'; import { useJoinedRoomId } from '$hooks/useJoinedRoomId'; import { useElementSizeObserver } from '$hooks/useElementSizeObserver'; -import { getRoomAvatarUrl, getStateEvent } from '$utils/room'; +import { getRoomAvatarUrl } from '$utils/room/display'; +import { getStateEvent } from '$utils/room/hierarchy'; import { useStateEventCallback } from '$hooks/useStateEventCallback'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { KnockRoomPrompt } from '$components/knock-room-prompt'; diff --git a/src/app/components/room-intro/RoomIntro.tsx b/src/app/components/room-intro/RoomIntro.tsx index 6b24f203b..fe5ffc7af 100644 --- a/src/app/components/room-intro/RoomIntro.tsx +++ b/src/app/components/room-intro/RoomIntro.tsx @@ -4,7 +4,8 @@ import type { Room } from '$types/matrix-sdk'; import { useAtomValue } from 'jotai'; import type { IRoomCreateContent } from '$types/matrix/room'; -import { getMemberDisplayName, getStateEvent } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; +import { getStateEvent } from '$utils/room/hierarchy'; import { nicknamesAtom } from '$state/nicknames'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getMxIdLocalPart, mxcUrlToHttp, removeRoomIdFromMDirect } from '$utils/matrix'; @@ -24,7 +25,7 @@ import { userFallbackIcon } from '$components/icons/phosphor'; import { DirectInvitePrompt } from '$components/direct-invite-prompt'; import { EventType, KnownMembership } from '$types/matrix-sdk'; -export type RoomIntroProps = { +type RoomIntroProps = { room: Room; }; diff --git a/src/app/components/setting-tile/SettingToggle.tsx b/src/app/components/setting-tile/SettingToggle.tsx new file mode 100644 index 000000000..a7f8c651d --- /dev/null +++ b/src/app/components/setting-tile/SettingToggle.tsx @@ -0,0 +1,48 @@ +import type { ReactNode } from 'react'; +import { Switch } from 'folds'; +import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; +import { SettingTile } from './SettingTile'; + +type SettingToggleProps = { + title: string; + focusId: string; + description?: ReactNode; + value: boolean; + onChange: (value: boolean) => void; + disabled?: boolean; + switchVariant?: 'Primary' | 'Secondary'; + ariaLabel?: string; + switchTitle?: string; +}; + +export function SettingToggle({ + title, + focusId, + description, + value, + onChange, + disabled, + switchVariant, + ariaLabel, + switchTitle, +}: SettingToggleProps) { + return ( + + + } + /> + + ); +} diff --git a/src/app/components/setting-tile/index.ts b/src/app/components/setting-tile/index.ts index 49fede72c..90546be22 100644 --- a/src/app/components/setting-tile/index.ts +++ b/src/app/components/setting-tile/index.ts @@ -1 +1,2 @@ export * from './SettingTile'; +export * from './SettingToggle'; diff --git a/src/app/components/sidebar/SidebarTab.tsx b/src/app/components/sidebar/SidebarTab.tsx new file mode 100644 index 000000000..a75e88fc1 --- /dev/null +++ b/src/app/components/sidebar/SidebarTab.tsx @@ -0,0 +1,68 @@ +import type { ReactNode } from 'react'; +import { + SidebarAvatar, + SidebarItemLeft, + SidebarUnreadBadge, + SidebarItemTooltip, +} from '$components/sidebar'; +import { ResponsiveMenu } from '$components/ResponsiveMenu'; +import type { MenuAnchor } from '$hooks/useMenuAnchor'; + +type SidebarTabProps = { + icon: ReactNode; + selected: boolean; + tooltip: string; + onClick: () => void; + menu: ReactNode; + menuAnchor: MenuAnchor; + unreadHighlight?: boolean; + unreadCount?: number; + dm?: boolean; +}; + +export function SidebarTab({ + icon, + selected, + tooltip, + onClick, + menu, + menuAnchor, + unreadHighlight = false, + unreadCount = 0, + dm = false, +}: SidebarTabProps) { + const { anchor, close, triggerProps } = menuAnchor; + + return ( + + + {(triggerRef) => ( + + + {icon} + + + )} + + {unreadCount > 0 && ( + + )} + + ); +} diff --git a/src/app/components/sidebar/index.ts b/src/app/components/sidebar/index.ts index 2d8e58672..0a764f36f 100644 --- a/src/app/components/sidebar/index.ts +++ b/src/app/components/sidebar/index.ts @@ -4,3 +4,4 @@ export * from './SidebarUnreadBadge'; export * from './SidebarContent'; export * from './SidebarStack'; export * from './SidebarStackSeparator'; +export * from './SidebarTab'; diff --git a/src/app/components/typing-indicator/TypingIndicator.tsx b/src/app/components/typing-indicator/TypingIndicator.tsx index 779a728a7..4865e5985 100644 --- a/src/app/components/typing-indicator/TypingIndicator.tsx +++ b/src/app/components/typing-indicator/TypingIndicator.tsx @@ -1,7 +1,7 @@ import { Box, as, toRem } from 'folds'; import * as css from './TypingIndicator.css'; -export type TypingIndicatorProps = { +type TypingIndicatorProps = { size?: '300' | '400'; disableAnimation?: boolean; }; diff --git a/src/app/components/url-preview/ClientPreview.tsx b/src/app/components/url-preview/ClientPreview.tsx index e54e90e54..00e126626 100644 --- a/src/app/components/url-preview/ClientPreview.tsx +++ b/src/app/components/url-preview/ClientPreview.tsx @@ -42,7 +42,7 @@ async function oEmbedData(url: string): Promise { return response.json(); } -export type EmbedHeaderProps = { +type EmbedHeaderProps = { title: string; source: string; after?: ReactNode; diff --git a/src/app/components/user-profile/UserChips.tsx b/src/app/components/user-profile/UserChips.tsx index e6f1a5d55..23d3b6b2b 100644 --- a/src/app/components/user-profile/UserChips.tsx +++ b/src/app/components/user-profile/UserChips.tsx @@ -44,7 +44,7 @@ import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useDirectRooms } from '$pages/client/direct/useDirectRooms'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; import { nameInitials } from '$utils/common'; import { getMatrixToUser } from '$plugins/matrix-to'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; diff --git a/src/app/components/user-profile/UserHero.tsx b/src/app/components/user-profile/UserHero.tsx index 9d8223601..235a889d6 100644 --- a/src/app/components/user-profile/UserHero.tsx +++ b/src/app/components/user-profile/UserHero.tsx @@ -220,13 +220,13 @@ export function UserHero({ size="T200" style={{ flex: 1, - wordBreak: 'break-word', + display: '-webkit-box', + overflowWrap: 'anywhere', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', opacity: allowEditing && !status ? config.opacity.Placeholder : 1, }} - truncate={allowEditing} > {status || (allowEditing && "What's on your mind?")} diff --git a/src/app/components/user-profile/UserModeration.tsx b/src/app/components/user-profile/UserModeration.tsx index bc796cc7f..0c0b88c39 100644 --- a/src/app/components/user-profile/UserModeration.tsx +++ b/src/app/components/user-profile/UserModeration.tsx @@ -1,10 +1,11 @@ -import { Box, Button, color, config, Spinner, Text, Input } from 'folds'; +import { Box, Button, config, Spinner, Text, Input } from 'folds'; import { ArrowLeft, ArrowRight, profileIcon, Prohibit } from '$components/icons/phosphor'; import { useCallback, useRef } from 'react'; import { useRoom } from '$hooks/useRoom'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { BreakWord } from '$styles/Text.css'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { timeDayMonYear, timeHourMinute } from '$utils/time'; @@ -79,7 +80,6 @@ export function UserBanAlert({ userId, reason, canUnban, bannedBy, ts }: UserBan }, [mx, room, userId]) ); const banning = unbanState.status === AsyncStatus.Loading; - const error = unbanState.status === AsyncStatus.Error; return ( @@ -109,22 +109,20 @@ export function UserBanAlert({ userId, reason, canUnban, bannedBy, ts }: UserBan )} - {error && ( - - {unbanState.error.message} - - )} + {canUnban && ( - + )} @@ -154,7 +152,6 @@ export function UserInviteAlert({ userId, reason, canKick, invitedBy, ts }: User }, [mx, room, userId]) ); const kicking = kickState.status === AsyncStatus.Loading; - const error = kickState.status === AsyncStatus.Error; return ( @@ -184,24 +181,22 @@ export function UserInviteAlert({ userId, reason, canKick, invitedBy, ts }: User )} - {error && ( - - {kickState.error.message} - - )} + {canKick && ( - + )} @@ -268,21 +263,9 @@ export function UserModeration({ userId, canKick, canBan, canInvite }: UserModer radii="300" disabled={disabled} /> - {kickState.status === AsyncStatus.Error && ( - - {kickState.error.message} - - )} - {banState.status === AsyncStatus.Error && ( - - {banState.error.message} - - )} - {inviteState.status === AsyncStatus.Error && ( - - {inviteState.error.message} - - )} + + + {canInvite && ( diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index ea6092aaa..3f9d6b572 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -17,7 +17,7 @@ import { User, } from '$components/icons/phosphor'; import { mxcUrlToHttp } from '$utils/matrix'; -import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room'; +import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room/display'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { usePowerLevels } from '$hooks/usePowerLevels'; diff --git a/src/app/components/user-profile/styles.css.ts b/src/app/components/user-profile/styles.css.ts index 095363339..a3e083b50 100644 --- a/src/app/components/user-profile/styles.css.ts +++ b/src/app/components/user-profile/styles.css.ts @@ -3,16 +3,21 @@ import { color, config, toRem } from 'folds'; export const UserHero = style({ position: 'relative', + minWidth: 0, + maxWidth: '100%', }); export const UserHeroCoverContainer = style({ height: toRem(96), overflow: 'hidden', + maxWidth: '100%', + minWidth: 0, }); export const UserHeroCover = style({ height: '100%', width: '100%', + maxWidth: '100%', objectFit: 'cover', objectPosition: 'center', }); @@ -26,6 +31,7 @@ export const UserHeroAvatarStatusContainer = style({ position: 'relative', height: toRem(29), width: '100%', + minWidth: 0, }); export const UserHeroAvatarContainer = style({ position: 'relative', diff --git a/src/app/cs-api.ts b/src/app/cs-api.ts index 636d0ec53..ec985b97b 100644 --- a/src/app/cs-api.ts +++ b/src/app/cs-api.ts @@ -2,8 +2,6 @@ import to from 'await-to-js'; import { trimTrailingSlash } from './utils/common'; export enum AutoDiscoveryAction { - PROMPT = 'PROMPT', - IGNORE = 'IGNORE', FAIL_PROMPT = 'FAIL_PROMPT', FAIL_ERROR = 'FAIL_ERROR', } diff --git a/src/app/cs-errorcode.ts b/src/app/cs-errorcode.ts index 4e54d5ac0..5001b5e1b 100644 --- a/src/app/cs-errorcode.ts +++ b/src/app/cs-errorcode.ts @@ -1,38 +1,13 @@ export enum ErrorCode { M_FORBIDDEN = 'M_FORBIDDEN', - M_UNKNOWN_TOKEN = 'M_UNKNOWN_TOKEN', - M_MISSING_TOKEN = 'M_MISSING_TOKEN', - M_BAD_JSON = 'M_BAD_JSON', - M_NOT_JSON = 'M_NOT_JSON', - M_NOT_FOUND = 'M_NOT_FOUND', M_LIMIT_EXCEEDED = 'M_LIMIT_EXCEEDED', - M_UNRECOGNIZED = 'M_UNRECOGNIZED', - M_UNKNOWN = 'M_UNKNOWN', - M_UNAUTHORIZED = 'M_UNAUTHORIZED', M_USER_DEACTIVATED = 'M_USER_DEACTIVATED', M_USER_IN_USE = 'M_USER_IN_USE', M_INVALID_USERNAME = 'M_INVALID_USERNAME', M_WEAK_PASSWORD = 'M_WEAK_PASSWORD', M_PASSWORD_TOO_SHORT = 'M_PASSWORD_TOO_SHORT', - M_ROOM_IN_USE = 'M_ROOM_IN_USE', - M_INVALID_ROOM_STATE = 'M_INVALID_ROOM_STATE', - M_THREEPID_IN_USE = 'M_THREEPID_IN_USE', - M_THREEPID_NOT_FOUND = 'M_THREEPID_NOT_FOUND', - M_THREEPID_AUTH_FAILED = 'M_THREEPID_AUTH_FAILED', - M_THREEPID_DENIED = 'M_THREEPID_DENIED', - M_SERVER_NOT_TRUSTED = 'M_SERVER_NOT_TRUSTED', - M_UNSUPPORTED_ROOM_VERSION = 'M_UNSUPPORTED_ROOM_VERSION', - M_INCOMPATIBLE_ROOM_VERSION = 'M_INCOMPATIBLE_ROOM_VERSION', - M_BAD_STATE = 'M_BAD_STATE', - M_GUEST_ACCESS_FORBIDDEN = 'M_GUEST_ACCESS_FORBIDDEN', - M_CAPTCHA_NEEDED = 'M_CAPTCHA_NEEDED', - M_CAPTCHA_INVALID = 'M_CAPTCHA_INVALID', - M_MISSING_PARAM = 'M_MISSING_PARAM', - M_INVALID_PARAM = 'M_INVALID_PARAM', - M_TOO_LARGE = 'M_TOO_LARGE', + M_EXCLUSIVE = 'M_EXCLUSIVE', - M_RESOURCE_LIMIT_EXCEEDED = 'M_RESOURCE_LIMIT_EXCEEDED', - M_CANNOT_LEAVE_SERVER_NOTICE_ROOM = 'M_CANNOT_LEAVE_SERVER_NOTICE_ROOM', M_MAX_DELAY_EXCEEDED = 'M_MAX_DELAY_EXCEEDED', } diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx index b0876fba1..82ec6aac7 100644 --- a/src/app/features/add-existing/AddExisting.tsx +++ b/src/app/features/add-existing/AddExisting.tsx @@ -33,7 +33,7 @@ import { mDirectAtom } from '$state/mDirectList'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import { VirtualTile } from '$components/virtualizer'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; import { nameInitials } from '$utils/common'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; diff --git a/src/app/features/call-status/CallRoomName.tsx b/src/app/features/call-status/CallRoomName.tsx index 184868236..6f620f77e 100644 --- a/src/app/features/call-status/CallRoomName.tsx +++ b/src/app/features/call-status/CallRoomName.tsx @@ -4,7 +4,7 @@ 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 { getAllParents, guessPerfectParent } from '../../utils/room/hierarchy'; import { useOrphanSpaces } from '../../state/hooks/roomList'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { allRoomsAtom } from '../../state/room-list/roomList'; diff --git a/src/app/features/call-status/LiveChip.tsx b/src/app/features/call-status/LiveChip.tsx index d9e9cc18e..944d79153 100644 --- a/src/app/features/call-status/LiveChip.tsx +++ b/src/app/features/call-status/LiveChip.tsx @@ -3,7 +3,7 @@ import { CaretDown, CaretUp, sizedIcon, userFallbackIcon } from '$components/ico import type { CallMembership } from '$types/matrix-sdk'; import type { Room } from '$types/matrix-sdk'; import * as css from './styles.css'; -import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room'; +import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room/display'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; diff --git a/src/app/features/call-status/MemberGlance.tsx b/src/app/features/call-status/MemberGlance.tsx index 1b68cecb7..c6ca70abb 100644 --- a/src/app/features/call-status/MemberGlance.tsx +++ b/src/app/features/call-status/MemberGlance.tsx @@ -3,7 +3,7 @@ import type { CallMembership } from '$types/matrix-sdk'; import type { Room } from '$types/matrix-sdk'; import { UserAvatar } from '../../components/user-avatar'; import { userFallbackIcon } from '$components/icons/phosphor'; -import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room'; +import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room/display'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; diff --git a/src/app/features/call-status/MemberSpeaking.tsx b/src/app/features/call-status/MemberSpeaking.tsx index a69a4fdcc..90034a548 100644 --- a/src/app/features/call-status/MemberSpeaking.tsx +++ b/src/app/features/call-status/MemberSpeaking.tsx @@ -1,7 +1,7 @@ import type { Room } from '$types/matrix-sdk'; import { Box, Text } from 'folds'; import { sizedIcon, Microphone } from '$components/icons/phosphor'; -import { getMemberDisplayName } from '../../utils/room'; +import { getMemberDisplayName } from '../../utils/room/display'; import { getMxIdLocalPart } from '../../utils/matrix'; type MemberSpeakingProps = { diff --git a/src/app/features/call/CallMemberCard.tsx b/src/app/features/call/CallMemberCard.tsx index f2bb7d0ee..192188476 100644 --- a/src/app/features/call/CallMemberCard.tsx +++ b/src/app/features/call/CallMemberCard.tsx @@ -12,7 +12,7 @@ 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 { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room/display'; import { useRoom } from '../../hooks/useRoom'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; import { UserAvatar } from '../../components/user-avatar'; diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx index 1317914d2..7760a1432 100644 --- a/src/app/features/call/CallView.tsx +++ b/src/app/features/call/CallView.tsx @@ -3,7 +3,7 @@ import { Badge, Box, color, Header, Scroll, Text, toRem } from 'folds'; import { useAtomValue } from 'jotai'; import { ContainerColor } from '$styles/ContainerColor.css'; import { useRoom } from '$hooks/useRoom'; -import { useCallStartCapabilities } from '$hooks/useCallStartCapabilities'; +import { useCallStartCapabilities } from './useCallStartCapabilities'; import { useCallMembers, useCallSession } from '$hooks/useCall'; import { useCallEmbed, useCallEmbedPlacementSync, useCallJoined } from '$hooks/useCallEmbed'; diff --git a/src/app/components/IncomingCallModal.css.ts b/src/app/features/call/IncomingCallModal.css.ts similarity index 100% rename from src/app/components/IncomingCallModal.css.ts rename to src/app/features/call/IncomingCallModal.css.ts diff --git a/src/app/components/IncomingCallModal.test.tsx b/src/app/features/call/IncomingCallModal.test.tsx similarity index 96% rename from src/app/components/IncomingCallModal.test.tsx rename to src/app/features/call/IncomingCallModal.test.tsx index c85c7c173..324e853c7 100644 --- a/src/app/components/IncomingCallModal.test.tsx +++ b/src/app/features/call/IncomingCallModal.test.tsx @@ -30,7 +30,7 @@ vi.mock('$hooks/useRoomMeta', () => ({ useRoomName: () => 'Direct Message', })); -vi.mock(import('$utils/room'), async (importOriginal) => ({ +vi.mock(import('$utils/room/display'), async (importOriginal) => ({ ...(await importOriginal()), getRoomAvatarUrl: () => undefined, getMemberDisplayName: () => 'Alice', @@ -46,11 +46,11 @@ vi.mock('$utils/rtc', () => ({ webRTCSupported: () => webRtcSupportedMock(), })); -vi.mock('./room-avatar', () => ({ +vi.mock('$components/room-avatar', () => ({ RoomAvatar: ({ alt }: { alt: string }) =>
{alt}
, })); -vi.mock('./user-avatar', () => ({ +vi.mock('$components/user-avatar', () => ({ UserAvatar: ({ alt }: { alt?: string }) =>
{alt}
, })); diff --git a/src/app/components/IncomingCallModal.tsx b/src/app/features/call/IncomingCallModal.tsx similarity index 98% rename from src/app/components/IncomingCallModal.tsx rename to src/app/features/call/IncomingCallModal.tsx index 807c08bda..9d212fd11 100644 --- a/src/app/components/IncomingCallModal.tsx +++ b/src/app/features/call/IncomingCallModal.tsx @@ -6,7 +6,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useRoomName } from '$hooks/useRoomMeta'; import { useCallEmbed } from '$hooks/useCallEmbed'; import { getMxIdLocalPart } from '$utils/matrix'; -import { getAvatarUrl, getMemberDisplayName, getRoomAvatarUrl } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName, getRoomAvatarUrl } from '$utils/room/display'; import { webRTCSupported } from '$utils/rtc'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import * as Sentry from '@sentry/react'; @@ -21,8 +21,8 @@ import { import { createDebugLogger } from '$utils/debugLogger'; import { dismissSystemCallNotifications } from '$features/call/callNotificationBridge'; import { getIncomingCallBlockers } from '$features/call/getIncomingCallBlockers'; -import { RoomAvatar } from './room-avatar'; -import { UserAvatar } from './user-avatar'; +import { RoomAvatar } from '$components/room-avatar'; +import { UserAvatar } from '$components/user-avatar'; import { composerIcon, menuIcon, @@ -33,7 +33,7 @@ import { User, sizedIcon, } from '$components/icons/phosphor'; -import { ModalOverlay } from './modal-overlay/ModalOverlay'; +import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import * as css from './IncomingCallModal.css'; const debugLog = createDebugLogger('IncomingCall'); diff --git a/src/app/hooks/useCallStartCapabilities.test.ts b/src/app/features/call/callStartCapabilities.test.ts similarity index 96% rename from src/app/hooks/useCallStartCapabilities.test.ts rename to src/app/features/call/callStartCapabilities.test.ts index 0f3c45b28..d7264efa0 100644 --- a/src/app/hooks/useCallStartCapabilities.test.ts +++ b/src/app/features/call/callStartCapabilities.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { Room } from '$types/matrix-sdk'; -import { evaluateCallStartCapabilities } from '$features/call/callStartCapabilities'; +import { evaluateCallStartCapabilities } from './callStartCapabilities'; const createRoom = (roomId: string, canSend = true): Room => ({ diff --git a/src/app/hooks/useCallSignaling.ts b/src/app/features/call/useCallSignaling.ts similarity index 99% rename from src/app/hooks/useCallSignaling.ts rename to src/app/features/call/useCallSignaling.ts index 084b0bebb..a652d21ab 100644 --- a/src/app/hooks/useCallSignaling.ts +++ b/src/app/features/call/useCallSignaling.ts @@ -40,8 +40,8 @@ import { } from '$features/call/callMembershipState'; import { ringtoneManager } from '$features/call/CallRingtoneManager'; import { OUTGOING_RING_TIMEOUT_MS } from '$features/call/callSignalingPolicy'; -import { useMatrixClient } from './useMatrixClient'; -import { createDebugLogger } from '../utils/debugLogger'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { createDebugLogger } from '$utils/debugLogger'; const debugLog = createDebugLogger('CallSignaling'); diff --git a/src/app/hooks/useCallStartCapabilities.ts b/src/app/features/call/useCallStartCapabilities.ts similarity index 100% rename from src/app/hooks/useCallStartCapabilities.ts rename to src/app/features/call/useCallStartCapabilities.ts diff --git a/src/app/features/common-settings/cosmetics/Cosmetics.tsx b/src/app/features/common-settings/cosmetics/Cosmetics.tsx index ffb0ffb1c..c9cc300dd 100644 --- a/src/app/features/common-settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/common-settings/cosmetics/Cosmetics.tsx @@ -1,5 +1,5 @@ import type { ChangeEvent, ChangeEventHandler, FormEventHandler } from 'react'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { Box, Text, @@ -11,7 +11,6 @@ import { config, Button, Spinner, - Modal, } from 'folds'; import { menuIcon, X } from '$components/icons/phosphor'; import { PageContent, SettingsSectionPage } from '$components/page'; @@ -35,20 +34,12 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import type { Room, RoomMember, StateEvents } from '$types/matrix-sdk'; import { Command, useCommands } from '$hooks/useCommands'; import { useCapabilities } from '$hooks/useCapabilities'; -import { useObjectURL } from '$hooks/useObjectURL'; -import type { UploadSuccess } from '$state/upload'; -import { createUploadAtom } from '$state/upload'; -import { useFilePicker } from '$hooks/useFilePicker'; -import { CompactUploadCardRenderer } from '$components/upload-card'; -import { ImageEditor } from '$components/image-editor'; -import { ModalWide } from '$styles/Modal.css'; import { NameColorEditor } from '$features/settings/account/NameColorEditor'; import { PronounEditor } from '$features/settings/account/PronounEditor'; import type { PronounSet } from '$utils/pronouns'; import { EventType } from '$types/matrix-sdk'; import { CustomStateEvent } from '$types/matrix/room'; -import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; -import { confirm } from '$components/confirm/confirm'; +import { AvatarUploadTile } from '$components/avatar-upload-tile/AvatarUploadTile'; const log = createLogger('Cosmetics'); @@ -80,45 +71,17 @@ function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSettingProp const avatarUrl = avatarMxc && (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined); - const [imageFile, setImageFile] = useState(); - const imageFileURL = useObjectURL(imageFile); - const uploadAtom = useMemo(() => { - if (imageFile) return createUploadAtom(imageFile); - return undefined; - }, [imageFile]); - - const pickFile = useFilePicker(setImageFile, false); - - const handleRemoveUpload = useCallback(() => { - setImageFile(undefined); - }, []); - const myRoomAvatar = useCommands(mx, room)[Command.MyRoomAvatar]; - const handleUploaded = useCallback( - (upload: UploadSuccess) => { - const { mxc } = upload; - myRoomAvatar.exe(mxc).finally(() => { - handleRemoveUpload(); - }); - }, - [myRoomAvatar, handleRemoveUpload] - ); - - const handleRemoveAvatar = async () => { - const ok = await confirm({ - title: 'Remove Room Avatar', - description: 'Are you sure you want to remove room avatar?', - action: 'Remove', - variant: 'Critical', - }); - if (ok) { - myRoomAvatar.exe(''); - } - }; return ( - myRoomAvatar.exe(mxc)} + onRemove={() => myRoomAvatar.exe('')} + confirmTitle="Remove Room Avatar" + confirmDescription="Are you sure you want to remove room avatar?" after={ } - > - {uploadAtom ? ( - - - - ) : ( - - - {hasRoomAvatarOverride && ( - - )} - - )} - - {imageFileURL && ( - - - - - - )} - + /> ); } diff --git a/src/app/features/common-settings/developer-tools/DevelopTools.tsx b/src/app/features/common-settings/developer-tools/DevelopTools.tsx index 1d8a925c5..cdbf5d19a 100644 --- a/src/app/features/common-settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/common-settings/developer-tools/DevelopTools.tsx @@ -24,7 +24,7 @@ import { useRoomAccountData } from '$hooks/useRoomAccountData'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { allRoomsAtom } from '$state/room-list/roomList'; import { allInvitesAtom } from '$state/room-list/inviteList'; -import { isNotificationEvent } from '$utils/room'; +import { isNotificationEvent } from '$utils/room/unread'; import { CutoutCard } from '$components/cutout-card'; import type { AccountDataSubmitCallback } from '$components/AccountDataEditor'; import { AccountDataEditor } from '$components/AccountDataEditor'; diff --git a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx index ea97427b8..fa4bfd28b 100644 --- a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx +++ b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx @@ -7,8 +7,6 @@ import { IconButton, Text, config, - Button, - Spinner, color, TextArea as TextAreaComponent, Input, @@ -20,6 +18,8 @@ import { useRoom } from '$hooks/useRoom'; import { useAlive } from '$hooks/useAlive'; import { useTextAreaCodeEditor } from '$hooks/useTextAreaCodeEditor'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { syntaxErrorPosition } from '$utils/dom'; import { Cursor } from '$plugins/text-area'; @@ -152,23 +152,21 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro required />
- + - {submitState.status === AsyncStatus.Error && ( - - {submitState.error.message} - - )} + {composeStateEvent && ( diff --git a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx index a0e563e7d..a270fa441 100644 --- a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx +++ b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx @@ -9,7 +9,6 @@ import { config, TextArea as TextAreaComponent, color, - Spinner, Button, } from 'folds'; import { ArrowLeft, composerIcon, menuIcon, X } from '$components/icons/phosphor'; @@ -24,6 +23,8 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useAlive } from '$hooks/useAlive'; import { Cursor } from '$plugins/text-area'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { syntaxErrorPosition } from '$utils/dom'; import { SettingTile } from '$components/setting-tile'; import { usePowerLevels } from '$hooks/usePowerLevels'; @@ -129,16 +130,18 @@ function StateEventEdit({ type, stateKey, content, requestClose }: StateEventEdi description={stateKey} after={ - + + @@ -334,16 +335,18 @@ export function RoomPacks({ onViewPack }: Readonly) { > Cancel - +
diff --git a/src/app/features/common-settings/general/RoomEncryption.tsx b/src/app/features/common-settings/general/RoomEncryption.tsx index 2d3f4c50f..51f823ca6 100644 --- a/src/app/features/common-settings/general/RoomEncryption.tsx +++ b/src/app/features/common-settings/general/RoomEncryption.tsx @@ -1,6 +1,6 @@ -import { Badge, Button, color, Spinner, Text } from 'folds'; +import { Badge, Text } from 'folds'; import { useCallback } from 'react'; -import type { MatrixError, StateEvents } from '$types/matrix-sdk'; +import type { StateEvents } from '$types/matrix-sdk'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -11,6 +11,8 @@ import { useStateEvent } from '$hooks/useStateEvent'; import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; import { EventType } from '$types/matrix-sdk'; import { confirm } from '$components/confirm/confirm'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; const ROOM_ENC_ALGO = 'm.megolm.v1.aes-sha2'; @@ -69,25 +71,23 @@ export function RoomEncryption({ permissions }: RoomEncryptionProps) { Enabled ) : ( - + ) } > - {enableState.status === AsyncStatus.Error && ( - - {(enableState.error as MatrixError).message} - - )} + ); diff --git a/src/app/features/common-settings/general/RoomHistoryVisibility.tsx b/src/app/features/common-settings/general/RoomHistoryVisibility.tsx index 22e9c8991..3d18097f4 100644 --- a/src/app/features/common-settings/general/RoomHistoryVisibility.tsx +++ b/src/app/features/common-settings/general/RoomHistoryVisibility.tsx @@ -1,11 +1,7 @@ import { useCallback, useMemo } from 'react'; -import { Button, color, Spinner, Text } from 'folds'; +import { Button, Spinner, Text } from 'folds'; import { CaretDown, menuIcon } from '$components/icons/phosphor'; -import type { - MatrixError, - RoomHistoryVisibilityEventContent, - StateEvents, -} from '$types/matrix-sdk'; +import type { RoomHistoryVisibilityEventContent, StateEvents } from '$types/matrix-sdk'; import { HistoryVisibility, EventType } from '$types/matrix-sdk'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; @@ -14,6 +10,7 @@ import { useRoom } from '$hooks/useRoom'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useStateEvent } from '$hooks/useStateEvent'; +import { AsyncError } from '$components/AsyncError'; import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; import { SettingMenuSelector, @@ -114,11 +111,7 @@ export function RoomHistoryVisibility({ permissions }: RoomHistoryVisibilityProp /> } > - {submitState.status === AsyncStatus.Error && ( - - {(submitState.error as MatrixError).message} - - )} + ); diff --git a/src/app/features/common-settings/general/RoomJoinRules.tsx b/src/app/features/common-settings/general/RoomJoinRules.tsx index 610a09d92..061dbcbff 100644 --- a/src/app/features/common-settings/general/RoomJoinRules.tsx +++ b/src/app/features/common-settings/general/RoomJoinRules.tsx @@ -1,6 +1,5 @@ import { useCallback, useMemo } from 'react'; -import { color, Text } from 'folds'; -import type { MatrixError, RoomJoinRulesEventContent, StateEvents } from '$types/matrix-sdk'; +import type { RoomJoinRulesEventContent, StateEvents } from '$types/matrix-sdk'; import { JoinRule, RestrictedAllowType, EventType } from '$types/matrix-sdk'; import { useAtomValue } from 'jotai'; import type { ExtendedJoinRules } from '$components/JoinRulesSwitcher'; @@ -17,7 +16,8 @@ import { useRoom } from '$hooks/useRoom'; import { useStateEvent } from '$hooks/useStateEvent'; import { useSpaceOptionally } from '$hooks/useSpace'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { getStateEvents } from '$utils/room'; +import { getStateEvents } from '$utils/room/hierarchy'; +import { AsyncError } from '$components/AsyncError'; import { useRecursiveChildSpaceScopeFactory, useSpaceChildren } from '$state/hooks/roomList'; import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToParentsAtom } from '$state/room/roomToParents'; @@ -137,11 +137,7 @@ export function RoomJoinRules({ permissions }: RoomJoinRulesProps) { /> } > - {submitState.status === AsyncStatus.Error && ( - - {(submitState.error as MatrixError).message} - - )} + ); diff --git a/src/app/features/common-settings/general/RoomProfile.tsx b/src/app/features/common-settings/general/RoomProfile.tsx index b0afb34ce..0cfe3859a 100644 --- a/src/app/features/common-settings/general/RoomProfile.tsx +++ b/src/app/features/common-settings/general/RoomProfile.tsx @@ -1,11 +1,11 @@ -import { Avatar, Box, Button, Chip, color, config, Input, Spinner, Text, TextArea } from 'folds'; +import { Avatar, Box, Button, Chip, config, Input, Text, TextArea } from 'folds'; import { ArrowsClockwise, chipIcon, menuIcon, PencilSimple } from '$components/icons/phosphor'; import type { FormEventHandler } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import Linkify from 'linkify-react'; import classNames from 'classnames'; -import type { MatrixError, StateEvents } from '$types/matrix-sdk'; +import type { StateEvents } from '$types/matrix-sdk'; import { JoinRule, EventType } from '$types/matrix-sdk'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { useRoom } from '$hooks/useRoom'; @@ -34,6 +34,8 @@ import { CustomStateEvent } from '$types/matrix/room'; import { SettingTile } from '$components/setting-tile'; import { confirm } from '$components/confirm/confirm'; import { reportMediaLoadFailure } from '$utils/mediaLoadDiagnostics'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; type RoomProfileEditProps = { canEditAvatar: boolean; @@ -259,22 +261,20 @@ function RoomProfileEdit({ readOnly={!canEditTopic || submitting} />
- {submitState.status === AsyncStatus.Error && ( - - {(submitState.error as MatrixError).message} - - )} + - + + diff --git a/src/app/features/common-settings/members/Members.tsx b/src/app/features/common-settings/members/Members.tsx index bbdb05f38..e48fbeb79 100644 --- a/src/app/features/common-settings/members/Members.tsx +++ b/src/app/features/common-settings/members/Members.tsx @@ -27,7 +27,7 @@ import { ServerBadge } from '$components/server-badge'; import { useDebounce } from '$hooks/useDebounce'; import type { SearchItemStrGetter, UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; -import { getMemberSearchStr } from '$utils/room'; +import { getMemberSearchStr } from '$utils/room/display'; import { useMembershipFilter, useMembershipFilterMenu } from '$hooks/useMemberFilter'; import { useMemberPowerSort, useMemberSort, useMemberSortMenu } from '$hooks/useMemberSort'; import { settingsAtom } from '$state/settings'; diff --git a/src/app/features/common-settings/permissions/PermissionGroups.tsx b/src/app/features/common-settings/permissions/PermissionGroups.tsx index 0afa817e4..350626762 100644 --- a/src/app/features/common-settings/permissions/PermissionGroups.tsx +++ b/src/app/features/common-settings/permissions/PermissionGroups.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; -import { Badge, Box, Button, Chip, config, Menu, Spinner, Text } from 'folds'; +import { Badge, Box, Button, Chip, config, Menu, Text } from 'folds'; +import { AsyncButton } from '$components/AsyncButton'; import { CaretDown, CaretUp, chipIcon } from '$components/icons/phosphor'; import { produce } from 'immer'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; @@ -265,16 +266,18 @@ export function PermissionGroups({ > Reset - + diff --git a/src/app/features/create-chat/CreateChat.tsx b/src/app/features/create-chat/CreateChat.tsx index a5c6693ba..28a896560 100644 --- a/src/app/features/create-chat/CreateChat.tsx +++ b/src/app/features/create-chat/CreateChat.tsx @@ -1,4 +1,5 @@ -import { Box, Button, color, config, Input, Spinner, Switch, Text } from 'folds'; +import { Box, color, config, Input, Switch, Text } from 'folds'; +import { AsyncButton } from '$components/AsyncButton'; import { sizedIcon, Warning } from '$components/icons/phosphor'; import type { FormEventHandler } from 'react'; import { useCallback, useState } from 'react'; @@ -140,16 +141,18 @@ export function CreateChat({ defaultUserId }: CreateChatProps) { )} - + Create Chat + ); diff --git a/src/app/features/create-room/CreateRoom.tsx b/src/app/features/create-room/CreateRoom.tsx index 799a30fea..6f9cdec41 100644 --- a/src/app/features/create-room/CreateRoom.tsx +++ b/src/app/features/create-room/CreateRoom.tsx @@ -2,7 +2,8 @@ import type { ReactNode, FormEventHandler } from 'react'; import { useCallback, useEffect, useState } from 'react'; import type { Room } from '$types/matrix-sdk'; import { MatrixError, JoinRule, RoomType } from '$types/matrix-sdk'; -import { Box, Button, Chip, color, config, Input, Spinner, Switch, Text, TextArea } from 'folds'; +import { Box, Chip, color, config, Input, Switch, Text, TextArea } from 'folds'; +import { AsyncButton } from '$components/AsyncButton'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -346,16 +347,18 @@ export function CreateRoomForm({ )} - + Create Room + ); diff --git a/src/app/features/create-space/CreateSpace.tsx b/src/app/features/create-space/CreateSpace.tsx index ac8e75764..c1ec08829 100644 --- a/src/app/features/create-space/CreateSpace.tsx +++ b/src/app/features/create-space/CreateSpace.tsx @@ -2,7 +2,8 @@ import type { ReactNode, FormEventHandler } from 'react'; import { useCallback, useEffect, useState } from 'react'; import type { Room } from '$types/matrix-sdk'; import { MatrixError, RoomType } from '$types/matrix-sdk'; -import { Box, Button, Chip, color, config, Input, Spinner, Switch, Text, TextArea } from 'folds'; +import { Box, Chip, color, config, Input, Switch, Text, TextArea } from 'folds'; +import { AsyncButton } from '$components/AsyncButton'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -266,16 +267,18 @@ export function CreateSpaceForm({ defaultAccess, space, onCreate }: CreateSpaceF )} - + Create Space + ); diff --git a/src/app/features/lobby/Lobby.tsx b/src/app/features/lobby/Lobby.tsx index b3664e856..4c3514f83 100644 --- a/src/app/features/lobby/Lobby.tsx +++ b/src/app/features/lobby/Lobby.tsx @@ -40,7 +40,7 @@ import { getCanonicalAliasOrRoomId, rateLimitedActions } from '$utils/matrix'; import { getSpaceRoomPath } from '$pages/pathUtils'; import { ASCIILexicalTable, orderKeys } from '$utils/ASCIILexicalTable'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { useClosedLobbyCategoriesAtom } from '$state/hooks/closedLobbyCategories'; import { makeCinnySpacesContent, diff --git a/src/app/features/lobby/RoomItem.tsx b/src/app/features/lobby/RoomItem.tsx index 6f5f14826..e8f8f8ef2 100644 --- a/src/app/features/lobby/RoomItem.tsx +++ b/src/app/features/lobby/RoomItem.tsx @@ -27,7 +27,7 @@ import { RoomTopicViewer } from '$components/room-topic-viewer'; import { onEnterOrSpace } from '$utils/keyboard'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; import { mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { formatCompactNumber } from '$utils/formatCompactNumber'; diff --git a/src/app/features/lobby/SpaceItem.tsx b/src/app/features/lobby/SpaceItem.tsx index 9d0af7fd3..081d66dc3 100644 --- a/src/app/features/lobby/SpaceItem.tsx +++ b/src/app/features/lobby/SpaceItem.tsx @@ -22,7 +22,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { RoomAvatar } from '$components/room-avatar'; import { nameInitials } from '$utils/common'; import { LocalRoomSummaryLoader } from '$components/RoomSummaryLoader'; -import { getRoomAvatarUrl } from '$utils/room'; +import { getRoomAvatarUrl } from '$utils/room/display'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; diff --git a/src/app/features/lobby/SpaceNavItem.tsx b/src/app/features/lobby/SpaceNavItem.tsx index deca187dd..8eb592718 100644 --- a/src/app/features/lobby/SpaceNavItem.tsx +++ b/src/app/features/lobby/SpaceNavItem.tsx @@ -8,7 +8,7 @@ import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import type { HierarchyItem } from '$hooks/useSpaceHierarchy'; import { LocalRoomSummaryLoader } from '$components/RoomSummaryLoader'; -import { getRoomAvatarUrl } from '$utils/room'; +import { getRoomAvatarUrl } from '$utils/room/display'; import { RoomAvatar } from '$components/room-avatar'; import { nameInitials } from '$utils/common'; import { useNavigate } from 'react-router-dom'; diff --git a/src/app/features/navigate/RoomSearch.tsx b/src/app/features/navigate/RoomSearch.tsx index b6e94578b..7ccfa74e7 100644 --- a/src/app/features/navigate/RoomSearch.tsx +++ b/src/app/features/navigate/RoomSearch.tsx @@ -29,12 +29,8 @@ import type { SearchItemStrGetter, UseAsyncSearchOptions } from '$hooks/useAsync import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; -import { - getAllParents, - getDirectRoomAvatarUrl, - getRoomAvatarUrl, - guessPerfectParent, -} from '$utils/room'; +import { getAllParents, guessPerfectParent } from '$utils/room/hierarchy'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; import { highlightText, makeHighlightRegex } from '$plugins/react-custom-html-parser'; import { factoryRoomIdByActivity } from '$utils/sort'; import { nameInitials } from '$utils/common'; diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 90ee8040e..f72828f99 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -2,7 +2,6 @@ import type { MouseEventHandler, MouseEvent } from 'react'; import { forwardRef, startTransition, useState, useEffect } from 'react'; import type { Room } from '$types/matrix-sdk'; import { RoomEvent as RoomEventEnum } from '$types/matrix-sdk'; -import type { RectCords } from 'folds'; import { Avatar, Box, @@ -10,7 +9,6 @@ import { Text, Menu, config, - PopOut, toRem, Line, Badge, @@ -19,34 +17,26 @@ import { TooltipProvider, } from 'folds'; import { useFocusWithin, useHover } from 'react-aria'; -import FocusTrap from 'focus-trap-react'; import { useAtom, useAtomValue } from 'jotai'; import { useNavigate } from 'react-router-dom'; import { NavButton, NavItem, NavItemContent, NavItemOptions } from '$components/nav'; import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl, roomHaveUnread } from '$utils/room'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; +import { roomHaveUnread } from '$utils/room/unread'; import { nameInitials } from '$utils/common'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useRoomUnread } from '$state/hooks/unread'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; -import { usePowerLevels } from '$hooks/usePowerLevels'; -import { copyToClipboard, getMouseEventCords } from '$utils/dom'; -import { markAsRead } from '$utils/notifications'; -import { confirm } from '$components/confirm/confirm'; -import { showToast } from '$state/toast'; -import { useMobileLongPress } from '$hooks/useMobileLongPress'; +import { copyToClipboard } from '$utils/dom'; +import { useMenuAnchor } from '$hooks/useMenuAnchor'; import { useRoomTypingMember } from '$hooks/useRoomTypingMembers'; import { TypingIndicator } from '$components/typing-indicator'; -import { stopPropagation } from '$utils/keyboard'; -import { getMatrixToRoom } from '$plugins/matrix-to'; -import { getCanonicalAliasOrRoomId, isRoomAlias } from '$utils/matrix'; -import { getViaServers } from '$plugins/via-servers'; + import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; -import { useOpenRoomSettings } from '$state/hooks/roomSettings'; -import { useSpaceOptionally } from '$hooks/useSpace'; + import { ChatCircleDots, Checks, @@ -60,19 +50,17 @@ import { UserPlus, } from '$components/icons/phosphor'; import { Copy as CopyIcon } from '@phosphor-icons/react'; -import { MobileSwipeDownModal } from '$components/MobileSwipeDownModal'; import { MobileMenuItem } from '$components/MobileMenuItem'; -import { type DragOptsProps } from '$components/message/modals/Options'; -import * as messageCss from '$features/room/message/styles.css'; import { RoomNotificationMode, roomNotificationModeChipIcon, roomNotificationModeIcon, } from '$hooks/useRoomsNotificationPreferences'; import { RoomNotificationModeSwitcher } from '$components/RoomNotificationSwitcher'; -import { useRoomCreators } from '$hooks/useRoomCreators'; -import { useRoomPermissions } from '$hooks/useRoomPermissions'; + import { InviteUserPrompt } from '$components/invite-user-prompt'; +import { DirectInvitePrompt } from '$components/direct-invite-prompt'; +import { AsyncStatus } from '$hooks/useAsyncCallback'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { useRoomName, useRoomTopic } from '$hooks/useRoomMeta'; import { nicknamesAtom } from '$state/nicknames'; @@ -80,6 +68,8 @@ import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { warmupRoomDecryption } from '$utils/decryptScheduler'; import { useMobileTapActivation } from '$hooks/useMobileTapActivation'; import { useOpenMobileDrawerContent } from '$components/page/MobileNavDrawerContext'; +import { ResponsiveMenu } from '$components/ResponsiveMenu'; +import { useRoomMenuActions } from '$hooks/useRoomMenuActions'; // Call Hooks & Plugins import { useCallMembers, useCallSession } from '$hooks/useCall'; @@ -119,33 +109,36 @@ type RoomNavItemMenuProps = { room: Room; requestClose: () => void; notificationMode?: RoomNotificationMode; - dragOpts?: DragOptsProps; }; const RoomNavItemMenu = forwardRef( - ({ room, requestClose, notificationMode, dragOpts }, ref) => { + ({ room, requestClose, notificationMode }, ref) => { + const { + handleMarkAsRead: hookMarkAsRead, + handleInvite: hookInvite, + handleCopyLink: hookCopyLink, + handleOpenSettings: hookOpenSettings, + handleLeaveRoom: hookLeaveRoom, + canInvite, + unread, + invitePrompt, + setInvitePrompt, + directInvitePrompt, + setDirectInvitePrompt, + handleInviteDirect, + handleConvertAndInvite, + convertState, + } = useRoomMenuActions(room); + const mx = useMatrixClient(); const isMobile = useScreenSizeContext() === ScreenSize.Mobile; - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const unread = useRoomUnread(room.roomId, roomToUnreadAtom); - const powerLevels = usePowerLevels(room); - const creators = useRoomCreators(room); - - const permissions = useRoomPermissions(creators, powerLevels); - const canInvite = permissions.action('invite', mx.getSafeUserId()); - const openRoomSettings = useOpenRoomSettings(); - const space = useSpaceOptionally(); - - const [invitePrompt, setInvitePrompt] = useState(false); const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideReads); + hookMarkAsRead(); requestClose(); }; - const handleInvite = () => { - setInvitePrompt(true); - }; + const handleInvite = hookInvite; const handleCopyName = () => { const roomName = mx.getRoom(room.roomId)?.name || 'Room'; @@ -154,44 +147,21 @@ const RoomNavItemMenu = forwardRef( }; const handleCopyLink = () => { - const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, room.roomId); - const viaServers = isRoomAlias(roomIdOrAlias) ? undefined : getViaServers(room); - copyToClipboard(getMatrixToRoom(roomIdOrAlias, viaServers)); + hookCopyLink(); requestClose(); }; const handleRoomSettings = () => { - openRoomSettings(room.roomId, space?.roomId); + hookOpenSettings(); requestClose(); }; const handleLeaveRoom = async () => { - const ok = await confirm({ - title: 'Leave Room', - description: 'Are you sure you want to leave this room?', - action: 'Leave', - variant: 'Critical', - }); - if (ok) { - try { - await mx.leave(room.roomId); - requestClose(); - } catch (e) { - showToast(`Failed to leave room: ${e instanceof Error ? e.message : 'unknown error'}`); - } - } + if (await hookLeaveRoom()) requestClose(); }; return ( - - {dragOpts?.dragHandle} + {invitePrompt && room && ( ( }} /> )} + {directInvitePrompt && ( + { + setDirectInvitePrompt(false); + requestClose(); + }} + onInviteDirect={handleInviteDirect} + onConvertAndInvite={handleConvertAndInvite} + converting={convertState.status === AsyncStatus.Loading} + convertError={ + convertState.status === AsyncStatus.Error ? convertState.error.message : undefined + } + /> + )} (); const unread = useRoomUnread(room.roomId, roomToUnreadAtom); const hasRoomUnread = useRoomHasUnread(room); @@ -380,41 +363,19 @@ export function RoomNavItem({ const isActiveCall = callEmbed?.roomId === room.roomId; - const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); + const menu = useMenuAnchor(); - const { - onTouchStart, - onTouchEnd, - onTouchMove, - onTouchCancel, - firedRef: longPressFiredRef, - isPressing, - } = useMobileLongPress(() => { - setIsMobileMenuOpen(true); - }); - - const handleContextMenu: MouseEventHandler = (evt) => { + const contextMenuHandler: MouseEventHandler = (evt) => { if (isMobile) { - if (longPressFiredRef.current) { - evt.preventDefault(); - longPressFiredRef.current = false; - return; - } evt.preventDefault(); - setIsMobileMenuOpen(true); + menu.triggerProps.onContextMenu(evt); return; } - - evt.preventDefault(); - setMenuAnchor(getMouseEventCords(evt.nativeEvent)); + menu.triggerProps.onContextMenu(evt); }; const handleOpenMenu: MouseEventHandler = (evt) => { - if (isMobile) { - setIsMobileMenuOpen(true); - } else { - setMenuAnchor(evt.currentTarget.getBoundingClientRect()); - } + menu.triggerProps.onClick(evt); }; const handleNavItemClick: MouseEventHandler = (evt) => { @@ -464,7 +425,7 @@ export function RoomNavItem({ navigate(linkPath); }; - const optionsVisible = hover || !!menuAnchor || isMobileMenuOpen; + const optionsVisible = hover || !!menu.anchor; const isMutedRoom = notificationMode === RoomNotificationMode.Mute; const shouldShowUnreadIndicator = !isMutedRoom && (!!unread || hasRoomUnread); @@ -504,8 +465,8 @@ export function RoomNavItem({ radii="400" highlight={shouldShowUnreadIndicator} aria-selected={selected} - data-hover={!!menuAnchor || isPressing} - onContextMenu={handleContextMenu} + data-hover={!!menu.anchor || menu.isPressing} + onContextMenu={contextMenuHandler} {...hoverProps} {...focusWithinProps} style={hideTextStyling(hideText)} @@ -531,10 +492,10 @@ export function RoomNavItem({ onPointerMove={mobileTapActivation.onPointerMove} onPointerUp={mobileTapActivation.onPointerUp} onPointerCancel={mobileTapActivation.onPointerCancel} - onTouchStart={onTouchStart} - onTouchEnd={onTouchEnd} - onTouchMove={onTouchMove} - onTouchCancel={onTouchCancel} + onTouchStart={menu.triggerProps.onTouchStart} + onTouchEnd={menu.triggerProps.onTouchEnd} + onTouchMove={menu.triggerProps.onTouchMove} + onTouchCancel={menu.triggerProps.onTouchCancel} aria-label={ariaLabel} ref={triggerRef} style={{ @@ -696,53 +657,24 @@ export function RoomNavItem({ )} )} - {isMobileMenuOpen && ( - setIsMobileMenuOpen(false)}> - {(dragHandleJSX, dragHandlers) => ( - setIsMobileMenuOpen(false)} - notificationMode={notificationMode} - dragOpts={{ - dragHandle: dragHandleJSX, - ...dragHandlers, - }} - /> - )} - - )} - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > - setMenuAnchor(undefined)} - notificationMode={notificationMode} - /> - + align={menu.anchor?.width === 0 ? 'Start' : 'End'} + offset={menu.anchor?.width === 0 ? 0 : undefined} + menu={ + } > {!hideText && ( {chipIcon(DotsThreeOutlineVerticalIcon, { - weight: menuAnchor ? 'fill' : 'regular', + weight: menu.anchor ? 'fill' : 'regular', })} )} - + )} diff --git a/src/app/features/room-nav/RoomNavUser.tsx b/src/app/features/room-nav/RoomNavUser.tsx index e798acffd..8854bebb0 100644 --- a/src/app/features/room-nav/RoomNavUser.tsx +++ b/src/app/features/room-nav/RoomNavUser.tsx @@ -7,7 +7,7 @@ import { NavButton, NavItem, NavItemContent } from '$components/nav'; import { UserAvatar } from '$components/user-avatar'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getMxIdLocalPart } from '$utils/matrix'; -import { getAvatarUrl, getMemberAvatarMxc, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberAvatarMxc, getMemberDisplayName } from '$utils/room/display'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useSpaceOptionally } from '$hooks/useSpace'; diff --git a/src/app/features/room-settings/RoomSettings.test.tsx b/src/app/features/room-settings/RoomSettings.test.tsx new file mode 100644 index 000000000..072fa84db --- /dev/null +++ b/src/app/features/room-settings/RoomSettings.test.tsx @@ -0,0 +1,230 @@ +import { atom as jotaiAtom } from 'jotai'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import type { ReactNode } from 'react'; +import { describe, expect, it, vi } from 'vitest'; +import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; +import { RoomSettingsPage } from '$state/roomSettings'; +import type { Room } from '$types/matrix-sdk'; +import { RoomSettings } from './RoomSettings'; + +// ── Mock room factory ── + +function createMockRoom(isSpace: boolean): Room { + return { + roomId: isSpace ? '!space:server' : '!room:server', + isSpaceRoom: () => isSpace, + getType: () => undefined, + } as unknown as Room; +} + +// ── Mutable mock globals — updated per render, referenced by hoisted vi.mock ── + +let mockRoom = createMockRoom(false); + +const mockMatrixClient = { getUserId: () => '@user:server' }; + +// ── Module mocks (vi.mock is hoisted, must reference module-scope vars) ── + +vi.mock('$hooks/useRoom', () => ({ + useRoom: () => mockRoom, +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => mockMatrixClient, +})); + +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => false, +})); + +vi.mock('$hooks/useRoomMeta', () => ({ + useRoomAvatar: () => undefined, + useRoomName: () => 'Test Room', + useRoomJoinRule: () => undefined, +})); + +vi.mock('$state/mDirectList', () => ({ + mDirectAtom: jotaiAtom(new Set()), +})); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: () => [false, vi.fn<(value: boolean) => void>()] as const, +})); + +vi.mock('$components/room-avatar', () => ({ + RoomAvatar: () => null, + RoomIcon: () => null, +})); + +// Section component mocks — each renders a div with its title text +function mkSection(title: string) { + return function MockSection({ + requestBack, + requestClose, + }: { + requestBack?: () => void; + requestClose: () => void; + }): ReactNode { + return ( +
+

{title}

+ {requestBack && ( + + )} + +
+ ); + }; +} + +vi.mock('./general', () => ({ General: mkSection('General section') })); +vi.mock('./permissions', () => ({ Permissions: mkSection('Permissions section') })); +vi.mock('$features/common-settings/members', () => ({ + Members: mkSection('Members section'), +})); +vi.mock('$features/common-settings/cosmetics/Cosmetics', () => ({ + Cosmetics: mkSection('Cosmetics section'), +})); +vi.mock('./abbreviations/RoomAbbreviations', () => ({ + RoomAbbreviations: mkSection('Abbreviations section'), +})); +vi.mock('$features/common-settings/emojis-stickers', () => ({ + EmojisStickers: mkSection('Emojis & Stickers section'), +})); +vi.mock('$features/common-settings/developer-tools', () => ({ + DeveloperTools: mkSection('Developer Tools section'), +})); +vi.mock('$features/common-settings/appearance/Appearance', () => ({ + Appearance: mkSection('Appearance section'), +})); + +// ── Render helper ── + +function renderRoomSettings({ + isSpace = false, + screenSize = ScreenSize.Desktop, + initialPage, +}: { + isSpace?: boolean; + screenSize?: ScreenSize; + initialPage?: RoomSettingsPage; +} = {}) { + mockRoom = createMockRoom(isSpace); + + const requestClose = vi.fn<() => void>(); + + render( + + + + ); + + return { requestClose }; +} + +// ── Tests ── + +describe('RoomSettings menu', () => { + it('renders expected sections for a space', () => { + renderRoomSettings({ isSpace: true }); + + const expectedLabels = [ + 'General', + 'Members', + 'Permissions', + 'Cosmetics', + 'Abbreviations', + 'Emojis & Stickers', + 'Developer Tools', + 'Appearance', + ]; + + for (const label of expectedLabels) { + expect(screen.getByRole('button', { name: label })).toBeInTheDocument(); + } + }); + + it('renders expected sections for a non-space room', () => { + renderRoomSettings({ isSpace: false }); + + const expectedLabels = [ + 'General', + 'Members', + 'Permissions', + 'Cosmetics', + 'Abbreviations', + 'Emojis & Stickers', + 'Developer Tools', + ]; + + for (const label of expectedLabels) { + expect(screen.getByRole('button', { name: label })).toBeInTheDocument(); + } + + // Appearance is gated by isSpace + expect(screen.queryByRole('button', { name: 'Appearance' })).not.toBeInTheDocument(); + }); + + it('switches active section on menu click', async () => { + const user = userEvent.setup(); + + renderRoomSettings({ isSpace: true }); + + // Desktop starts on General page + expect(screen.getByRole('heading', { name: 'General section' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Permissions' })); + + expect(screen.getByRole('heading', { name: 'Permissions section' })).toBeInTheDocument(); + }); + + it('calls setActivePage(undefined) on mobile back (not requestClose)', async () => { + const user = userEvent.setup(); + + const { requestClose } = renderRoomSettings({ + isSpace: true, + screenSize: ScreenSize.Mobile, + }); + + // On mobile, no initial page — menu is shown + expect(screen.queryByRole('heading')).not.toBeInTheDocument(); + expect(screen.getByText('Test Room')).toBeInTheDocument(); + + // Click a section to activate it + await user.click(screen.getByRole('button', { name: 'Members' })); + + // Section content appears with a Back button + expect(screen.getByRole('heading', { name: 'Members section' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument(); + + // Click Back + await user.click(screen.getByRole('button', { name: 'Back' })); + + // Menu returns — not requestClose (no close was called) + expect(requestClose).not.toHaveBeenCalled(); + expect(screen.getByText('Test Room')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'General' })).toBeInTheDocument(); + }); + + it('visible flag gates section content', () => { + // Render for a non-space room, but try to force the Appearance section + // by starting on AppearancePage. The SettingsShell's `visible !== false` + // gate should prevent the section from rendering. + renderRoomSettings({ + isSpace: false, + screenSize: ScreenSize.Desktop, + initialPage: RoomSettingsPage.AppearancePage, + }); + + // Menu still shows (no Appearance menu item) + expect(screen.queryByRole('button', { name: 'Appearance' })).not.toBeInTheDocument(); + + // Section content is empty — nothing renders because visible gate blocks it + expect(screen.queryByRole('heading')).not.toBeInTheDocument(); + }); +}); diff --git a/src/app/features/room-settings/RoomSettingsRenderer.tsx b/src/app/features/room-settings/RoomSettingsRenderer.tsx index dfba79a81..67aa4d434 100644 --- a/src/app/features/room-settings/RoomSettingsRenderer.tsx +++ b/src/app/features/room-settings/RoomSettingsRenderer.tsx @@ -1,4 +1,6 @@ -import { Modal500 } from '$components/Modal500'; +import { useRef } from 'react'; +import { Modal } from 'folds'; +import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { useCloseRoomSettings, useRoomSettingsState } from '$state/hooks/roomSettings'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import type { RoomSettingsState } from '$state/roomSettings'; @@ -16,17 +18,20 @@ function RenderSettings({ state }: RenderSettingsProps) { const getRoom = useGetRoom(allJoinedRooms); const room = getRoom(roomId); const space = spaceId && spaceId !== roomId ? getRoom(spaceId) : undefined; + const modalRef = useRef(null); if (!room) return null; return ( - - - - - - - + + + + + + + + + ); } diff --git a/src/app/features/room-settings/abbreviations/RoomAbbreviations.tsx b/src/app/features/room-settings/abbreviations/RoomAbbreviations.tsx index a6924a622..ab34677de 100644 --- a/src/app/features/room-settings/abbreviations/RoomAbbreviations.tsx +++ b/src/app/features/room-settings/abbreviations/RoomAbbreviations.tsx @@ -18,7 +18,7 @@ import { useForceUpdate } from '$hooks/useForceUpdate'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import type { MatrixError } from '$types/matrix-sdk'; import type { AbbreviationEntry, RoomAbbreviationsContent } from '$utils/abbreviations'; -import { getAllParents, getStateEvent } from '$utils/room'; +import { getAllParents, getStateEvent } from '$utils/room/hierarchy'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { CustomStateEvent } from '$types/matrix/room'; diff --git a/src/app/features/room/MembersDrawer.tsx b/src/app/features/room/MembersDrawer.tsx index 2eac49fc6..e12c497cd 100644 --- a/src/app/features/room/MembersDrawer.tsx +++ b/src/app/features/room/MembersDrawer.tsx @@ -28,7 +28,7 @@ import type { SearchItemStrGetter, UseAsyncSearchOptions } from '$hooks/useAsync import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { useDebounce } from '$hooks/useDebounce'; import { TypingIndicator } from '$components/typing-indicator'; -import { getAvatarUrl, getMemberDisplayName, getMemberSearchStr } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName, getMemberSearchStr } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useSetSetting, useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index cbcae8035..5c9452856 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -112,7 +112,7 @@ import { useSetting } from '$state/hooks/settings'; import type { EditorButtonId } from '$state/settings'; import { settingsAtom } from '$state/settings'; import { matchesShortcut } from '../../keyboard/shortcuts'; -import { getEditedEvent, getMentionContent, getThreadReplyEvents } from '$utils/room'; +import { getEditedEvent, getMentionContent, getThreadReplyEvents } from '$utils/room/relations'; import { buildReplacementContent } from './buildReplacementContent'; import { htmlToMarkdown } from '$plugins/markdown'; import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands'; diff --git a/src/app/features/room/RoomMenu.tsx b/src/app/features/room/RoomMenu.tsx new file mode 100644 index 000000000..0ced7f4e4 --- /dev/null +++ b/src/app/features/room/RoomMenu.tsx @@ -0,0 +1,205 @@ +import { forwardRef } from 'react'; +import { Box, Text, Menu, MenuItem, toRem, config, Line, Spinner } from 'folds'; +import type { Room } from '$types/matrix-sdk'; + +import { + Checks, + ClockCounterClockwise, + GearSix, + Link, + menuIcon, + SignOut, + UserPlus, +} from '$components/icons/phosphor'; +import { UseStateProvider } from '$components/UseStateProvider'; +import { InviteUserPrompt } from '$components/invite-user-prompt'; +import { DirectInvitePrompt } from '$components/direct-invite-prompt'; +import { + getRoomNotificationMode, + roomNotificationModeIcon, + useRoomsNotificationPreferencesContext, +} from '$hooks/useRoomsNotificationPreferences'; +import { RoomNotificationModeSwitcher } from '$components/RoomNotificationSwitcher'; +import { AsyncStatus } from '$hooks/useAsyncCallback'; +import { JumpToTime } from './jump-to-time'; +import { useRoomMenuActions } from '$hooks/useRoomMenuActions'; + +type RoomMenuProps = { + room: Room; + requestClose: () => void; +}; + +const RoomMenu = forwardRef(({ room, requestClose }, ref) => { + const { + handleMarkAsRead, + handleInvite, + handleCopyLink, + handleOpenSettings, + handleLeaveRoom, + canInvite, + unread, + invitePrompt, + setInvitePrompt, + directInvitePrompt, + setDirectInvitePrompt, + handleInviteDirect, + handleConvertAndInvite, + convertState, + navigateRoom, + } = useRoomMenuActions(room); + + const notificationPreferences = useRoomsNotificationPreferencesContext(); + const notificationMode = getRoomNotificationMode(notificationPreferences, room.roomId); + + const wrappedClose = (reason: string) => () => { + if (reason === 'invite') setInvitePrompt(false); + if (reason === 'directInvite') setDirectInvitePrompt(false); + requestClose(); + }; + + return ( + + {invitePrompt && } + {directInvitePrompt && ( + + )} + + { + handleMarkAsRead(); + requestClose(); + }} + size="300" + after={menuIcon(Checks)} + radii="300" + disabled={!unread} + > + + Mark as Read + + + + {(handleOpen, opened, changing) => ( + + ) : ( + roomNotificationModeIcon(notificationMode) + ) + } + radii="300" + aria-pressed={opened} + onClick={handleOpen} + > + + Notifications + + + )} + + + + + { + handleInvite(); + }} + variant="Primary" + fill="None" + size="300" + after={menuIcon(UserPlus)} + radii="300" + aria-pressed={invitePrompt} + disabled={!canInvite} + > + + Invite + + + { + handleCopyLink(); + requestClose(); + }} + size="300" + after={menuIcon(Link)} + radii="300" + > + + Copy Link + + + { + handleOpenSettings(); + requestClose(); + }} + size="300" + after={menuIcon(GearSix)} + radii="300" + > + + Room Settings + + + + {(promptJump, setPromptJump) => ( + <> + setPromptJump(true)} + size="300" + after={menuIcon(ClockCounterClockwise)} + radii="300" + aria-pressed={promptJump} + > + + Jump to Time + + + {promptJump && ( + { + setPromptJump(false); + navigateRoom(room.roomId, eventId); + requestClose(); + }} + onCancel={() => setPromptJump(false)} + /> + )} + + )} + + + + + { + if (await handleLeaveRoom()) requestClose(); + }} + variant="Critical" + fill="None" + size="300" + after={menuIcon(SignOut)} + radii="300" + > + + Leave Room + + + + + ); +}); +RoomMenu.displayName = 'RoomMenu'; + +export { RoomMenu }; diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 9434daae4..50b50c829 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -27,13 +27,6 @@ import { useMessageEdit } from '$hooks/useMessageEdit'; import { useDocumentFocusChange } from '$hooks/useDocumentFocusChange'; import { useIsInactivePanel } from '$hooks/useRoom'; import { markAsRead } from '$utils/notifications'; -import { - getReactCustomHtmlParser, - LINKIFY_OPTS, - makeMentionCustomProps, - renderMatrixMention, - factoryRenderLinkifyWithMention, -} from '$plugins/react-custom-html-parser'; import { today, yesterday, timeDayMonthYear } from '$utils/time'; import { unwrapRelationJumpTarget, @@ -44,27 +37,16 @@ import { isThreadRelationEvent, getRedactionTargetEvent, shouldShowRedactionTimelineEvent, -} from '$utils/room'; -import { useMemberEventParser } from '$hooks/useMemberEventParser'; -import { usePowerLevelsContext } from '$hooks/usePowerLevels'; -import { useRoomCreators } from '$hooks/useRoomCreators'; -import { useRoomPermissions } from '$hooks/useRoomPermissions'; -import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; +} from '$utils/room/relations'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useSlidingSyncRoomLoading } from '$hooks/useSlidingSyncActiveRoom'; -import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; -import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; -import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useSpaceOptionally } from '$hooks/useSpace'; -import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { useImagePackRooms } from '$hooks/useImagePackRooms'; import { settingsAtom, MessageLayout, type MessageSpacing } from '$state/settings'; -import { useHiddenEventSettings, useSetting } from '$state/hooks/settings'; +import { useSetting } from '$state/hooks/settings'; import { nicknamesAtom } from '$state/nicknames'; -import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations'; -import { buildAbbrReplaceTextNode } from '$components/message/RenderBody'; import { profilesCacheAtom } from '$state/userRoomProfile'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts'; @@ -85,6 +67,7 @@ import { type ProcessedEvent, } from '$hooks/timeline/useProcessedTimeline'; import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; +import { useTimelineRendererContext } from '$hooks/timeline/useTimelineRendererContext'; import { TimelineScrollingProvider, useScrollActivity } from '$hooks/useTimelineScrollActivity'; import * as css from './RoomTimeline.css'; @@ -336,85 +319,39 @@ export function RoomTimeline({ const { navigateRoom } = useRoomNavigate(); const isInactivePanel = useIsInactivePanel(); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const [messageLayout] = useSetting(settingsAtom, 'messageLayout'); - const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); - const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents'); - const [hideNickAvatarEvents] = useSetting(settingsAtom, 'hideNickAvatarEvents'); - const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); - const [showBundledPreview] = useSetting(settingsAtom, 'bundledPreview'); - const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); - const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview'); - const [clientUrlPreview] = useSetting(settingsAtom, 'clientUrlPreview'); - const [encClientUrlPreview] = useSetting(settingsAtom, 'encClientUrlPreview'); - const hiddenEvents = useHiddenEventSettings(settingsAtom); - const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); + // Shared renderer context — replaces 17+ inline useSetting calls, linkifyOpts, + // htmlReactParserOptions, and the permissions block that were duplicated with + // ThreadDrawer character-for-character. + const rendererCtx = useTimelineRendererContext(room); + + // RoomTimeline keeps these 3 extra settings inline: + // - hideMembershipEvents & hideNickAvatarEvents → already in rendererCtx.settings + // - reducedMotion → used only for scroll logic, NOT passed to the event renderer const [reducedMotion] = useSetting(settingsAtom, 'reducedMotion'); - const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); - const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); - const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); - const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); - const [incomingInlineImagesDefaultHeight] = useSetting( - settingsAtom, - 'incomingInlineImagesDefaultHeight' - ); - const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); - const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); - const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap'); - const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap'); - const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap; - - const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; - const showClientUrlPreview = room.hasEncryptionStateEvent() - ? clientUrlPreview && encClientUrlPreview - : clientUrlPreview; - - const powerLevels = usePowerLevelsContext(); - const creators = useRoomCreators(room); - const permissions = useRoomPermissions(creators, powerLevels); - const isReadOnly = !permissions.message(room.hasEncryptionStateEvent(), mx.getSafeUserId()); - - const settings = useMemo( - () => ({ - messageLayout, - messageSpacing, - hideReads, - showDeveloperTools, - hour24Clock, - dateFormatString, - mediaAutoLoad, - showBundledPreview, - showUrlPreview, - showClientUrlPreview, - showMaps, - autoplayStickers, - hideMemberInReadOnly, + // Destructure what we need from the shared context + const { + settings, + linkifyOpts, + htmlReactParserOptions, + permissions: { + canRedact, + canDeleteOwn, + canSendReaction, + canPinEvent, isReadOnly, - hideMembershipEvents, - hideNickAvatarEvents, - hiddenEvents, - }), - [ - messageLayout, - messageSpacing, - hideReads, - showDeveloperTools, - hour24Clock, - dateFormatString, - mediaAutoLoad, - showBundledPreview, - showUrlPreview, - showClientUrlPreview, - showMaps, - autoplayStickers, - hideMemberInReadOnly, - isReadOnly, - hideMembershipEvents, - hideNickAvatarEvents, - hiddenEvents, - ] - ); + getMemberPowerTag, + parseMemberEvent, + }, + } = rendererCtx; + + const hiddenEvents = settings.hiddenEvents; + const messageLayout = settings.messageLayout; + const messageSpacing = settings.messageSpacing; + const hideReads = settings.hideReads; + const hideMembershipEvents = settings.hideMembershipEvents; + const hideNickAvatarEvents = settings.hideNickAvatarEvents; + const hideMemberInReadOnly = settings.hideMemberInReadOnly; const nicknames = useAtomValue(nicknamesAtom); const jotaiStore = useStore(); @@ -425,7 +362,6 @@ export function RoomTimeline({ const ignoredUsersList = useIgnoredUsers(); const ignoredUsersSet = useMemo(() => new Set(ignoredUsersList), [ignoredUsersList]); - const getMemberPowerTag = useGetMemberPowerTag(room, creators, powerLevels); const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true)); const readUptoEventIdRef = useRef(undefined); @@ -436,16 +372,11 @@ export function RoomTimeline({ const prevViewportHeightRef = useRef(0); const messageListRef = useRef(null); - const mediaAuthentication = useMediaAuthentication(); - const spoilerClickHandler = useSpoilerClickHandler(); - const mentionClickHandler = useMentionClickHandler(room.roomId); - const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const openUserRoomProfile = useOpenUserRoomProfile(); const optionalSpace = useSpaceOptionally(); const roomParents = useAtomValue(roomToParentsAtom); const imagePackRooms = useImagePackRooms(room.roomId, roomParents); const pushProcessor = mx.pushProcessor; - const parseMemberEvent = useMemberEventParser(); const replyDraftAtom = useMemo(() => roomIdToReplyDraftAtomFamily(room.roomId), [room.roomId]); const activeReplyDraft = useAtomValue(replyDraftAtom); @@ -879,57 +810,6 @@ export function RoomTimeline({ }, }); - const linkifyOpts = useMemo( - () => ({ - ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention( - settingsLinkBaseUrl, - (href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ), - mentionClickHandler - ), - }), - [mx, room.roomId, mentionClickHandler, nicknames, settingsLinkBaseUrl] - ); - - const abbrMap = useRoomAbbreviationsContext(); - - const htmlReactParserOptions = useMemo( - () => - getReactCustomHtmlParser(mx, room.roomId, { - settingsLinkBaseUrl, - linkifyOpts, - useAuthentication: mediaAuthentication, - handleSpoilerClick: spoilerClickHandler, - handleMentionClick: mentionClickHandler, - nicknames, - autoplayEmojis, - incomingInlineImagesDefaultHeight, - incomingInlineImagesMaxHeight, - replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts), - }), - [ - mx, - room.roomId, - linkifyOpts, - autoplayEmojis, - incomingInlineImagesDefaultHeight, - incomingInlineImagesMaxHeight, - mentionClickHandler, - nicknames, - mediaAuthentication, - spoilerClickHandler, - settingsLinkBaseUrl, - abbrMap, - ] - ); - const renderMatrixEvent = useTimelineEventRenderer({ room, mx, @@ -940,10 +820,10 @@ export function RoomTimeline({ settings, state: { focusItem: timelineSync.focusItem, editId, activeReplyId, openThreadId }, permissions: { - canRedact: permissions.action('redact', mx.getSafeUserId()), - canDeleteOwn: permissions.event('m.room.redaction', mx.getSafeUserId()), - canSendReaction: permissions.event('m.reaction', mx.getSafeUserId()), - canPinEvent: permissions.stateEvent('m.room.pinned_events', mx.getSafeUserId()), + canRedact, + canDeleteOwn, + canSendReaction, + canPinEvent, }, callbacks: { onUserClick: actions.handleUserClick, @@ -1266,7 +1146,7 @@ export function RoomTimeline({ room={room} messageLayout={messageLayout} messageSpacing={messageSpacing} - settings={settings} + settings={settings as unknown as Record} renderMatrixEvent={renderMatrixEvent} focusItem={timelineSync.focusItem} editId={editId} diff --git a/src/app/features/room/RoomTombstone.tsx b/src/app/features/room/RoomTombstone.tsx index 0979b8acf..45f662514 100644 --- a/src/app/features/room/RoomTombstone.tsx +++ b/src/app/features/room/RoomTombstone.tsx @@ -1,8 +1,10 @@ import { useCallback } from 'react'; -import { Box, Button, Spinner, Text, color } from 'folds'; +import { Box, Button, Text } from 'folds'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { getViaServers } from '$plugins/via-servers'; @@ -35,11 +37,7 @@ export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstone {body || 'This room has been replaced and is no longer active.'} - {joinState.status === AsyncStatus.Error && ( - - {(joinState.error as Error)?.message ?? 'Failed to join replacement room!'} - - )} + {replacementRoom?.getMyMembership() === KnownMembership.Join || @@ -48,21 +46,19 @@ export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstone Open New Room ) : ( - + )} diff --git a/src/app/features/room/RoomViewFollowing.tsx b/src/app/features/room/RoomViewFollowing.tsx index 280304d34..70b6ca6b3 100644 --- a/src/app/features/room/RoomViewFollowing.tsx +++ b/src/app/features/room/RoomViewFollowing.tsx @@ -5,7 +5,7 @@ import type { Room } from '$types/matrix-sdk'; import classNames from 'classnames'; import { useAtom } from 'jotai'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useRoomLatestRenderedEvent } from '$hooks/useRoomLatestRenderedEvent'; @@ -19,7 +19,7 @@ export function RoomViewFollowingPlaceholder() { return
; } -export type RoomViewFollowingProps = { +type RoomViewFollowingProps = { room: Room; threadEventId?: string; participantIds?: Set; diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index b8b76b264..ff4093b24 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -1,24 +1,10 @@ -import type { MouseEventHandler, ReactNode } from 'react'; -import { forwardRef, useCallback, useEffect, useState } from 'react'; -import { useAtom, useAtomValue } from 'jotai'; +import type { MouseEventHandler } from 'react'; +import { useEffect, useState } from 'react'; +import { useAtom } from 'jotai'; import classNames from 'classnames'; -import { - Box, - Avatar, - Text, - IconButton, - Tooltip, - TooltipProvider, - Menu, - MenuItem, - toRem, - config, - Line, - Badge, - Spinner, -} from 'folds'; +import { Box, Avatar, Text, IconButton, Tooltip, TooltipProvider, toRem, Badge } from 'folds'; import { useNavigate } from 'react-router-dom'; -import type { Room, MatrixEvent } from '$types/matrix-sdk'; +import type { MatrixEvent } from '$types/matrix-sdk'; import { Direction, type EventTimeline, @@ -33,20 +19,13 @@ import { PageHeader } from '$components/page'; import { ArrowLeft, ChatCircleDots, - Checks, Chats, - ClockCounterClockwise, composerIcon, DotsThreeOutlineVerticalIcon, - GearSix, GridFour, - Link, MagnifyingGlass, - menuIcon, PushPin, - SignOut, UserCircle, - UserPlus, } from '$components/icons/phosphor'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; import { UseStateProvider } from '$components/UseStateProvider'; @@ -59,56 +38,25 @@ import { settingsAtom } from '$state/settings'; import { useSpaceOptionally } from '$hooks/useSpace'; import { getHomeSearchPath, getSpaceSearchPath, withSearchParam } from '$pages/pathUtils'; import { createLogger } from '$utils/debug'; -import { - getCanonicalAliasOrRoomId, - isRoomAlias, - mxcUrlToHttp, - removeRoomIdFromMDirect, -} from '$utils/matrix'; +import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { type SearchPathSearchParams } from '$pages/paths'; -import { useRoomUnread } from '$state/hooks/unread'; -import { usePowerLevelsContext } from '$hooks/usePowerLevels'; -import { markAsRead } from '$utils/notifications'; -import { roomToUnreadAtom } from '$state/room/roomToUnread'; -import { copyToClipboard } from '$utils/dom'; -import { confirm } from '$components/confirm/confirm'; -import { showToast } from '$state/toast'; import { useRoomAvatar, useRoomName, useRoomTopic } from '$hooks/useRoomMeta'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { ResponsiveMenu } from '$components/ResponsiveMenu'; import { useMenuAnchor } from '$hooks/useMenuAnchor'; -import { type DragOptsProps } from '$components/message/modals/Options'; -import * as messageCss from '$features/room/message/styles.css'; -import { getMatrixToRoom } from '$plugins/matrix-to'; -import { getViaServers } from '$plugins/via-servers'; import { BackRouteHandler } from '$components/BackRouteHandler'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useRoomPinnedEvents } from '$hooks/useRoomPinnedEvents'; import { useOpenRoomSettings } from '$state/hooks/roomSettings'; -import { RoomNotificationModeSwitcher } from '$components/RoomNotificationSwitcher'; -import { - getRoomNotificationMode, - roomNotificationModeIcon, - useRoomsNotificationPreferencesContext, -} from '$hooks/useRoomsNotificationPreferences'; -import { useRoomNavigate } from '$hooks/useRoomNavigate'; -import { useRoomCreators } from '$hooks/useRoomCreators'; -import { useRoomPermissions } from '$hooks/useRoomPermissions'; -import { InviteUserPrompt } from '$components/invite-user-prompt'; import { ContainerColor } from '$styles/ContainerColor.css'; import { useRoomWidgets } from '$hooks/useRoomWidgets'; -import { hasThreadRootAggregation, isThreadRelationEvent } from '$utils/room'; - -import { DirectInvitePrompt } from '$components/direct-invite-prompt'; -import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { mDirectAtom } from '$state/mDirectList'; +import { hasThreadRootAggregation, isThreadRelationEvent } from '$utils/room/relations'; import { callChatAtom } from '$state/callEmbed'; import { RoomSettingsPage } from '$state/roomSettings'; import { roomIdToThreadBrowserAtomFamily } from '$state/room/roomToThreadBrowser'; import { roomIdToOpenThreadAtomFamily } from '$state/room/roomToOpenThread'; import { useCallPreferences } from '$state/hooks/callPreferences'; -import { useCallStartCapabilities } from '$hooks/useCallStartCapabilities'; -import { JumpToTime } from './jump-to-time'; +import { useCallStartCapabilities } from '$features/call/useCallStartCapabilities'; import { RoomPinMenu } from './room-pin-menu'; import * as css from './RoomViewHeader.css'; import { RoomCallButton } from './RoomCallButton'; @@ -133,239 +81,7 @@ export interface PinReadMarker { last_seen_id: string; } -export type RoomMenuProps = { - room: Room; - requestClose: () => void; - dragOpts?: DragOptsProps; -}; - -const RoomMenu = forwardRef( - ({ room, requestClose, dragOpts }, ref) => { - const mx = useMatrixClient(); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const unread = useRoomUnread(room.roomId, roomToUnreadAtom); - const powerLevels = usePowerLevelsContext(); - const creators = useRoomCreators(room); - - const permissions = useRoomPermissions(creators, powerLevels); - const canInvite = permissions.action('invite', mx.getSafeUserId()); - const mDirects = useAtomValue(mDirectAtom); - const isDirectConversation = mDirects.has(room.roomId); - const notificationPreferences = useRoomsNotificationPreferencesContext(); - const notificationMode = getRoomNotificationMode(notificationPreferences, room.roomId); - const { navigateRoom } = useRoomNavigate(); - - const [invitePrompt, setInvitePrompt] = useState(false); - const [directInvitePrompt, setDirectInvitePrompt] = useState(false); - - const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideReads); - requestClose(); - }; - - const handleInvite = () => { - if (isDirectConversation) { - setDirectInvitePrompt(true); - return; - } - setInvitePrompt(true); - }; - - const handleInviteDirect = () => { - setDirectInvitePrompt(false); - setInvitePrompt(true); - }; - - const [convertState, convertToRoom] = useAsyncCallback( - useCallback(async () => { - await removeRoomIdFromMDirect(mx, room.roomId); - }, [mx, room.roomId]) - ); - - const handleConvertAndInvite = () => { - if (convertState.status === AsyncStatus.Loading) return; - convertToRoom().catch(() => {}); - }; - - useEffect(() => { - if (convertState.status === AsyncStatus.Success) { - setDirectInvitePrompt(false); - setInvitePrompt(true); - } - }, [convertState.status]); - - const handleCopyLink = () => { - const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, room.roomId); - const viaServers = isRoomAlias(roomIdOrAlias) ? undefined : getViaServers(room); - copyToClipboard(getMatrixToRoom(roomIdOrAlias, viaServers)); - requestClose(); - }; - - const openSettings = useOpenRoomSettings(); - const parentSpace = useSpaceOptionally(); - const handleOpenSettings = () => { - openSettings(room.roomId, parentSpace?.roomId); - requestClose(); - }; - - const handleLeaveRoom = async () => { - const ok = await confirm({ - title: 'Leave Room', - description: 'Are you sure you want to leave this room?', - action: 'Leave', - variant: 'Critical', - }); - if (ok) { - try { - await mx.leave(room.roomId); - requestClose(); - } catch (e) { - showToast(`Failed to leave room: ${e instanceof Error ? e.message : 'unknown error'}`); - } - } - }; - - return ( - - {dragOpts?.dragHandle} - {invitePrompt && ( - { - setInvitePrompt(false); - requestClose(); - }} - /> - )} - {directInvitePrompt && ( - { - setDirectInvitePrompt(false); - requestClose(); - }} - onInviteDirect={handleInviteDirect} - onConvertAndInvite={handleConvertAndInvite} - converting={convertState.status === AsyncStatus.Loading} - convertError={ - convertState.status === AsyncStatus.Error ? convertState.error.message : undefined - } - /> - )} - - - - Mark as Read - - - - {(handleOpen, opened, changing) => ( - - ) : ( - roomNotificationModeIcon(notificationMode) - ) - } - radii="300" - aria-pressed={opened} - onClick={handleOpen} - > - - Notifications - - - )} - - - - - - - Invite - - - - - Copy Link - - - - - Room Settings - - - - {(promptJump, setPromptJump) => ( - <> - setPromptJump(true)} - size="300" - after={menuIcon(ClockCounterClockwise)} - radii="300" - aria-pressed={promptJump} - > - - Jump to Time - - - {promptJump && ( - { - setPromptJump(false); - navigateRoom(room.roomId, eventId); - requestClose(); - }} - onCancel={() => setPromptJump(false)} - /> - )} - - )} - - - - - - - Leave Room - - - - - ); - } -); -RoomMenu.displayName = 'RoomMenu'; +import { RoomMenu } from './RoomMenu'; export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { const navigate = useNavigate(); @@ -611,17 +327,6 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { setPeopleDrawer(!peopleDrawer); }; - const renderOptionsMenu = ( - dragHandle: ReactNode, - dragHandlers: Required> | undefined - ) => ( - - ); - return ( @@ -914,7 +619,7 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { requestClose={optionsMenu.close} position="Bottom" align="End" - menu={renderOptionsMenu} + menu={} > ( diff --git a/src/app/features/room/ThreadBrowser.tsx b/src/app/features/room/ThreadBrowser.tsx index 7c53e6885..b7d9e0e84 100644 --- a/src/app/features/room/ThreadBrowser.tsx +++ b/src/app/features/room/ThreadBrowser.tsx @@ -9,7 +9,8 @@ import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { nicknamesAtom } from '$state/nicknames'; import { profilesCacheAtom } from '$state/userRoomProfile'; import { useRoomMemberHydration } from '$hooks/useRoomMemberHydration'; -import { getMemberDisplayName, reactionOrEditEvent } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; +import { reactionOrEditEvent } from '$utils/room/relations'; import { getMxIdLocalPart } from '$utils/matrix'; import { Chats, chipIcon, composerIcon, MagnifyingGlass, X } from '$components/icons/phosphor'; import { settingsAtom } from '$state/settings'; @@ -19,6 +20,7 @@ import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; import * as css from './ThreadDrawer.css'; import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; import { mobileOrTablet } from '$utils/user-agent'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; type ThreadPreviewProps = { room: Room; @@ -45,15 +47,13 @@ function ThreadPreview({ room, thread, onClick, onJump }: ThreadPreviewProps) { ); const [, forceUnread] = useState(0); - useEffect(() => { - const onUnread = (_count: unknown, threadId?: string) => { + const onUnread = useCallback( + (_count: unknown, threadId?: string) => { if (!threadId || threadId === thread.id) forceUnread((n) => n + 1); - }; - room.on(RoomEvent.UnreadNotifications, onUnread); - return () => { - room.off(RoomEvent.UnreadNotifications, onUnread); - }; - }, [room, thread.id]); + }, + [thread.id] + ); + useMatrixEvent(room, RoomEvent.UnreadNotifications, onUnread); const unreadTotal = room.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total); const unreadHighlight = room.getThreadUnreadNotificationCount( thread.id, diff --git a/src/app/features/room/ThreadDrawer.test.ts b/src/app/features/room/ThreadDrawer.test.ts index e37ec33f6..62f224eab 100644 --- a/src/app/features/room/ThreadDrawer.test.ts +++ b/src/app/features/room/ThreadDrawer.test.ts @@ -14,7 +14,7 @@ import { describe, it, expect } from 'vitest'; import { RelationType } from '$types/matrix-sdk'; -import { getThreadReplyEvents } from '$utils/room'; +import { getThreadReplyEvents } from '$utils/room/relations'; // ── Minimal MatrixEvent factory ─────────────────────────────────────────────── diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 514a4ed93..371fc44c1 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -1,69 +1,39 @@ -import type { MouseEventHandler } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Header, IconButton, Scroll, Spinner, Text, config, toRem } from 'folds'; import { Chats, composerIcon, X } from '$components/icons/phosphor'; import type { IEvent, Room, CryptoBackend } from '$types/matrix-sdk'; import { Direction, - EventStatus, MatrixEvent, MatrixEventEvent, ReceiptType, - RelationType, RoomEvent, ThreadEvent, - EventType, } from '$types/matrix-sdk'; import { useSpaceOptionally } from '$hooks/useSpace'; -import { buildCachedProfilePayload } from '$hooks/timeline/useTimelineActions'; +import { useTimelineActions } from '$hooks/timeline/useTimelineActions'; +import { useTimelineRendererContext } from '$hooks/timeline/useTimelineRendererContext'; import { useAtomValue, useSetAtom, useStore } from 'jotai'; -import { ReactEditor } from 'slate-react'; -import type { HTMLReactParserOptions } from 'html-react-parser'; -import type { Opts as LinkifyOpts } from 'linkifyjs'; import { - factoryRenderLinkifyWithMention, - getReactCustomHtmlParser, - LINKIFY_OPTS, - makeMentionCustomProps, - renderMatrixMention, -} from '$plugins/react-custom-html-parser'; -import { - extractReplyDraftBody, - getMemberDisplayName, getThreadReplyEvents, isThreadRelationEvent, reactionOrEditEvent, - resolveReplyDraftTarget, unwrapRelationJumpTarget, getEditedEvent, getEventReactions, -} from '$utils/room'; -import { getMxIdLocalPart, toggleReaction } from '$utils/matrix'; +} from '$utils/room/relations'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useIsInactivePanel } from '$hooks/useRoom'; -import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; -import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { nicknamesAtom } from '$state/nicknames'; import { profilesCacheAtom } from '$state/userRoomProfile'; import { settingsAtom } from '$state/settings'; -import { useHiddenEventSettings, useSetting } from '$state/hooks/settings'; -import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations'; -import { buildAbbrReplaceTextNode } from '$components/message/RenderBody'; -import { createMentionElement, moveCursor, useEditor } from '$components/editor'; -import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; -import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; - -import { usePowerLevelsContext } from '$hooks/usePowerLevels'; -import { useRoomPermissions } from '$hooks/useRoomPermissions'; -import { useRoomCreators } from '$hooks/useRoomCreators'; +import { useSetting } from '$state/hooks/settings'; +import { useEditor } from '$components/editor'; import { useImagePackRooms } from '$hooks/useImagePackRooms'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; -import type { IReplyDraft } from '$state/room/roomInputDrafts'; import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; -import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; -import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { useMessageEdit } from '$hooks/useMessageEdit'; import { useProcessedTimeline, @@ -106,105 +76,45 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra [jotaiStore] ); const pushProcessor = mx.pushProcessor; - const useAuthentication = useMediaAuthentication(); - const mentionClickHandler = useMentionClickHandler(room.roomId); - const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); - const spoilerClickHandler = useSpoilerClickHandler(); const isInactivePanel = useIsInactivePanel(); - // Settings - const [messageLayout] = useSetting(settingsAtom, 'messageLayout'); - const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); - const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); - const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); - const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); - const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); - const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview'); - const [clientUrlPreview] = useSetting(settingsAtom, 'clientUrlPreview'); - const [encClientUrlPreview] = useSetting(settingsAtom, 'encClientUrlPreview'); - const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); - const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); - const hiddenEvents = useHiddenEventSettings(settingsAtom); - const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); - const [showBundledPreview] = useSetting(settingsAtom, 'bundledPreview'); - const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; - const showClientUrlPreview = room.hasEncryptionStateEvent() - ? clientUrlPreview && encClientUrlPreview - : clientUrlPreview; - const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap'); - const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap'); - const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap; - const [incomingInlineImagesDefaultHeight] = useSetting( - settingsAtom, - 'incomingInlineImagesDefaultHeight' - ); - const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); + // Shared renderer context — replaces 17+ inline useSetting calls, + // linkifyOpts useMemo, htmlReactParserOptions useMemo, and the + // permissions block that were duplicated with RoomTimeline. + const rendererCtx = useTimelineRendererContext(room); - // Memoized parsing options - const linkifyOpts = useMemo( + const { + settings, + linkifyOpts, + htmlReactParserOptions, + permissions: { + canRedact, + canDeleteOwn, + canSendReaction, + canPinEvent, + isReadOnly, + getMemberPowerTag, + parseMemberEvent, + }, + } = rendererCtx; + + // ThreadDrawer overrides on top of the shared settings: + // - hideThreadChip: true (thread replies don't show a nested thread chip) + // - hideMembershipEvents: true (thread view never shows membership) + // - hideNickAvatarEvents: true (thread view never shows nick changes) + const threadSettings = useMemo( () => ({ - ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention( - settingsLinkBaseUrl, - (href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ), - mentionClickHandler - ), + ...settings, + hideThreadChip: true as const, + hideMembershipEvents: true, + hideNickAvatarEvents: true, }), - [mx, room, mentionClickHandler, nicknames, settingsLinkBaseUrl] + [settings] ); - const abbrMap = useRoomAbbreviationsContext(); - - const htmlReactParserOptions = useMemo( - () => - getReactCustomHtmlParser(mx, room.roomId, { - settingsLinkBaseUrl, - linkifyOpts, - useAuthentication, - handleSpoilerClick: spoilerClickHandler, - handleMentionClick: mentionClickHandler, - nicknames, - autoplayEmojis, - incomingInlineImagesDefaultHeight, - incomingInlineImagesMaxHeight, - replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts), - }), - [ - mx, - room, - linkifyOpts, - spoilerClickHandler, - mentionClickHandler, - useAuthentication, - nicknames, - settingsLinkBaseUrl, - autoplayEmojis, - incomingInlineImagesDefaultHeight, - incomingInlineImagesMaxHeight, - abbrMap, - ] - ); - - // Power levels & permissions - const powerLevels = usePowerLevelsContext(); - const creators = useRoomCreators(room); - const permissions = useRoomPermissions(creators, powerLevels); - const canRedact = permissions.action('redact', mx.getSafeUserId()); - const canDeleteOwn = permissions.event(EventType.RoomRedaction, mx.getSafeUserId()); - const canSendReaction = permissions.event(EventType.Reaction, mx.getSafeUserId()); - const canPinEvent = permissions.stateEvent(EventType.RoomPinnedEvents, mx.getSafeUserId()); - const isReadOnly = !permissions.message(room.hasEncryptionStateEvent(), mx.getSafeUserId()); - const getMemberPowerTag = useGetMemberPowerTag(room, creators, powerLevels); - const parseMemberEvent = useMemberEventParser(); + const hiddenEvents = settings.hiddenEvents; + const hideMemberInReadOnly = settings.hideMemberInReadOnly; + const hideReads = settings.hideReads; // Ignored users const ignoredUsersList = useIgnoredUsers(); @@ -224,6 +134,61 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const openUserRoomProfile = useOpenUserRoomProfile(); const optionalSpace = useSpaceOptionally(); + // Shared timeline actions — replaces inline handleUserClick, + // handleUsernameClick, handleReplyClick, handleReactionToggle, + // handleResend, handleDeleteFailedSend (~65 lines). + // handleOpenEvent is caller-specific (ThreadDrawer's scroll architecture). + // setOpenThread is a no-op (thread drawer can't open sub-threads). + const actions = useTimelineActions({ + room, + mx, + editor, + nicknames, + getGlobalProfile, + spaceId: optionalSpace?.roomId, + openUserRoomProfile: openUserRoomProfile as unknown as ( + roomId: string, + spaceId: string | undefined, + userId: string, + rect: DOMRect, + undefinedArg?: undefined, + options?: unknown + ) => void, + activeReplyId, + activeReplyBody: replyDraft?.body, + setReplyDraft: setReplyDraft as unknown as (draft: unknown) => void, + threadRootId, + openThreadId: threadRootId, + setOpenThread: () => {}, + handleEdit, + handleOpenEvent: (id) => { + let anchorId = unwrapRelationJumpTarget(room, id); + const threadLive = thread?.timelineSet.getLiveTimeline(); + const threadEvents = threadLive?.getEvents(); + const rawIndex = threadEvents?.findIndex((e) => e.getId() === anchorId) ?? -1; + if (rawIndex >= 0) { + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + rawIndex + ); + if (nearest) { + const rowEv = processedEventsRef.current[nearest.rowIndex]; + if (rowEv) anchorId = rowEv.id; + } + } + const isRoot = anchorId === threadRootId; + const isInReplies = processedEventsRef.current.some((e) => e.id === anchorId); + if (!isRoot && !isInReplies) return; + setJumpToEventId(anchorId); + setTimeout(() => setJumpToEventId(undefined), 2500); + const el = drawerRef.current; + if (el) { + const target = el.querySelector(`[data-message-id="${anchorId}"]`); + target?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); + } + }, + }); + // Thread timeline data for useProcessedTimeline const thread = room.getThread(threadRootId); const threadTimeline = thread?.timelineSet.getLiveTimeline(); @@ -544,100 +509,6 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra } }, [processedReplies.length, hasOlderReplies]); - const handleUserClick: MouseEventHandler = useCallback( - (evt) => { - if (!evt.currentTarget) return; - evt.preventDefault(); - evt.stopPropagation(); - const userId = evt.currentTarget.getAttribute('data-user-id'); - if (!userId) return; - openUserRoomProfile( - room.roomId, - optionalSpace?.roomId, - userId, - evt.currentTarget.getBoundingClientRect(), - undefined, - buildCachedProfilePayload(getGlobalProfile(userId)) - ); - }, - [room, optionalSpace, openUserRoomProfile, getGlobalProfile] - ); - - const handleUsernameClick: MouseEventHandler = useCallback( - (evt) => { - evt.preventDefault(); - const userId = evt.currentTarget.getAttribute('data-user-id'); - if (!userId) return; - const name = - getMemberDisplayName(room, userId, nicknames) ?? getMxIdLocalPart(userId) ?? userId; - editor.insertNode( - createMentionElement( - userId, - name.startsWith('@') ? name : `@${name}`, - userId === mx.getUserId() - ) - ); - ReactEditor.focus(editor); - moveCursor(editor); - }, - [mx, room, editor, nicknames] - ); - - const handleReplyClick: MouseEventHandler = useCallback( - (evt) => { - const replyId = evt.currentTarget.getAttribute('data-event-id'); - if (!replyId) { - // In thread mode, resetting means going back to base thread draft - setReplyDraft({ - userId: mx.getUserId() ?? '', - eventId: threadRootId, - body: '', - relation: { rel_type: RelationType.Thread, event_id: threadRootId }, - }); - return; - } - const resolved = resolveReplyDraftTarget(room, replyId); - if (!resolved) return; - const { eventId: draftEventId, replyEvt } = resolved; - const { body, formattedBody } = extractReplyDraftBody( - replyEvt, - room.getUnfilteredTimelineSet() - ); - const senderId = replyEvt.getSender(); - if (senderId) { - const draft: IReplyDraft = { - userId: senderId, - eventId: draftEventId, - body, - formattedBody, - relation: { rel_type: RelationType.Thread, event_id: threadRootId }, - }; - // Only toggle off if we're actively replying to this event (non-empty body distinguishes - // a real reply draft from the seeded base-thread draft, which has body: ''). - if (activeReplyId === draftEventId && replyDraft?.body) { - // Toggle off — reset to base thread draft - setReplyDraft({ - userId: mx.getUserId() ?? '', - eventId: threadRootId, - body: '', - relation: { rel_type: RelationType.Thread, event_id: threadRootId }, - }); - } else { - setReplyDraft(draft); - } - } - }, - [mx, room, setReplyDraft, activeReplyId, threadRootId, replyDraft] - ); - - const handleReactionToggle = useCallback( - (targetEventId: string, key: string, shortcode?: string) => { - const threadTimelineSet = room.getThread(threadRootId)?.timelineSet; - toggleReaction(mx, room, targetEventId, key, shortcode, threadTimelineSet); - }, - [mx, room, threadRootId] - ); - const handleEditLastMessage = useCallback(() => { const userId = mx.getUserId(); const ownReply = [...processedEventsRef.current] @@ -662,54 +533,6 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra } }, [mx, threadRootId, handleEdit]); - const handleResend = useCallback( - (event: MatrixEvent) => { - if (event.getAssociatedStatus() !== EventStatus.NOT_SENT) return; - mx.resendEvent(event, room).catch(() => undefined); - }, - [mx, room] - ); - - const handleDeleteFailedSend = useCallback( - (event: MatrixEvent) => { - if (event.getAssociatedStatus() !== EventStatus.NOT_SENT) return; - mx.cancelPendingEvent(event); - }, - [mx] - ); - - const handleOpenReply: MouseEventHandler = useCallback( - (evt) => { - const targetId = evt.currentTarget.getAttribute('data-event-id'); - if (!targetId) return; - let anchorId = unwrapRelationJumpTarget(room, targetId); - const threadLive = thread?.timelineSet.getLiveTimeline(); - const threadEvents = threadLive?.getEvents(); - const rawIndex = threadEvents?.findIndex((e) => e.getId() === anchorId) ?? -1; - if (rawIndex >= 0) { - const nearest = getProcessedRowIndexForRawTimelineIndex( - processedEventsRef.current, - rawIndex - ); - if (nearest) { - const rowEv = processedEventsRef.current[nearest.rowIndex]; - if (rowEv) anchorId = rowEv.id; - } - } - const isRoot = anchorId === threadRootId; - const isInReplies = processedEventsRef.current.some((e) => e.id === anchorId); - if (!isRoot && !isInReplies) return; - setJumpToEventId(anchorId); - setTimeout(() => setJumpToEventId(undefined), 2500); - const el = drawerRef.current; - if (el) { - const target = el.querySelector(`[data-message-id="${anchorId}"]`); - target?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); - } - }, - [threadRootId, room, thread] - ); - // Map jumpToEventId to a focusItem index for useTimelineEventRenderer highlighting const jumpIndex = jumpToEventId ? processedEvents.findIndex((e) => e.id === jumpToEventId) : -1; const focusItem = @@ -728,26 +551,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra nicknames, getProfile: getGlobalProfile, imagePackRooms, - settings: { - messageLayout, - messageSpacing, - hideReads, - showDeveloperTools, - hour24Clock, - dateFormatString, - mediaAutoLoad, - showUrlPreview, - showClientUrlPreview, - showBundledPreview, - showMaps, - autoplayStickers, - hideMemberInReadOnly, - isReadOnly, - hideMembershipEvents: true, - hideNickAvatarEvents: true, - hiddenEvents, - hideThreadChip: true, - }, + settings: threadSettings, state: { focusItem, editId, activeReplyId, openThreadId: threadRootId, suppressMark }, permissions: { canRedact, @@ -756,15 +560,15 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra canPinEvent, }, callbacks: { - onUserClick: handleUserClick, - onUsernameClick: handleUsernameClick, - onReplyClick: handleReplyClick, - onReactionToggle: handleReactionToggle, - onEditId: handleEdit, - onResend: handleResend, - onDeleteFailedSend: handleDeleteFailedSend, + onUserClick: actions.handleUserClick, + onUsernameClick: actions.handleUsernameClick, + onReplyClick: actions.handleReplyClick, + onReactionToggle: actions.handleReactionToggle, + onEditId: actions.handleEdit, + onResend: actions.handleResend, + onDeleteFailedSend: actions.handleDeleteFailedSend, setOpenThread: () => {}, - handleOpenReply, + handleOpenReply: actions.handleOpenReply, }, utils: { htmlReactParserOptions, linkifyOpts, getMemberPowerTag, parseMemberEvent }, }); diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 87abe5912..7beccfed3 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -39,9 +39,9 @@ import { Username, UsernameBold, } from '$components/message'; -import { canEditEvent, getEditedEvent, getMemberAvatarMxc } from '$utils/room'; +import { canEditEvent, getEditedEvent } from '$utils/room/relations'; +import { getMemberAvatarMxc } from '$utils/room/display'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; -import { getMouseEventCords } from '$utils/dom'; import type { MessageSpacing } from '$state/settings'; import { getSettings, MessageLayout, settingsAtom } from '$state/settings'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -130,7 +130,7 @@ export type MessageProps = { msc2723ForwardedMessageProps?: MSC2723ForwardedMessageProps; }; -import { useMobileLongPress } from '$hooks/useMobileLongPress'; +import { useMenuAnchor } from '$hooks/useMenuAnchor'; const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str); @@ -512,7 +512,13 @@ function MessageInternal( }, }); - const [menuAnchor, setMenuAnchor] = useState(); + // Touch opens the mobile sheet, not the desktop popout; the hook still owns + // the press-feedback timer so `isPressing` keeps working. + const menu = useMenuAnchor({ + onLongPress: () => { + if (!edit) openMobileOptions(); + }, + }); const tagIconSrc = memberPowerTag?.icon ? getPowerTagIconSrc(mx, useAuthentication, memberPowerTag.icon) @@ -846,7 +852,7 @@ function MessageInternal( ); const closeMenu = () => { - setMenuAnchor(undefined); + menu.close(); setIsDesktopHover(false); setIsEmoji(false); }; @@ -885,43 +891,24 @@ function MessageInternal( }); }; - const { - onTouchStart, - onTouchEnd, - onTouchMove, - onTouchCancel, - firedRef: longPressFiredRef, - isPressing, - } = useMobileLongPress(() => { - if (!edit) openMobileOptions(); - }); - - const handleContextMenu: MouseEventHandler = (evt) => { + const contextMenuHandler: MouseEventHandler = (evt) => { if (evt.altKey || !window.getSelection()?.isCollapsed || edit) return; const tag = (evt.target as HTMLElement).tagName; if (typeof tag === 'string' && tag.toLowerCase() === 'a') return; if (mobileOrTablet()) { - // If our long-press handler already fired (iOS), suppress the native contextmenu - if (longPressFiredRef.current) { - evt.preventDefault(); - longPressFiredRef.current = false; - return; - } evt.preventDefault(); + // The long-press timer already opened the sheet; this is its synthetic follow-up. + if (menu.consumeLongPressFired()) return; openMobileOptions(); return; } - - evt.preventDefault(); - setMenuAnchor(getMouseEventCords(evt.nativeEvent)); + menu.triggerProps.onContextMenu(evt); }; const handleOpenMenu: MouseEventHandler = (evt) => { const target = evt.currentTarget.parentElement?.parentElement ?? evt.currentTarget; - const rect = target.getBoundingClientRect(); - window.requestAnimationFrame(() => { - setMenuAnchor(rect); + menu.openAt(target); }); }; @@ -960,7 +947,7 @@ function MessageInternal( - {!edit && (isDesktopHover || !!menuAnchor || isEmoji) && ( + {!edit && (isDesktopHover || !!menu.anchor || isEmoji) && (
diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index fc2fd1def..559a2f621 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -61,7 +61,8 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useDismissOnBack } from '$utils/androidBack'; import { nicknamesAtom } from '$state/nicknames'; -import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '$utils/room'; +import { getEditedEvent, getMentionContent } from '$utils/room/relations'; +import { trimReplyFromFormattedBody } from '$utils/room/display'; import { buildReplacementContent } from '../buildReplacementContent'; import { mobileOrTablet } from '$utils/user-agent'; import { useComposingCheck } from '$hooks/useComposingCheck'; diff --git a/src/app/features/room/poll-modals/PollResponses.tsx b/src/app/features/room/poll-modals/PollResponses.tsx index 30c620647..eb3f3639b 100644 --- a/src/app/features/room/poll-modals/PollResponses.tsx +++ b/src/app/features/room/poll-modals/PollResponses.tsx @@ -13,7 +13,7 @@ import { config, } from 'folds'; import type { MatrixEvent, Room, RoomMember } from '$types/matrix-sdk'; -import { getAvatarUrl, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName } from '$utils/room/display'; import { getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useAtomValue } from 'jotai'; @@ -29,7 +29,7 @@ import { useCallback, useEffect, useState } from 'react'; import type { PollAnswerItem } from '$components/message/PollEvent'; import { M_POLL_RESPONSE, M_TEXT } from 'matrix-js-sdk'; -export type PollResponsesViewerProps = { +type PollResponsesViewerProps = { room: Room; answers: PollAnswerItem[]; events: MatrixEvent[]; diff --git a/src/app/features/room/reaction-viewer/ReactionViewer.tsx b/src/app/features/room/reaction-viewer/ReactionViewer.tsx index dbe2b00a2..93e3dcf7a 100644 --- a/src/app/features/room/reaction-viewer/ReactionViewer.tsx +++ b/src/app/features/room/reaction-viewer/ReactionViewer.tsx @@ -2,7 +2,7 @@ import { useCallback, useState } from 'react'; import classNames from 'classnames'; import { Avatar, Box, Header, IconButton, Line, MenuItem, Scroll, Text, as, config } from 'folds'; import type { MatrixEvent, Room, RoomMember, Relations } from '$types/matrix-sdk'; -import { getAvatarUrl, getMemberDisplayName } from '$utils/room'; +import { getAvatarUrl, getMemberDisplayName } from '$utils/room/display'; import { eventWithShortcode, getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useRelations } from '$hooks/useRelations'; @@ -18,7 +18,7 @@ import { useSpaceOptionally } from '$hooks/useSpace'; import { getMouseEventCords } from '$utils/dom'; import * as css from './ReactionViewer.css'; -export type ReactionViewerProps = { +type ReactionViewerProps = { room: Room; initialKey?: string; relations: Relations; diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 937a73284..18394a0df 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -22,7 +22,7 @@ import { useRoomEvent } from '$hooks/useRoomEvent'; import { DefaultPlaceholder } from '$components/message'; import { dropzoneIcon, menuIcon, composerIcon, PushPin, X } from '$components/icons/phosphor'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import type { StateEvents } from '$types/matrix-sdk'; import { useSetting } from '$state/hooks/settings'; diff --git a/src/app/features/settings/SettingsRoute.test.tsx b/src/app/features/settings/SettingsRoute.test.tsx index 70a52fae0..e2712978a 100644 --- a/src/app/features/settings/SettingsRoute.test.tsx +++ b/src/app/features/settings/SettingsRoute.test.tsx @@ -90,8 +90,8 @@ vi.mock('$state/hooks/settings', () => ({ useSetting: mockUseSetting, })); -vi.mock('$components/Modal500', () => ({ - Modal500: ({ children }: { children: ReactNode }) =>
{children}
, +vi.mock('$components/modal-overlay/ModalOverlay', () => ({ + ModalOverlay: ({ children }: { children: ReactNode }) =>
{children}
, })); vi.mock('./general', () => ({ diff --git a/src/app/features/settings/SettingsShallowRouteRenderer.tsx b/src/app/features/settings/SettingsShallowRouteRenderer.tsx index c310fb6c3..dfcababc7 100644 --- a/src/app/features/settings/SettingsShallowRouteRenderer.tsx +++ b/src/app/features/settings/SettingsShallowRouteRenderer.tsx @@ -1,6 +1,8 @@ +import { useRef } from 'react'; import { matchPath, useLocation } from 'react-router-dom'; +import { Modal } from 'folds'; import { useScreenSizeContext } from '$hooks/useScreenSize'; -import { Modal500 } from '$components/Modal500'; +import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { isShallowRoute } from '$pages/client/shallowRoute'; import { useCloseShallowRoute } from '$pages/client/useShallowRoute'; import { SETTINGS_PATH } from '$pages/paths'; @@ -11,14 +13,17 @@ export function SettingsShallowRouteRenderer() { const screenSize = useScreenSizeContext(); const requestClose = useCloseShallowRoute(); const routeMatch = matchPath(SETTINGS_PATH, location.pathname); + const modalRef = useRef(null); if (!routeMatch || !isShallowRoute(location.pathname, location.state, screenSize)) { return null; } return ( - - - + + + + + ); } diff --git a/src/app/features/settings/account/AnimalCosmetics.tsx b/src/app/features/settings/account/AnimalCosmetics.tsx index 1cf7fd475..4d05db368 100644 --- a/src/app/features/settings/account/AnimalCosmetics.tsx +++ b/src/app/features/settings/account/AnimalCosmetics.tsx @@ -1,11 +1,11 @@ import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import { SettingTile } from '$components/setting-tile'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; import { useMatrixClient } from '$hooks/useMatrixClient'; import type { UserProfile } from '$hooks/useUserProfile'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { profilesCacheAtom } from '$state/userRoomProfile'; -import { Box, IconButton, Input, Switch, Text } from 'folds'; +import { Box, IconButton, Input, Text } from 'folds'; import { useSetAtom } from 'jotai'; import { useCallback, useEffect, useState, type ChangeEvent } from 'react'; import * as prefix from '$unstable/prefixes'; @@ -129,14 +129,13 @@ export function AnimalCosmetics({ profile, userId }: Readonly Animal Identity - - } - /> - + ) ? (mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; - const [imageFile, setImageFile] = useState(); - const imageFileURL = useObjectURL(imageFile); - const uploadAtom = useMemo(() => { - if (imageFile) return createUploadAtom(imageFile); - return undefined; - }, [imageFile]); - - const pickFile = useFilePicker(setImageFile, false); - - const handleRemoveUpload = useCallback(() => { - setImageFile(undefined); - }, []); - const handleUploaded = useCallback( - async (upload: UploadSuccess) => { - const { mxc } = upload; + async (mxc: string) => { await setAvatarUrlWithPropagation(mx, mxc, propagateTo); setGlobalProfiles((prev) => ({ ...prev, [userId]: { ...prev[userId], avatarUrl: mxc }, })); - handleRemoveUpload(); }, - [mx, userId, propagateTo, setGlobalProfiles, handleRemoveUpload] + [mx, userId, propagateTo, setGlobalProfiles] ); - const handleRemoveAvatar = async () => { - const ok = await confirm({ - title: 'Remove Avatar', - description: 'Are you sure you want to remove profile avatar?', - action: 'Remove', - variant: 'Critical', - }); - if (ok) { - await setAvatarUrlWithPropagation(mx, '', propagateTo); - setGlobalProfiles((prev) => ({ - ...prev, - [userId]: { ...prev[userId], avatarUrl: undefined }, - })); - } - }; + const handleRemoveAvatar = useCallback(async () => { + await setAvatarUrlWithPropagation(mx, '', propagateTo); + setGlobalProfiles((prev) => ({ + ...prev, + [userId]: { ...prev[userId], avatarUrl: undefined }, + })); + }, [mx, userId, propagateTo, setGlobalProfiles]); return ( - ) /> } - > - {uploadAtom ? ( - - - - ) : ( - - - {avatarUrl && ( - - )} - - )} - - {imageFileURL && ( - - - - - - )} - + /> ); } @@ -695,7 +628,15 @@ function ProfileExtended({ profile, userId }: Readonly) { title={key.split('.').pop() || key} description={key} after={ - + {strVal} } diff --git a/src/app/features/settings/account/StatusEditor.tsx b/src/app/features/settings/account/StatusEditor.tsx index 813be142f..d71618863 100644 --- a/src/app/features/settings/account/StatusEditor.tsx +++ b/src/app/features/settings/account/StatusEditor.tsx @@ -43,7 +43,14 @@ export function StatusEditor({ current = '', onSave }: StatusEditorProps) { return ( - + Privacy & Security - - } - /> - + - - - } - /> - + - - - } - /> - + ); } @@ -437,28 +418,20 @@ function IdentityCosmetics() { return ( Identity - - - } - /> - - - } - /> - + + } /> - - } - /> - + } /> - - - } - /> - - - - } - /> - - - } - /> - - - } - /> - + + + + ); } diff --git a/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx b/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx index 0d493958b..16fe2df7e 100644 --- a/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx +++ b/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx @@ -4,7 +4,7 @@ import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { useEffect, useState } from 'react'; import { getSettings, setSettings } from '$state/settings'; -export type LanguageSpecificPronounsConfig = { +type LanguageSpecificPronounsConfig = { enabled?: boolean | string; languages?: string[]; }; diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx index 2028c4b08..f2a939305 100644 --- a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -28,7 +28,7 @@ import { type ThemeRemoteTweakFavorite, } from '$state/settings'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import { SettingTile } from '$components/setting-tile'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; import { ThemePreviewCard } from '$components/theme/ThemePreviewCard'; import { usePatchSettings } from './themeSettingsPatch'; import { ThemeImportModal } from './ThemeImportModal'; @@ -63,7 +63,7 @@ import { import { CssViewerButton } from '$components/theme/CssViewerButton'; import * as css from './ThemeCatalogSettings.css'; -export type CatalogPreviewRow = ThemePair & { +type CatalogPreviewRow = ThemePair & { previewText: string; displayName: string; author?: string; @@ -73,7 +73,7 @@ export type CatalogPreviewRow = ThemePair & { fullInstallUrl: string; }; -export type LocalPreviewRow = ThemeRemoteFavorite & { +type LocalPreviewRow = ThemeRemoteFavorite & { previewUrl: string; previewText: string; fullCssText: string; @@ -84,7 +84,7 @@ export type LocalPreviewRow = ThemeRemoteFavorite & { importedLocal?: boolean; }; -export type CatalogTweakRow = TweakCatalogEntry & { +type CatalogTweakRow = TweakCatalogEntry & { fullCssText: string; displayName: string; description?: string; @@ -92,14 +92,14 @@ export type CatalogTweakRow = TweakCatalogEntry & { tags: string[]; }; -export type LocalTweakRow = ThemeRemoteTweakFavorite & { +type LocalTweakRow = ThemeRemoteTweakFavorite & { fullCssText: string; description?: string; author?: string; tags: string[]; }; -export type ThemeCatalogSettingsMode = 'local' | 'appearance'; +type ThemeCatalogSettingsMode = 'local' | 'appearance'; type ThemeCatalogSettingsProps = { mode: ThemeCatalogSettingsMode; @@ -1750,46 +1750,29 @@ export function ThemeCatalogSettings({ mode, onBrowseOpenChange }: ThemeCatalogS {isChatMode && ( <> - - - } - /> - - - - } - /> - - - - } - /> - + + + )} diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index baa42f5e2..36a491ccf 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -12,7 +12,7 @@ import { type SettingMenuOption, } from '$components/setting-menu-selector'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import { SettingTile } from '$components/setting-tile'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; import { DEFAULT_ARBORIUM_DARK_THEME, DEFAULT_ARBORIUM_LIGHT_THEME, @@ -301,38 +301,34 @@ function ThemeVisualPreferences() { } /> - - } - /> - - - } - /> - - - } - /> - - - } - /> - + + + + - - - } - /> - - - } - /> - + + - - } - /> - + Visual Tweaks - - } - /> - + - - - } - /> - + - - - } - /> - + - - - } - /> - + } /> @@ -773,16 +750,13 @@ export function Appearance({ /> - - - } - /> - + Window - - - } - /> - - - - } - /> - + + {type !== 'macos' && ( - - - System tray is unavailable on this system. Sable can still keep running - in the background without it. - - ) : ( - 'Show a system tray icon while Sable is running. Disable this if you want Sable to stay available without a tray icon.' - ) - } - after={ - - } - /> - + + System tray is unavailable on this system. Sable can still keep running in + the background without it. + + ) : ( + 'Show a system tray icon while Sable is running. Disable this if you want Sable to stay available without a tray icon.' + ) + } + value={!trayFallback ? showSystemTrayIcon : false} + disabled={trayFallback} + onChange={setShowSystemTrayIcon} + ariaLabel="show-system-tray-icon" + /> )} Updates - - - } - /> - +
diff --git a/src/app/features/settings/developer-tools/SentrySettings.tsx b/src/app/features/settings/developer-tools/SentrySettings.tsx index 7d4190d02..03a213ac7 100644 --- a/src/app/features/settings/developer-tools/SentrySettings.tsx +++ b/src/app/features/settings/developer-tools/SentrySettings.tsx @@ -18,15 +18,10 @@ const ALL_CATEGORIES: LogCategory[] = [ 'general', ]; +import { downloadJsonFile } from '$utils/common'; + const handleExportLogs = () => { - const data = getDebugLogger().exportLogs(); - const blob = new Blob([data], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `sable-debug-logs-${Date.now()}.json`; - a.click(); - URL.revokeObjectURL(url); + downloadJsonFile(getDebugLogger().exportLogs(), 'sable-debug-logs'); }; export function SentrySettings() { diff --git a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx index bed7611e7..3ee69fac7 100644 --- a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx +++ b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx @@ -8,7 +8,7 @@ import { getClientSyncDiagnostics } from '$client/initMatrix'; import type { Room } from '$types/matrix-sdk'; import { Direction, EventType, NotificationCountType, KnownMembership } from '$types/matrix-sdk'; -import { getUnreadInfo, isNotificationEvent } from '$utils/room'; +import { getUnreadInfo, isNotificationEvent } from '$utils/room/unread'; import { allRoomsAtom } from '$state/room-list/roomList'; import { allInvitesAtom } from '$state/room-list/inviteList'; import { getMediaLoadFailureCounts } from '$utils/mediaLoadDiagnostics'; diff --git a/src/app/features/settings/devices/LocalBackup.tsx b/src/app/features/settings/devices/LocalBackup.tsx index e4648d161..f9cb9e981 100644 --- a/src/app/features/settings/devices/LocalBackup.tsx +++ b/src/app/features/settings/devices/LocalBackup.tsx @@ -1,6 +1,6 @@ import type { FormEventHandler } from 'react'; import { useCallback, useEffect, useState } from 'react'; -import { Box, Button, color, Spinner, Text, toRem } from 'folds'; +import { Box, Button, color, Text, toRem } from 'folds'; import { ArrowRight, CaretDown, CaretUp, File, menuIcon, X } from '$components/icons/phosphor'; import { saveFileToDevice } from '$utils/download'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; @@ -9,6 +9,7 @@ import { PasswordInput } from '$components/password-input'; import { ConfirmPasswordMatch } from '$components/ConfirmPasswordMatch'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; import { decryptMegolmKeyFile, encryptMegolmKeyFile, @@ -111,20 +112,22 @@ function ExportKeys() { )} - + {exportState.status === AsyncStatus.Error && ( @@ -234,20 +237,22 @@ function ImportKeys({ file, onDone }: ImportKeysProps) { readOnly={decrypting} /> - + {decryptState.status === AsyncStatus.Error && ( diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index d2f815b80..5d38fb06b 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -1,11 +1,10 @@ -import { Box, Text, Scroll, Switch } from 'folds'; +import { Box, Text, Scroll } from 'folds'; import { menuIcon, Warning } from '$components/icons/phosphor'; import { PageContent, SettingsSectionPage } from '$components/page'; import { InfoCard } from '$components/info-card'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; -import { SettingTile } from '$components/setting-tile'; -import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; +import { SettingToggle } from '$components/setting-tile'; import { BandwidthSavingEmojis } from './BandwithSavingEmojis'; import { MSC4268HistoryShare } from './MSC4268HistoryShare'; import { MSC4274MediaGalleries } from './MSC4274MediaGalleries'; @@ -19,16 +18,13 @@ function PersonaToggle() { return ( Personas (Per-Message Profiles) - - - } - /> - + ); } diff --git a/src/app/features/settings/general/CallSoundSettings.tsx b/src/app/features/settings/general/CallSoundSettings.tsx index 0868b44ea..6d007048c 100644 --- a/src/app/features/settings/general/CallSoundSettings.tsx +++ b/src/app/features/settings/general/CallSoundSettings.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; -import { Box, Icons, Input, Switch, Text, toRem } from 'folds'; +import { Box, Icons, Input, Text, toRem } from 'folds'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import { SettingTile } from '$components/setting-tile'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; import { SettingMenuSelector } from '$components/setting-menu-selector'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, type CallRingtoneId } from '$state/settings'; @@ -256,48 +256,27 @@ export function CallSoundSettings() { return ( - - - } - /> - - - - } - /> - - - - } - /> - + + + - - - } - /> - + Date & Time - - } - /> - + @@ -482,72 +481,55 @@ function Editor() { return ( Editor - - } - /> - - - } - /> - - - - } - /> - - - } - /> - - - - } - /> - - - } - /> - - - - } - /> - + + + + + + + )} - - } - /> - - - } - /> - - - } - /> - - - - } - /> - - - - } - /> - + + + + + ); } @@ -756,32 +725,18 @@ function Calls() { return ( Calls - - - } - /> - - - - } - /> - + + ); @@ -866,78 +821,43 @@ function Messages() { /> )} - - setMediaAutoLoad(!v)} - /> - } - /> - - - - } - /> - - - - } - /> - - - - } - /> - - - + setMediaAutoLoad(!v)} + /> + + + + ); } @@ -1300,23 +1186,15 @@ function Sync() { return ( Data Syncing - - Enable Sliding Sync for this current login/session. Requires server support. - } - after={ - - } - /> - + Enable Sliding Sync for this current login/session. Requires server support. + } + value={useSlidingSync} + onChange={handleSetSlidingSync} + /> { - const actions = getModeActions(mode); - await mx.setPushRuleActions('global', kind, ruleId, actions); - }, - [mx, getModeActions, kind, ruleId] - ) - ); - return ( - ); } diff --git a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx index a59db2c48..665037fe6 100644 --- a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx +++ b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx @@ -1,5 +1,5 @@ import { useCallback, useState } from 'react'; -import { Box, Button, color, config, Dialog, Header, IconButton, Spinner, Text } from 'folds'; +import { Box, Button, color, config, Dialog, Header, IconButton, Text } from 'folds'; import { menuIcon, X } from '$components/icons/phosphor'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { useAtom } from 'jotai'; @@ -14,6 +14,7 @@ import { disableNativePush } from './NotificationTransport'; import { disableUnifiedPush } from './UnifiedPushNotifications'; import { SettingTile } from '../../../components/setting-tile'; import { isTauri } from '@tauri-apps/api/core'; +import { AsyncButton } from '../../../components/AsyncButton'; type ConfirmDeregisterDialogProps = { onClose: () => void; @@ -39,15 +40,16 @@ function ConfirmDeregisterDialog({ onClose, onConfirm, isLoading }: ConfirmDereg cannot be undone. Are you sure you want to continue? - + diff --git a/src/app/features/settings/notifications/NotificationModeSwitcher.tsx b/src/app/features/settings/notifications/NotificationModeSwitcher.tsx new file mode 100644 index 000000000..53ca0d636 --- /dev/null +++ b/src/app/features/settings/notifications/NotificationModeSwitcher.tsx @@ -0,0 +1,50 @@ +import { useCallback } from 'react'; +import type { IPushRules, RuleId } from '$types/matrix-sdk'; +import { type PushRuleData, usePushRule } from '$hooks/usePushRule'; +import { + type NotificationMode, + type NotificationModeOptions, + useNotificationActionsMode, + useNotificationModeActions, +} from '$hooks/useNotificationMode'; +import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { SettingMenuSelector } from '$components/setting-menu-selector'; +import { notificationModeSelectorOptions } from './notificationModeOptions'; + +export type NotificationModeSwitcherProps = { + ruleId: RuleId; + pushRules: IPushRules; + defaultPushRuleData: PushRuleData; + modeOptions?: NotificationModeOptions; +}; + +export function NotificationModeSwitcher({ + ruleId, + pushRules, + defaultPushRuleData, + modeOptions, +}: NotificationModeSwitcherProps) { + const mx = useMatrixClient(); + const { kind, pushRule } = usePushRule(pushRules, ruleId) ?? defaultPushRuleData; + const getModeActions = useNotificationModeActions(modeOptions); + const selectedMode = useNotificationActionsMode(pushRule.actions); + const [changeState, change] = useAsyncCallback( + useCallback( + async (mode: NotificationMode) => { + const actions = getModeActions(mode); + await mx.setPushRuleActions('global', kind, ruleId, actions); + }, + [mx, getModeActions, kind, ruleId] + ) + ); + + return ( + + ); +} diff --git a/src/app/features/settings/notifications/SpecialMessages.tsx b/src/app/features/settings/notifications/SpecialMessages.tsx index f16b8e1c4..97d2d77e9 100644 --- a/src/app/features/settings/notifications/SpecialMessages.tsx +++ b/src/app/features/settings/notifications/SpecialMessages.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useMemo } from 'react'; import type { IPushRules } from '$types/matrix-sdk'; import { ConditionKind, PushRuleKind, RuleId, EventType } from '$types/matrix-sdk'; import { Box, Text, Badge } from 'folds'; @@ -6,24 +6,16 @@ import { useAccountData } from '$hooks/useAccountData'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; -import { SettingMenuSelector } from '$components/setting-menu-selector'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useUserProfile } from '$hooks/useUserProfile'; import { getMxIdLocalPart } from '$utils/matrix'; import type { PushRuleData } from '$hooks/usePushRule'; -import { makePushRuleData, usePushRule } from '$hooks/usePushRule'; -import type { NotificationModeOptions } from '$hooks/useNotificationMode'; -import { - getNotificationModeActions, - NotificationMode, - useNotificationActionsMode, - useNotificationModeActions, -} from '$hooks/useNotificationMode'; -import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { makePushRuleData } from '$hooks/usePushRule'; +import { getNotificationModeActions, NotificationMode } from '$hooks/useNotificationMode'; import { NotificationLevelsHint } from './NotificationLevelsHint'; -import { notificationModeSelectorOptions } from './notificationModeOptions'; +import { NotificationModeSwitcher } from './NotificationModeSwitcher'; -const NOTIFY_MODE_OPS: NotificationModeOptions = { +const NOTIFY_MODE_OPS = { highlight: true, }; const getDefaultIsUserMention = (userId: string): PushRuleData => @@ -100,27 +92,12 @@ type PushRulesProps = { defaultPushRuleData: PushRuleData; }; function MentionModeSwitcher({ ruleId, pushRules, defaultPushRuleData }: PushRulesProps) { - const mx = useMatrixClient(); - - const { kind, pushRule } = usePushRule(pushRules, ruleId) ?? defaultPushRuleData; - const getModeActions = useNotificationModeActions(NOTIFY_MODE_OPS); - const selectedMode = useNotificationActionsMode(pushRule.actions); - const [changeState, change] = useAsyncCallback( - useCallback( - async (mode: NotificationMode) => { - const actions = getModeActions(mode); - await mx.setPushRuleActions('global', kind, ruleId, actions); - }, - [mx, getModeActions, kind, ruleId] - ) - ); - return ( - ); } diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 2c758bba0..316e14ab7 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -15,7 +15,7 @@ import { import type { IPusherRequest } from '$types/matrix-sdk'; import { useAtom } from 'jotai'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import { SettingTile } from '$components/setting-tile'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; import { SettingMenuSelector } from '$components/setting-menu-selector'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; @@ -946,19 +946,13 @@ export function SystemNotification() { return ( System & Notifications - - } - /> - + {(!mobileOrTablet() || isIosTauri()) && ( - - } - /> - - - } - /> - - - - } - /> - - - } - /> - - - } - /> - + + + + + {badgeBehaviourSummary()} - - - } - /> - - - - } - /> - - - - } - /> - - - } - /> - - - - } - /> - + + + + + ); } diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index 6e51838c0..e094b7174 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -10,7 +10,8 @@ import { ENCRYPTED_MESSAGE_PREVIEW, } from '$utils/notificationStyle'; import { getMxIdLocalPart } from '$utils/matrix'; -import { getStateEvent, getMemberAvatarMxc } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; +import { getMemberAvatarMxc } from '$utils/room/display'; import { createDebugLogger } from '$utils/debugLogger'; import { registerUnifiedPushTransport, diff --git a/src/app/features/settings/settingTileFocusCoverage.test.ts b/src/app/features/settings/settingTileFocusCoverage.test.ts index 76b02f79a..16ae19e1e 100644 --- a/src/app/features/settings/settingTileFocusCoverage.test.ts +++ b/src/app/features/settings/settingTileFocusCoverage.test.ts @@ -2,12 +2,33 @@ import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -const getSettingsFiles = (dir: string): string[] => +import { settingsLinkFocusIdsBySection } from './settingsLink'; +import { settingsSections, type SettingsSectionId } from './routes'; + +const SETTINGS_DIR = 'src/app/features/settings'; + +// --- directory → section id mapping --- +const dirToSection: Record = { + account: 'account', + Persona: 'persona', + cosmetics: 'appearance', + notifications: 'notifications', + 'keyboard-shortcuts': 'keyboard-shortcuts', + devices: 'devices', + desktop: 'desktop', + 'emojis-stickers': 'emojis', + 'developer-tools': 'developer-tools', + experimental: 'experimental', + about: 'about', + general: 'general', +}; + +const getSettingsComponentFiles = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const filePath = join(dir, entry.name); if (entry.isDirectory()) { - return getSettingsFiles(filePath); + return getSettingsComponentFiles(filePath); } if (!entry.isFile() || !filePath.endsWith('.tsx') || filePath.endsWith('.test.tsx')) { @@ -17,15 +38,109 @@ const getSettingsFiles = (dir: string): string[] => return [filePath]; }); -describe('settings tile focus coverage', () => { - it('requires every settings SettingTile to declare a focusId', () => { - const offenders = getSettingsFiles('src/app/features/settings').flatMap((file) => { - const source = readFileSync(file, 'utf8'); - const matches = [...source.matchAll(/]*\bfocusId=)/g)]; +/** Extract literal focusId="value" strings from a source file. */ +const extractLiteralFocusIds = (source: string): string[] => { + const results: string[] = []; + // Match focusId="value" (double-quoted literals only — skip template literals) + const re = /focusId="([^"]*)"/g; + let match: RegExpExecArray | null; + while ((match = re.exec(source)) !== null) { + const value = match[1]; + if (value) results.push(value); + } + return results; +}; - return matches.map(() => file); +describe('settings tile focus coverage', () => { + // --- canonical link-map checks --- + describe('settingsLinkFocusIdsBySection', () => { + it('covers every section', () => { + for (const section of settingsSections) { + expect( + settingsLinkFocusIdsBySection[section.id], + `section "${section.id}" has no focusIds entry` + ).toBeDefined(); + } }); - expect(offenders).toEqual([]); + it('has unique entries within each section', () => { + for (const section of settingsSections) { + const ids = settingsLinkFocusIdsBySection[section.id]; + const seen = new Set(); + const dupes: string[] = []; + for (const id of ids) { + if (seen.has(id)) dupes.push(id); + seen.add(id); + } + expect(dupes, `duplicate focusIds in section "${section.id}"`).toEqual([]); + } + }); + + it('contains only lowercase-alphanumeric-hyphen entries matching the focusId pattern', () => { + const PATTERN = /^[a-z0-9-]+$/; + for (const section of settingsSections) { + const offenders = settingsLinkFocusIdsBySection[section.id].filter( + (id) => !PATTERN.test(id) + ); + expect(offenders, `invalid focusId format in section "${section.id}"`).toEqual([]); + } + }); + }); + + // --- component source checks --- + describe('component focusId coverage', () => { + const files = getSettingsComponentFiles(SETTINGS_DIR); + const fileContents = new Map(files.map((f) => [f, readFileSync(f, 'utf8')])); + + // Build the full set of link-map focusIds for cross-reference + const allLinkMapIds = new Set(Object.values(settingsLinkFocusIdsBySection).flat()); + + it('every and tag has a focusId prop', () => { + const offenders: { file: string; line: number; context: string }[] = []; + + for (const [file, source] of fileContents) { + // Find ]*\/?>/g; + let tagMatch: RegExpExecArray | null; + while ((tagMatch = tagRe.exec(source)) !== null) { + const tag = tagMatch[0]; + if (!/\bfocusId=/.test(tag)) { + const line = source.slice(0, tagMatch.index).split('\n').length; + offenders.push({ file, line, context: tag.slice(0, 120) }); + } + } + } + + expect(offenders, ' or tags missing focusId prop').toEqual([]); + }); + + it('literal focusIds in a component directory belong to the correct section', () => { + const mismatches: { + file: string; + focusId: string; + expectedSection: SettingsSectionId; + }[] = []; + + for (const [file, source] of fileContents) { + // Determine section from file path + const relativePath = file.replace(SETTINGS_DIR + '/', ''); + const topDir = relativePath.split('/')[0]!; + const section = dirToSection[topDir]; + if (!section) continue; // e.g., root-level SettingTile definitions like SettingsRoute.tsx + + const sectionIds = new Set(settingsLinkFocusIdsBySection[section]); + + for (const focusId of extractLiteralFocusIds(source)) { + if (allLinkMapIds.has(focusId) && !sectionIds.has(focusId)) { + mismatches.push({ file, focusId, expectedSection: section }); + } + } + } + + expect( + mismatches, + 'focusId values in the wrong section (they appear in a directory but belong to a different section in the link map)' + ).toEqual([]); + }); }); }); diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts index fb7857f31..3e64bae70 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -15,7 +15,7 @@ const settingsSectionLabel = Object.fromEntries( settingsSections.map((section) => [section.id, section.label]) ) as Record; -const settingsLinkFocusIdsBySection: Record = { +export const settingsLinkFocusIdsBySection: Record = { general: [ 'show-interactive-map', 'show-interactive-map-enc', diff --git a/src/app/features/share-target/ShareTargetFeature.tsx b/src/app/features/share-target/ShareTargetFeature.tsx index e6d9d6c25..4f9ca1116 100644 --- a/src/app/features/share-target/ShareTargetFeature.tsx +++ b/src/app/features/share-target/ShareTargetFeature.tsx @@ -1,17 +1,15 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useAtom, useAtomValue } from 'jotai'; +import { useAtom } from 'jotai'; import { useStore } from 'jotai/react'; import { isTauri } from '@tauri-apps/api/core'; import { type as osType } from '@tauri-apps/plugin-os'; import { SyncState } from '$types/matrix-sdk'; import { shareInboxClear, shareInboxDrain, shareInboxRead } from '$generated/tauri/commands'; import { pendingShareAtom } from '$state/shareTarget'; -import { allRoomsAtom } from '$state/room-list/roomList'; -import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useSyncState } from '$hooks/useSyncState'; -import { factoryRoomIdByActivity } from '$utils/sort'; +import { useMessageTargetRooms } from '$hooks/useMessageTargetRooms'; import { encryptFile } from '$utils/matrix'; import { safeFile } from '$utils/mimeTypes'; import { createLogger } from '$utils/debug'; @@ -49,10 +47,6 @@ export function ShareTargetFeature() { // Guards against an in-flight drain resurrecting already-consumed batches. const consumedRef = useRef(new Set()); - const allRooms = useAtomValue(allRoomsAtom); - const allJoinedRooms = useAllJoinedRoomsSet(); - const getRoom = useGetRoom(allJoinedRooms); - useSyncState( mx, useCallback((state) => { @@ -112,16 +106,7 @@ export function ShareTargetFeature() { }; }, [setPending]); - const shareTargets = useMemo( - () => - allRooms - .filter((id) => { - const target = getRoom(id); - return !!target && !target.isSpaceRoom() && target.maySendMessage(); - }) - .sort(factoryRoomIdByActivity(mx)), - [allRooms, getRoom, mx] - ); + const shareTargets = useMessageTargetRooms(); const handleClose = useCallback(async () => { if (busy || !pending) return; diff --git a/src/app/hooks/commands/moderation.ts b/src/app/hooks/commands/moderation.ts index e917b58e2..698f9784b 100644 --- a/src/app/hooks/commands/moderation.ts +++ b/src/app/hooks/commands/moderation.ts @@ -1,7 +1,7 @@ import type { IContextResponse, RoomServerAclEventContent } from '$types/matrix-sdk'; import { Direction, EventType, KnownMembership, Method } from '$types/matrix-sdk'; import { isUserId, rateLimitedActions } from '$utils/matrix'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { splitWithSpace } from '$utils/common'; import type { CommandContext, CommandRecord } from './types'; import { Command } from './types'; diff --git a/src/app/hooks/media/index.ts b/src/app/hooks/media/index.ts index 7c202f9cf..72f3e64fc 100644 --- a/src/app/hooks/media/index.ts +++ b/src/app/hooks/media/index.ts @@ -1,6 +1,5 @@ export * from './useMediaPlay'; export * from './useMediaPlayTimeCallback'; -export * from './useMediaPlaybackRate'; export * from './useMediaSeek'; export * from './useMediaVolume'; export * from './useMediaLoading'; diff --git a/src/app/hooks/media/useMediaPlaybackRate.ts b/src/app/hooks/media/useMediaPlaybackRate.ts deleted file mode 100644 index 96a61c8c8..000000000 --- a/src/app/hooks/media/useMediaPlaybackRate.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type MediaPlaybackRateData = { - playbackRate: number; -}; -export type MediaPlaybackRateControl = { - setPlaybackRate: (rate: number) => void; -}; diff --git a/src/app/hooks/timeline/__snapshots__/useTimelineEventRenderer.test.tsx.snap b/src/app/hooks/timeline/__snapshots__/useTimelineEventRenderer.test.tsx.snap index 54ad40d06..ccbe5b17e 100644 --- a/src/app/hooks/timeline/__snapshots__/useTimelineEventRenderer.test.tsx.snap +++ b/src/app/hooks/timeline/__snapshots__/useTimelineEventRenderer.test.tsx.snap @@ -1,6 +1,6 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`useTimelineEventRenderer > 'm.call.member (GroupCallMemberPrefix)' > renders correctly 1`] = `"

bob sent m.call.member event

"`; +exports[`useTimelineEventRenderer > 'm.call.member (GroupCallMemberPrefix)' > renders correctly 1`] = `"

bob ended the call

"`; exports[`useTimelineEventRenderer > 'm.poll.start (M_POLL_START)' > renders correctly 1`] = `"
"`; @@ -27,3 +27,13 @@ exports[`useTimelineEventRenderer > 'm.sticker (Sticker)' > renders correctly 1` exports[`useTimelineEventRenderer > 'non-state event fallback (unknown eve…' > renders correctly 1`] = `"

bob sent io.sable.unknown.event event

"`; exports[`useTimelineEventRenderer > 'state event fallback (unknown state e…' > renders correctly 1`] = `"

bob sent io.sable.unknown.state state event

"`; + +exports[`useTimelineEventRenderer > activeReplyId === mEventId (marked logic) > sets data-is-marked="true" when activeReplyId matches 1`] = `"
"`; + +exports[`useTimelineEventRenderer > activeReplyId === mEventId (marked logic) > suppresses mark when suppressMark is true 1`] = `"
"`; + +exports[`useTimelineEventRenderer > edit event (renderEditTimelineEvent path) > renders an edit event with m.replace relation 1`] = `"

bob edited a message

"`; + +exports[`useTimelineEventRenderer > reactions bar (useReactionsGuard) > renders reactions bar when reactions exist 1`] = `"
"`; + +exports[`useTimelineEventRenderer > thread chip > renders thread chip when room.getThread returns non-null 1`] = `"
"`; diff --git a/src/app/hooks/timeline/useProcessedTimeline.ts b/src/app/hooks/timeline/useProcessedTimeline.ts index 9d9f29bad..61f0a964c 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.ts +++ b/src/app/hooks/timeline/useProcessedTimeline.ts @@ -13,7 +13,7 @@ import { collectRelationEditEvents, getEditedEvent, getEventReactions, -} from '$utils/room'; +} from '$utils/room/relations'; import { inSameDay, minuteDifference } from '$utils/time'; import type { ResolvedHiddenEventSettings } from '$state/hooks/settings'; diff --git a/src/app/hooks/timeline/useTimelineActions.ts b/src/app/hooks/timeline/useTimelineActions.ts index b3a3ecff5..aee5028b4 100644 --- a/src/app/hooks/timeline/useTimelineActions.ts +++ b/src/app/hooks/timeline/useTimelineActions.ts @@ -7,7 +7,8 @@ import type { Editor } from 'slate'; import { ReactEditor } from 'slate-react'; import { getMxIdLocalPart, toggleReaction } from '$utils/matrix'; -import { extractReplyDraftBody, getMemberDisplayName, resolveReplyDraftTarget } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; +import { extractReplyDraftBody, resolveReplyDraftTarget } from '$utils/room/relations'; import { createMentionElement, moveCursor } from '$components/editor'; import * as prefix from '$unstable/prefixes'; @@ -59,7 +60,11 @@ export interface UseTimelineActionsOptions { options?: unknown ) => void; activeReplyId?: string; + /** Distinguishes a real reply draft from the seeded base-thread draft, which has body ''. */ + activeReplyBody?: string; setReplyDraft: (draft: unknown) => void; + /** Set when these actions drive a thread drawer rather than the room timeline. */ + threadRootId?: string; openThreadId?: string; setOpenThread: (threadId: string | undefined) => void; handleEdit: (editId?: string) => void; @@ -75,7 +80,9 @@ export function useTimelineActions({ spaceId, openUserRoomProfile, activeReplyId, + activeReplyBody, setReplyDraft, + threadRootId, openThreadId, setOpenThread, handleEdit, @@ -138,8 +145,19 @@ export function useTimelineActions({ const { eventId: draftEventId, replyEvt } = resolved; - if (activeReplyId === draftEventId) { - setReplyDraft(undefined); + // In a thread the seeded base draft already targets the root with an empty + // body, so matching on the id alone would make the root unrepliable. + if (activeReplyId === draftEventId && activeReplyBody !== '') { + setReplyDraft( + threadRootId + ? { + userId: mx.getUserId() ?? '', + eventId: threadRootId, + body: '', + relation: { rel_type: 'm.thread', event_id: threadRootId }, + } + : undefined + ); return; } @@ -162,7 +180,7 @@ export function useTimelineActions({ }); } }, - [room, setReplyDraft, activeReplyId] + [room, setReplyDraft, activeReplyId, activeReplyBody, threadRootId, mx] ); const handleReplyClick = useCallback( @@ -187,9 +205,14 @@ export function useTimelineActions({ const handleReactionToggle = useCallback( (targetEventId: string, key: string, shortcode?: string) => { - toggleReaction(mx, room, targetEventId, key, shortcode); + // Thread reactions live in the thread's own timeline set; without it the + // existing reaction is never found and un-reacting sends a second one. + const threadTimelineSet = threadRootId + ? room.getThread(threadRootId)?.timelineSet + : undefined; + toggleReaction(mx, room, targetEventId, key, shortcode, threadTimelineSet); }, - [mx, room] + [mx, room, threadRootId] ); const handleResend = useCallback( diff --git a/src/app/hooks/timeline/useTimelineEventRenderer.test.tsx b/src/app/hooks/timeline/useTimelineEventRenderer.test.tsx index ffa17bc15..655a53279 100644 --- a/src/app/hooks/timeline/useTimelineEventRenderer.test.tsx +++ b/src/app/hooks/timeline/useTimelineEventRenderer.test.tsx @@ -360,7 +360,7 @@ function createRoom(): Room { findEventById: () => null, getUnfilteredTimelineSet: () => createTimelineSet() as any, getEventReadUpTo: () => null, - getLiveTimeline: () => ({ getEvents: () => [] }), + getLiveTimeline: () => ({ getEvents: () => [], getNeighbouringTimeline: () => null }), getUnreadNotificationCount: () => 0, getMyMembership: () => 'join', hasEncryptionStateEvent: () => false, @@ -461,6 +461,56 @@ function renderEvent(event: MatrixEvent, isStateEvent: boolean) { return { container }; } +function createCustomRoom(overrides: Record) { + const base = createRoom(); + return Object.assign(base, overrides) as unknown as Room; +} + +function createCustomTimelineSet(overrides: Record) { + const base = createTimelineSet(); + return Object.assign(base, overrides) as unknown as EventTimelineSet; +} + +// ── Helper: render with custom opts ───────────────────────────────────────── + +function renderEventWithOverrides( + event: MatrixEvent, + isStateEvent: boolean, + overrides: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + state?: any; + roomOverrides?: Record; + timelineSetOverrides?: Record; + } +) { + const customRoom = createCustomRoom(overrides.roomOverrides ?? {}); + const customTimelineSet = + overrides.timelineSetOverrides != null + ? createCustomTimelineSet(overrides.timelineSetOverrides) + : timelineSet; + const opts = { + ...rendererOpts, + state: { ...rendererOpts.state, ...overrides.state }, + room: customRoom, + }; + const { result } = renderHook(() => useTimelineEventRenderer(opts)); + const renderFn = result.current; + const node = renderFn( + event.getType() ?? 'UNKNOWN', + isStateEvent, + event.getId() ?? 'null', + event, + 0, + customTimelineSet, + false + ); + if (node === null) return { container: null as unknown as HTMLElement }; + const { container } = render(node as any); + return { container }; +} + +// ── Test suite ───────────────────────────────────────────────────────────── + type BranchEntry = { name: string; eventType: string; @@ -589,7 +639,7 @@ const branches: BranchEntry[] = [ createEvent: () => createEvent({ id: '$call:example.com', - type: 'm.call.member', + type: EventType.GroupCallMemberPrefix, content: { 'm.calls': [{ call_id: '!call:example.com', 'm.foci': [] }], }, @@ -674,4 +724,154 @@ describe('useTimelineEventRenderer', () => { expect(container.innerHTML).toMatchSnapshot(); }); }); + + // ── Additional coverage ─────────────────────────────────────────────────── + + describe('activeReplyId === mEventId (marked logic)', () => { + const msgEvent = () => + createEvent({ + id: '$msg:example.com', + type: EventType.RoomMessage, + content: { msgtype: 'm.text', body: 'Hello world!' }, + replyEventId: undefined, + }); + + it('sets data-is-marked="true" when activeReplyId matches', () => { + const evt = msgEvent(); + const { container } = renderEventWithOverrides(evt, false, { + state: { activeReplyId: '$msg:example.com' }, + }); + expect(container).not.toBeNull(); + expect(container.innerHTML).toMatchSnapshot(); + }); + + it('suppresses mark when suppressMark is true', () => { + const evt = msgEvent(); + const { container } = renderEventWithOverrides(evt, false, { + state: { activeReplyId: '$msg:example.com', suppressMark: true }, + }); + expect(container).not.toBeNull(); + expect(container.innerHTML).toMatchSnapshot(); + }); + }); + + describe('reactions bar (useReactionsGuard)', () => { + const msgEvent = () => + createEvent({ + id: '$msg:example.com', + type: EventType.RoomMessage, + content: { msgtype: 'm.text', body: 'Hello world!' }, + replyEventId: undefined, + }); + + function createRelationsWithReactions() { + return { + getSortedAnnotationsByKey: () => + [ + [ + '👍', + new Set([ + createEvent({ + id: '$react:example.com', + type: EventType.Reaction, + sender: ALICE, + content: { + 'm.relates_to': { + rel_type: 'm.annotation', + event_id: '$msg:example.com', + key: '👍', + }, + }, + }), + ]), + ], + ] as [string, Set][], + getRelations: () => [], + on: () => {}, + off: () => {}, + }; + } + + it('renders reactions bar when reactions exist', () => { + const evt = msgEvent(); + const { container } = renderEventWithOverrides(evt, false, { + timelineSetOverrides: { + relations: { + getChildEventsForEvent: () => createRelationsWithReactions(), + } as unknown as EventTimelineSet['relations'], + }, + }); + expect(container).not.toBeNull(); + expect(container.innerHTML).toMatchSnapshot(); + }); + }); + + describe('thread chip', () => { + const msgEvent = () => + createEvent({ + id: '$msg:example.com', + type: EventType.RoomMessage, + content: { msgtype: 'm.text', body: 'Hello world!' }, + replyEventId: undefined, + }); + + it('renders thread chip when room.getThread returns non-null', () => { + const evt = msgEvent(); + const mockThread = { + length: 1, + events: [ + createEvent({ + id: '$reply:example.com', + type: EventType.RoomMessage, + sender: ALICE, + content: { + msgtype: 'm.text', + body: 'reply text', + 'm.relates_to': { + rel_type: 'm.thread', + event_id: '$msg:example.com', + }, + }, + }), + ], + rootEvent: null, + on: () => {}, + off: () => {}, + }; + const { container } = renderEventWithOverrides(evt, false, { + roomOverrides: { getThread: () => mockThread }, + }); + expect(container).not.toBeNull(); + expect(container.innerHTML).toMatchSnapshot(); + }); + }); + + describe('edit event (renderEditTimelineEvent path)', () => { + it('renders an edit event with m.replace relation', () => { + const editEvent = createEvent({ + id: '$edit:example.com', + type: EventType.RoomMessage, + content: { + msgtype: 'm.text', + body: ' * corrected message', + 'm.new_content': { msgtype: 'm.text', body: 'corrected message' }, + 'm.relates_to': { + rel_type: 'm.replace', + event_id: '$msg:example.com', + }, + }, + replyEventId: undefined, + }); + // The edit event's getRelation() must return the m.relates_to info + // for isEditEvent() and getEditTargetId() to work. + editEvent.getRelation = () => + ({ + rel_type: 'm.replace', + event_id: '$msg:example.com', + }) as any; + const { container } = renderEventWithOverrides(editEvent, false, {}); + expect(container).not.toBeNull(); + expect(container.innerHTML).toMatchSnapshot(); + }); + }); }); diff --git a/src/app/hooks/timeline/useTimelineEventRenderer.tsx b/src/app/hooks/timeline/useTimelineEventRenderer.tsx index 6c5c110a7..81a2bd91d 100644 --- a/src/app/hooks/timeline/useTimelineEventRenderer.tsx +++ b/src/app/hooks/timeline/useTimelineEventRenderer.tsx @@ -59,14 +59,17 @@ import { UserAvatar } from '$components/user-avatar'; import type { GetContentCallback } from '$types/matrix/room'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; +import { + getMemberDisplayName, + getTimelineSenderDisplayName, + getMemberAvatarMxc, +} from '$utils/room/display'; import { getEditedEvent, getEditChain, getEditDiffBodies, getEditTargetId, getEventReactions, - getMemberDisplayName, - getTimelineSenderDisplayName, getPreviousEditId, getRedactionTargetEvent, getRedactionTargetId, @@ -78,8 +81,7 @@ import { isMembershipChanged, isThreadRelationEvent, reactionOrEditEvent, - getMemberAvatarMxc, -} from '$utils/room'; +} from '$utils/room/relations'; import { getLinkedTimelines, getLiveTimeline } from '$utils/timeline'; import * as customHtmlCss from '$styles/CustomHtml.css'; import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; diff --git a/src/app/hooks/timeline/useTimelineRendererContext.ts b/src/app/hooks/timeline/useTimelineRendererContext.ts new file mode 100644 index 000000000..ce47d892d --- /dev/null +++ b/src/app/hooks/timeline/useTimelineRendererContext.ts @@ -0,0 +1,232 @@ +import { useMemo } from 'react'; +import type { Room } from '$types/matrix-sdk'; +import type { HTMLReactParserOptions } from 'html-react-parser'; +import type { Opts as LinkifyOpts } from 'linkifyjs'; +import { + factoryRenderLinkifyWithMention, + getReactCustomHtmlParser, + LINKIFY_OPTS, + makeMentionCustomProps, + renderMatrixMention, +} from '$plugins/react-custom-html-parser'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; +import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; +import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; +import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations'; +import { buildAbbrReplaceTextNode } from '$components/message/RenderBody'; +import { usePowerLevelsContext } from '$hooks/usePowerLevels'; +import { useRoomCreators } from '$hooks/useRoomCreators'; +import { useRoomPermissions } from '$hooks/useRoomPermissions'; +import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; +import { useMemberEventParser } from '$hooks/useMemberEventParser'; +import type { ResolvedHiddenEventSettings } from '$state/hooks/settings'; +import { useHiddenEventSettings, useSetting } from '$state/hooks/settings'; +import { settingsAtom, type MessageLayout, type MessageSpacing } from '$state/settings'; +import { nicknamesAtom } from '$state/nicknames'; +import { useAtomValue } from 'jotai'; + +export interface TimelineRendererSettings { + messageLayout: MessageLayout; + messageSpacing: MessageSpacing; + hideReads: boolean; + showDeveloperTools: boolean; + hour24Clock: boolean; + dateFormatString: string; + mediaAutoLoad: boolean; + showBundledPreview: boolean; + showUrlPreview: boolean; + showClientUrlPreview: boolean; + showMaps: boolean; + autoplayStickers: boolean; + hideMemberInReadOnly: boolean; + isReadOnly: boolean; + hideMembershipEvents: boolean; + hideNickAvatarEvents: boolean; + hiddenEvents: ResolvedHiddenEventSettings; + // Not included by default — callers that need these add them on top: + // hideThreadChip?: boolean; +} + +export interface TimelineRendererPermissions { + canRedact: boolean; + canDeleteOwn: boolean; + canSendReaction: boolean; + canPinEvent: boolean; + isReadOnly: boolean; + getMemberPowerTag: ReturnType; + parseMemberEvent: ReturnType; +} + +export interface TimelineRendererContextValue { + settings: TimelineRendererSettings; + linkifyOpts: LinkifyOpts; + htmlReactParserOptions: HTMLReactParserOptions; + permissions: TimelineRendererPermissions; +} + +export function useTimelineRendererContext(room: Room): TimelineRendererContextValue { + const mx = useMatrixClient(); + const nicknames = useAtomValue(nicknamesAtom); + + // Raw settings reads — same set in both RoomTimeline and ThreadDrawer + const [messageLayout] = useSetting(settingsAtom, 'messageLayout'); + const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); + const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); + const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); + const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); + const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); + const [showBundledPreview] = useSetting(settingsAtom, 'bundledPreview'); + const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); + const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview'); + const [clientUrlPreview] = useSetting(settingsAtom, 'clientUrlPreview'); + const [encClientUrlPreview] = useSetting(settingsAtom, 'encClientUrlPreview'); + const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); + const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); + const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); + const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents'); + const [hideNickAvatarEvents] = useSetting(settingsAtom, 'hideNickAvatarEvents'); + const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap'); + const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap'); + const hiddenEvents = useHiddenEventSettings(settingsAtom); + + // Derived settings + const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap; + const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; + const showClientUrlPreview = room.hasEncryptionStateEvent() + ? clientUrlPreview && encClientUrlPreview + : clientUrlPreview; + + // Power levels & permissions + const powerLevels = usePowerLevelsContext(); + const creators = useRoomCreators(room); + const permissions = useRoomPermissions(creators, powerLevels); + const canRedact = permissions.action('redact', mx.getSafeUserId()); + const canDeleteOwn = permissions.event('m.room.redaction', mx.getSafeUserId()); + const canSendReaction = permissions.event('m.reaction', mx.getSafeUserId()); + const canPinEvent = permissions.stateEvent('m.room.pinned_events', mx.getSafeUserId()); + const isReadOnly = !permissions.message(room.hasEncryptionStateEvent(), mx.getSafeUserId()); + const getMemberPowerTag = useGetMemberPowerTag(room, creators, powerLevels); + const parseMemberEvent = useMemberEventParser(); + + // linkifyOpts + const mentionClickHandler = useMentionClickHandler(room.roomId); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); + + const linkifyOpts = useMemo( + () => ({ + ...LINKIFY_OPTS, + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler + ), + }), + [mx, room.roomId, mentionClickHandler, nicknames, settingsLinkBaseUrl] + ); + + // htmlReactParserOptions + const useAuthentication = useMediaAuthentication(); + const spoilerClickHandler = useSpoilerClickHandler(); + const abbrMap = useRoomAbbreviationsContext(); + + const htmlReactParserOptions = useMemo( + () => + getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, + linkifyOpts, + useAuthentication, + handleSpoilerClick: spoilerClickHandler, + handleMentionClick: mentionClickHandler, + nicknames, + autoplayEmojis, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, + replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts), + }), + [ + mx, + room.roomId, + linkifyOpts, + autoplayEmojis, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, + mentionClickHandler, + nicknames, + useAuthentication, + spoilerClickHandler, + settingsLinkBaseUrl, + abbrMap, + ] + ); + + const settings = useMemo( + () => ({ + messageLayout, + messageSpacing, + hideReads, + showDeveloperTools, + hour24Clock, + dateFormatString, + mediaAutoLoad, + showBundledPreview, + showUrlPreview, + showClientUrlPreview, + showMaps, + autoplayStickers, + hideMemberInReadOnly, + isReadOnly, + hideMembershipEvents, + hideNickAvatarEvents, + hiddenEvents, + }), + [ + messageLayout, + messageSpacing, + hideReads, + showDeveloperTools, + hour24Clock, + dateFormatString, + mediaAutoLoad, + showBundledPreview, + showUrlPreview, + showClientUrlPreview, + showMaps, + autoplayStickers, + hideMemberInReadOnly, + isReadOnly, + hideMembershipEvents, + hideNickAvatarEvents, + hiddenEvents, + ] + ); + + return { + settings, + linkifyOpts, + htmlReactParserOptions, + permissions: { + canRedact, + canDeleteOwn, + canSendReaction, + canPinEvent, + isReadOnly, + getMemberPowerTag, + parseMemberEvent, + }, + }; +} diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts index e369d5423..235b616f6 100644 --- a/src/app/hooks/timeline/useTimelineSync.ts +++ b/src/app/hooks/timeline/useTimelineSync.ts @@ -15,6 +15,7 @@ import type { import { Direction, RoomEvent, RelationType, ThreadEvent } from '$types/matrix-sdk'; import { useAlive } from '$hooks/useAlive'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; import { markAsRead } from '$utils/notifications'; import { getInitialTimeline, @@ -29,9 +30,9 @@ import { const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000; -export type PaginationStatus = 'idle' | 'loading' | 'error'; +type PaginationStatus = 'idle' | 'loading' | 'error'; -export type TimelineState = { +type TimelineState = { linkedTimelines: EventTimeline[]; }; @@ -299,8 +300,8 @@ const useRelationUpdate = (room: Room, onRelation: () => void) => { const onRelationRef = useRef(onRelation); onRelationRef.current = onRelation; - useEffect(() => { - const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = ( + const handleTimelineEvent = useCallback( + ( mEvent: MatrixEvent, eventRoom: Room | undefined, _toStartOfTimeline: boolean | undefined, @@ -311,12 +312,11 @@ const useRelationUpdate = (room: Room, onRelation: () => void) => { if (mEvent.getRelation()?.rel_type === RelationType.Replace) { onRelationRef.current(); } - }; - room.on(RoomEvent.Timeline, handleTimelineEvent); - return () => { - room.removeListener(RoomEvent.Timeline, handleTimelineEvent); - }; - }, [room]); + }, + [room] + ); + + useMatrixEvent(room, RoomEvent.Timeline, handleTimelineEvent); }; const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => { @@ -523,20 +523,15 @@ export function useTimelineSync({ ) ); - useEffect(() => { - const handleLocalEchoUpdated: RoomEventHandlerMap[RoomEvent.LocalEchoUpdated] = ( - _mEvent: MatrixEvent, - eventRoom: Room | undefined - ) => { + const handleLocalEchoUpdated = useCallback( + (_mEvent: MatrixEvent, eventRoom: Room | undefined) => { if (eventRoom?.roomId !== room.roomId) return; setTimeline((ct) => ({ ...ct })); - }; + }, + [room, setTimeline] + ); - room.on(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); - return () => { - room.removeListener(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); - }; - }, [room, setTimeline]); + useMatrixEvent(room, RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); useLiveTimelineRefresh( room, diff --git a/src/app/hooks/useAsyncCallback.ts b/src/app/hooks/useAsyncCallback.ts index 3412fc87e..d0b4f7819 100644 --- a/src/app/hooks/useAsyncCallback.ts +++ b/src/app/hooks/useAsyncCallback.ts @@ -74,7 +74,7 @@ export const useAsync = ( }); }); } - throw e; + return undefined as never; } if (currentReqNumber !== reqNumberRef.current) return undefined as never; diff --git a/src/app/hooks/useGroupDMMembers.ts b/src/app/hooks/useGroupDMMembers.ts index 01d8b074d..da5532e7d 100644 --- a/src/app/hooks/useGroupDMMembers.ts +++ b/src/app/hooks/useGroupDMMembers.ts @@ -1,5 +1,5 @@ import type { MatrixClient, Room } from '$types/matrix-sdk'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; export type GroupMemberInfo = { userId: string; diff --git a/src/app/hooks/useIgnoredUsers.ts b/src/app/hooks/useIgnoredUsers.ts index 27a81be77..fb8f909a3 100644 --- a/src/app/hooks/useIgnoredUsers.ts +++ b/src/app/hooks/useIgnoredUsers.ts @@ -3,7 +3,7 @@ import { useMemo } from 'react'; import { useAccountData } from './useAccountData'; import { EventType } from '$types/matrix-sdk'; -export type IgnoredUserListContent = { +type IgnoredUserListContent = { ignored_users?: Record; }; diff --git a/src/app/hooks/useImagePackRooms.ts b/src/app/hooks/useImagePackRooms.ts index 6dd130bbc..c8c0fe773 100644 --- a/src/app/hooks/useImagePackRooms.ts +++ b/src/app/hooks/useImagePackRooms.ts @@ -1,6 +1,6 @@ import type { Room } from '$types/matrix-sdk'; import { useMemo } from 'react'; -import { getAllParents } from '$utils/room'; +import { getAllParents } from '$utils/room/hierarchy'; import { useMatrixClient } from './useMatrixClient'; export const useImagePackRooms = ( diff --git a/src/app/hooks/useKeyBackup.ts b/src/app/hooks/useKeyBackup.ts index fe3831340..2c6eb1736 100644 --- a/src/app/hooks/useKeyBackup.ts +++ b/src/app/hooks/useKeyBackup.ts @@ -8,17 +8,13 @@ import { CryptoEvent } from '$types/matrix-sdk'; import { useCallback, useEffect, useState } from 'react'; import * as Sentry from '@sentry/react'; import { useMatrixClient } from './useMatrixClient'; +import { useMatrixEvent } from './useMatrixEvent'; import { useAlive } from './useAlive'; const useKeyBackupStatusChange = (onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupStatus]) => { const mx = useMatrixClient(); - useEffect(() => { - mx.on(CryptoEvent.KeyBackupStatus, onChange); - return () => { - mx.removeListener(CryptoEvent.KeyBackupStatus, onChange); - }; - }, [mx, onChange]); + useMatrixEvent(mx, CryptoEvent.KeyBackupStatus, onChange); }; export const useKeyBackupStatus = (crypto: CryptoApi): boolean => { @@ -43,23 +39,13 @@ const useKeyBackupSessionsRemainingChange = ( ) => { const mx = useMatrixClient(); - useEffect(() => { - mx.on(CryptoEvent.KeyBackupSessionsRemaining, onChange); - return () => { - mx.removeListener(CryptoEvent.KeyBackupSessionsRemaining, onChange); - }; - }, [mx, onChange]); + useMatrixEvent(mx, CryptoEvent.KeyBackupSessionsRemaining, onChange); }; const useKeyBackupFailedChange = (onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupFailed]) => { const mx = useMatrixClient(); - useEffect(() => { - mx.on(CryptoEvent.KeyBackupFailed, onChange); - return () => { - mx.removeListener(CryptoEvent.KeyBackupFailed, onChange); - }; - }, [mx, onChange]); + useMatrixEvent(mx, CryptoEvent.KeyBackupFailed, onChange); }; export const useKeyBackupDecryptionKeyCached = ( @@ -67,12 +53,7 @@ export const useKeyBackupDecryptionKeyCached = ( ) => { const mx = useMatrixClient(); - useEffect(() => { - mx.on(CryptoEvent.KeyBackupDecryptionKeyCached, onChange); - return () => { - mx.removeListener(CryptoEvent.KeyBackupDecryptionKeyCached, onChange); - }; - }, [mx, onChange]); + useMatrixEvent(mx, CryptoEvent.KeyBackupDecryptionKeyCached, onChange); }; export const useKeyBackupSync = (): [number, string | undefined] => { diff --git a/src/app/hooks/useLocalRoomSummary.ts b/src/app/hooks/useLocalRoomSummary.ts index 76f0e03d0..42f3255e1 100644 --- a/src/app/hooks/useLocalRoomSummary.ts +++ b/src/app/hooks/useLocalRoomSummary.ts @@ -1,7 +1,7 @@ import type { JoinRule, Room } from '$types/matrix-sdk'; import { GuestAccess, HistoryVisibility, EventType } from '$types/matrix-sdk'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; export type LocalRoomSummary = { roomId: string; diff --git a/src/app/hooks/useMatrixEvent.ts b/src/app/hooks/useMatrixEvent.ts new file mode 100644 index 000000000..1bcd4d4fe --- /dev/null +++ b/src/app/hooks/useMatrixEvent.ts @@ -0,0 +1,24 @@ +import { useEffect } from 'react'; + +/** + * Subscribes to an event on a Matrix SDK emitter and auto-cleans up. + * Replaces hand-rolled `emitter.on(event, handler)` + `return () => emitter.removeListener(event, handler)` in useEffect. + */ +// oxlint-disable typescript/no-explicit-any +export function useMatrixEvent( + emitter: + | { + on: (event: any, handler: (...args: any[]) => void) => any; + removeListener: (event: any, handler: (...args: any[]) => void) => any; + } + | undefined + | null, + eventName: string, + handler: (...args: any[]) => void +): void { + useEffect(() => { + if (!emitter) return undefined; + emitter.on(eventName, handler); + return () => emitter.removeListener(eventName, handler); + }, [emitter, eventName, handler]); +} diff --git a/src/app/hooks/useMemberEventParser.tsx b/src/app/hooks/useMemberEventParser.tsx index 03de8b965..dd19e02c0 100644 --- a/src/app/hooks/useMemberEventParser.tsx +++ b/src/app/hooks/useMemberEventParser.tsx @@ -15,7 +15,7 @@ import { } from '$components/icons/phosphor'; import { getMxIdLocalPart } from '$utils/matrix'; -import { isMembershipChanged } from '$utils/room'; +import { isMembershipChanged } from '$utils/room/relations'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useSableCosmetics } from './useSableCosmetics'; import { useMatrixClient } from './useMatrixClient'; diff --git a/src/app/hooks/useMembership.ts b/src/app/hooks/useMembership.ts index 63bcbb2b6..3b49d4d4e 100644 --- a/src/app/hooks/useMembership.ts +++ b/src/app/hooks/useMembership.ts @@ -1,6 +1,7 @@ -import { useEffect, useState } from 'react'; +import { useCallback, useState } from 'react'; import type { Membership, Room, RoomMemberEventHandlerMap } from '$types/matrix-sdk'; import { RoomMemberEvent, KnownMembership } from '$types/matrix-sdk'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; export const useMembership = (room: Room, userId: string): Membership => { const member = room.getMember(userId); @@ -9,20 +10,16 @@ export const useMembership = (room: Room, userId: string): Membership => { () => member?.membership ?? KnownMembership.Leave ); - useEffect(() => { - const handleMembershipChange: RoomMemberEventHandlerMap[RoomMemberEvent.Membership] = ( - event, - m - ) => { + const handleMembershipChange: RoomMemberEventHandlerMap[RoomMemberEvent.Membership] = useCallback( + (event, m) => { if (event.getRoomId() === room.roomId && m.userId === userId) { setMembership(m.membership ?? KnownMembership.Leave); } - }; - member?.on(RoomMemberEvent.Membership, handleMembershipChange); - return () => { - member?.removeListener(RoomMemberEvent.Membership, handleMembershipChange); - }; - }, [room, member, userId]); + }, + [room.roomId, userId] + ); + + useMatrixEvent(member, RoomMemberEvent.Membership, handleMembershipChange); return membership; }; diff --git a/src/app/hooks/useMenuAnchor.test.ts b/src/app/hooks/useMenuAnchor.test.ts new file mode 100644 index 000000000..30694d501 --- /dev/null +++ b/src/app/hooks/useMenuAnchor.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import type { MenuAnchor } from './useMenuAnchor'; +import { useMenuAnchor } from './useMenuAnchor'; + +interface FireLongPressOptions { + /** A mock element with `getBoundingClientRect` for the long press target. */ + element?: HTMLElement; +} + +/** + * Simulates a full long press cycle on the returned trigger props: + * touchstart → advance timer by 500ms → fire callback → touchend. + * After this, the synthetic click/contextmenu that browsers follow with + * should be suppressed. + */ +function fireLongPress( + triggerProps: MenuAnchor['triggerProps'], + opts: FireLongPressOptions = {} +) { + const element = + opts.element ?? + ({ + getBoundingClientRect: () => ({ x: 50, y: 100, width: 80, height: 40 }) as DOMRect, + } as HTMLElement); + + const touch = { + touches: [{ clientX: 50, clientY: 100 } as Touch], + changedTouches: [{ clientX: 50, clientY: 100 } as Touch], + preventDefault: vi.fn<() => void>(), + }; + + act(() => { + triggerProps.onTouchStart({ + currentTarget: element, + ...touch, + nativeEvent: new TouchEvent('touchstart'), + } as unknown as React.TouchEvent); + }); + + act(() => { + vi.advanceTimersByTime(500); + }); + + act(() => { + triggerProps.onTouchEnd(); + }); +} + +function createMockElement(rect: Partial = {}): HTMLElement { + return { + getBoundingClientRect: () => + ({ + x: 0, + y: 0, + width: 100, + height: 50, + top: 0, + right: 100, + bottom: 50, + left: 0, + ...rect, + }) as DOMRect, + } as HTMLElement; +} + +import type * as UseMobileLongPressModule from './useMobileLongPress'; + +// ── Mock modules ──────────────────────────────────────────────────────────── +vi.mock('./useMobileLongPress', async (importActual) => { + const actual = (await importActual()) as typeof UseMobileLongPressModule; + return { + ...actual, + useMobileLongPress: actual.useMobileLongPress, + }; +}); + +describe('useMenuAnchor', () => { + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + }); + + describe('toggle behavior of openAt', () => { + it('sets the anchor to the bounding rect of the element', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement({ x: 10, y: 20, width: 120, height: 60 }); + + act(() => { + result.current.openAt(element); + }); + + const anchor = result.current.anchor; + expect(anchor).not.toBeUndefined(); + expect(anchor!.x).toBe(10); + expect(anchor!.y).toBe(20); + expect(anchor!.width).toBe(120); + expect(anchor!.height).toBe(60); + }); + + it('toggles off when calling openAt twice with the same element', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement(); + + act(() => { + result.current.openAt(element); + }); + expect(result.current.anchor).not.toBeUndefined(); + + act(() => { + result.current.openAt(element); + }); + expect(result.current.anchor).toBeUndefined(); + }); + + it('sets anchor then clears on close()', () => { + const { result } = renderHook(() => useMenuAnchor()); + + act(() => { + result.current.openAt(createMockElement()); + }); + expect(result.current.anchor).not.toBeUndefined(); + + act(() => { + result.current.close(); + }); + expect(result.current.anchor).toBeUndefined(); + }); + }); + + describe('onClick', () => { + it('opens the menu at the clicked element', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement({ x: 30, y: 40 }); + + act(() => { + result.current.triggerProps.onClick({ + currentTarget: element, + preventDefault: vi.fn<() => void>(), + stopPropagation: vi.fn<() => void>(), + } as unknown as React.MouseEvent); + }); + + expect(result.current.anchor).not.toBeUndefined(); + expect(result.current.anchor!.x).toBe(30); + expect(result.current.anchor!.y).toBe(40); + }); + + it('is suppressed after a long press', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement({ x: 50, y: 100 }); + + // Perform a long press — this opens the menu via openAt + fireLongPress(result.current.triggerProps, { element }); + + // The long press already opened it + expect(result.current.anchor).not.toBeUndefined(); + expect(result.current.anchor!.x).toBe(50); + expect(result.current.anchor!.y).toBe(100); + + // Now simulate the synthetic click that browsers send after touchend. + // It must NOT toggle it shut. + act(() => { + result.current.triggerProps.onClick({ + currentTarget: createMockElement({ x: 999, y: 999 }), + preventDefault: vi.fn<() => void>(), + stopPropagation: vi.fn<() => void>(), + } as unknown as React.MouseEvent); + }); + + // Anchor should still be at the long press position, not toggled. + expect(result.current.anchor).not.toBeUndefined(); + expect(result.current.anchor!.x).toBe(50); + }); + }); + + describe('onContextMenu', () => { + it('anchors the menu at the pointer position', () => { + const { result } = renderHook(() => useMenuAnchor()); + + act(() => { + result.current.triggerProps.onContextMenu({ + currentTarget: createMockElement(), + preventDefault: vi.fn<() => void>(), + stopPropagation: vi.fn<() => void>(), + nativeEvent: { clientX: 120, clientY: 300 } as MouseEvent, + } as unknown as React.MouseEvent); + }); + + const anchor = result.current.anchor; + expect(anchor).not.toBeUndefined(); + // Context menu anchors to pointer, so width/height are 0 + expect(anchor!.x).toBe(120); + expect(anchor!.y).toBe(300); + expect(anchor!.width).toBe(0); + expect(anchor!.height).toBe(0); + }); + + it('prevents default behavior', () => { + const { result } = renderHook(() => useMenuAnchor()); + const preventDefault = vi.fn<() => void>(); + + act(() => { + result.current.triggerProps.onContextMenu({ + currentTarget: createMockElement(), + preventDefault, + stopPropagation: vi.fn<() => void>(), + nativeEvent: { clientX: 0, clientY: 0 } as MouseEvent, + } as unknown as React.MouseEvent); + }); + + expect(preventDefault).toHaveBeenCalled(); + }); + + it('is suppressed after a long press', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement({ x: 50, y: 100 }); + + fireLongPress(result.current.triggerProps, { element }); + expect(result.current.anchor).not.toBeUndefined(); + expect(result.current.anchor!.x).toBe(50); + + // Synthetic contextmenu (browsers dispatch it after long press on some + // platforms; our handler clears the fired flag and returns). + act(() => { + result.current.triggerProps.onContextMenu({ + currentTarget: createMockElement({ x: 999, y: 999 }), + preventDefault: vi.fn<() => void>(), + stopPropagation: vi.fn<() => void>(), + nativeEvent: { clientX: 999, clientY: 999 } as MouseEvent, + } as unknown as React.MouseEvent); + }); + + // Should remain anchored to the long-press element position. + expect(result.current.anchor).not.toBeUndefined(); + expect(result.current.anchor!.x).toBe(50); + }); + }); + + describe('isPressing', () => { + it('is false initially', () => { + const { result } = renderHook(() => useMenuAnchor()); + expect(result.current.isPressing).toBe(false); + }); + + it('becomes true during a long press (before timeout fires)', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement(); + + act(() => { + result.current.triggerProps.onTouchStart({ + currentTarget: element, + touches: [{ clientX: 10, clientY: 10 } as Touch], + changedTouches: [{ clientX: 10, clientY: 10 } as Touch], + preventDefault: vi.fn<() => void>(), + nativeEvent: new TouchEvent('touchstart'), + } as unknown as React.TouchEvent); + }); + + expect(result.current.isPressing).toBe(true); + }); + + it('is false after a long press completes', () => { + const { result } = renderHook(() => useMenuAnchor()); + fireLongPress(result.current.triggerProps, { element: createMockElement() }); + expect(result.current.isPressing).toBe(false); + }); + + it('is false after touch is cancelled before timeout', () => { + const { result } = renderHook(() => useMenuAnchor()); + const element = createMockElement(); + + act(() => { + result.current.triggerProps.onTouchStart({ + currentTarget: element, + touches: [{ clientX: 10, clientY: 10 } as Touch], + changedTouches: [{ clientX: 10, clientY: 10 } as Touch], + preventDefault: vi.fn<() => void>(), + nativeEvent: new TouchEvent('touchstart'), + } as unknown as React.TouchEvent); + }); + + // Less than the 500ms threshold + act(() => { + vi.advanceTimersByTime(200); + }); + expect(result.current.isPressing).toBe(true); + + act(() => { + result.current.triggerProps.onTouchCancel(); + }); + + expect(result.current.isPressing).toBe(false); + }); + }); +}); diff --git a/src/app/hooks/useMenuAnchor.ts b/src/app/hooks/useMenuAnchor.ts index c58df29f1..7677edbc4 100644 --- a/src/app/hooks/useMenuAnchor.ts +++ b/src/app/hooks/useMenuAnchor.ts @@ -1,6 +1,7 @@ import type { MouseEventHandler, TouchEvent as ReactTouchEvent } from 'react'; import { useCallback, useRef, useState } from 'react'; import type { RectCords } from 'folds'; +import { getMouseEventCords } from '$utils/dom'; import { useMobileLongPress } from './useMobileLongPress'; type TriggerProps = { @@ -21,15 +22,25 @@ export type MenuAnchor = { openAt: (element: HTMLElement) => void; /** Click, right-click and long-press wiring for the trigger element. */ triggerProps: TriggerProps; + /** True once if a long press just fired, for callers that own their contextmenu handler. */ + consumeLongPressFired: () => boolean; +}; + +type MenuAnchorOptions = { + /** Replaces the default "open at the trigger", for triggers that show their own surface. */ + onLongPress?: () => void; }; /** * Owns the anchor state behind a menu and gives its trigger a touch path, so a * menu is never reachable by right-click alone. */ -export function useMenuAnchor(): MenuAnchor { +export function useMenuAnchor( + options?: MenuAnchorOptions +): MenuAnchor { const [anchor, setAnchor] = useState(); const triggerRef = useRef(null); + const onLongPress = options?.onLongPress; const close = useCallback(() => setAnchor(undefined), []); @@ -39,13 +50,27 @@ export function useMenuAnchor(): MenuAnchor }, []); const longPress = useMobileLongPress(() => { + if (onLongPress) { + onLongPress(); + return; + } if (triggerRef.current) openAt(triggerRef.current); }); + const consumeLongPressFired = useCallback(() => { + if (!longPress.firedRef.current) return false; + longPress.firedRef.current = false; + return true; + }, [longPress]); + const onClick: MouseEventHandler = useCallback( (evt) => { // The long-press timer already opened it; the synthetic click would toggle it shut. - if (longPress.firedRef.current) return; + // Clearing here matters on mouse input, where no further touchstart resets it. + if (longPress.firedRef.current) { + longPress.firedRef.current = false; + return; + } openAt(evt.currentTarget); }, [longPress, openAt] @@ -55,10 +80,15 @@ export function useMenuAnchor(): MenuAnchor (evt) => { evt.preventDefault(); // The long-press timer already opened it; a synthetic contextmenu would toggle it shut. - if (longPress.firedRef.current) return; - openAt(evt.currentTarget); + if (longPress.firedRef.current) { + longPress.firedRef.current = false; + return; + } + // Call sites key align/offset on `width === 0` to lay out from the cursor. + // Assigning, not toggling: nested handlers fire this twice as the event bubbles. + setAnchor(getMouseEventCords(evt.nativeEvent)); }, - [longPress, openAt] + [longPress] ); const onTouchStart = useCallback( @@ -72,6 +102,7 @@ export function useMenuAnchor(): MenuAnchor return { anchor, isPressing: longPress.isPressing, + consumeLongPressFired, close, openAt, triggerProps: { diff --git a/src/app/hooks/useMessageTargetRooms.ts b/src/app/hooks/useMessageTargetRooms.ts new file mode 100644 index 000000000..4b7d7aae6 --- /dev/null +++ b/src/app/hooks/useMessageTargetRooms.ts @@ -0,0 +1,28 @@ +import { useMemo } from 'react'; +import { useAtomValue } from 'jotai'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { useAllJoinedRoomsSet, useGetRoom } from './useGetRoom'; +import { factoryRoomIdByActivity } from '$utils/sort'; +import { useMatrixClient } from './useMatrixClient'; + +/** + * Returns a sorted list of room IDs that can receive a forwarded/shared message. + * Excludes space rooms and rooms where the user cannot send messages. + */ +export function useMessageTargetRooms(): string[] { + const mx = useMatrixClient(); + const allRooms = useAtomValue(allRoomsAtom); + const allJoinedRooms = useAllJoinedRoomsSet(); + const getRoom = useGetRoom(allJoinedRooms); + + return useMemo( + () => + allRooms + .filter((id) => { + const target = getRoom(id); + return !!target && !target.isSpaceRoom() && target.maySendMessage(); + }) + .sort(factoryRoomIdByActivity(mx)), + [allRooms, getRoom, mx] + ); +} diff --git a/src/app/hooks/useNotificationJumper.ts b/src/app/hooks/useNotificationJumper.ts index a03342fc5..8a41fef8e 100644 --- a/src/app/hooks/useNotificationJumper.ts +++ b/src/app/hooks/useNotificationJumper.ts @@ -8,7 +8,7 @@ import { useSyncState } from './useSyncState'; import { useMatrixClient } from './useMatrixClient'; import { getCanonicalAliasOrRoomId } from '../utils/matrix'; import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '../pages/pathUtils'; -import { getOrphanParents, guessPerfectParent } from '../utils/room'; +import { getOrphanParents, guessPerfectParent } from '../utils/room/hierarchy'; import { roomToParentsAtom } from '../state/room/roomToParents'; import { createLogger } from '../utils/debug'; diff --git a/src/app/hooks/usePowerLevels.ts b/src/app/hooks/usePowerLevels.ts index f3b64834a..6f13c53be 100644 --- a/src/app/hooks/usePowerLevels.ts +++ b/src/app/hooks/usePowerLevels.ts @@ -2,7 +2,7 @@ import type { MatrixEvent, Room } from '$types/matrix-sdk'; import { createContext, useCallback, useContext, useMemo, useState } from 'react'; import { produce } from 'immer'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { useStateEvent } from './useStateEvent'; import { useStateEventCallback } from './useStateEventCallback'; import { useMatrixClient } from './useMatrixClient'; diff --git a/src/app/hooks/useRecentEmoji.ts b/src/app/hooks/useRecentEmoji.ts index 9993e9222..d90c0205b 100644 --- a/src/app/hooks/useRecentEmoji.ts +++ b/src/app/hooks/useRecentEmoji.ts @@ -1,6 +1,7 @@ -import { useEffect, useState } from 'react'; +import { useCallback, useState } from 'react'; import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; import { ClientEvent } from '$types/matrix-sdk'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; import { getRecentEmojis } from '$plugins/recent-emoji'; import type { IEmoji } from '$plugins/emoji'; @@ -9,8 +10,8 @@ import { CustomAccountDataEvent } from '$types/matrix/accountData'; export const useRecentEmoji = (mx: MatrixClient, limit?: number): IEmoji[] => { const [recentEmoji, setRecentEmoji] = useState(() => getRecentEmojis(mx, limit)); - useEffect(() => { - const handleAccountData = (event: MatrixEvent) => { + const handleAccountData = useCallback( + (event: MatrixEvent) => { if ( event.getType() !== (CustomAccountDataEvent.RecentEmoji as string) && event.getType() !== (CustomAccountDataEvent.LegacyElementRecentEmoji as string) @@ -18,13 +19,11 @@ export const useRecentEmoji = (mx: MatrixClient, limit?: number): IEmoji[] => { return; } setRecentEmoji(getRecentEmojis(mx, limit)); - }; + }, + [mx, limit] + ); - mx.on(ClientEvent.AccountData, handleAccountData); - return () => { - mx.removeListener(ClientEvent.AccountData, handleAccountData); - }; - }, [mx, limit]); + useMatrixEvent(mx, ClientEvent.AccountData, handleAccountData); return recentEmoji; }; diff --git a/src/app/hooks/useRoomAbbreviations.ts b/src/app/hooks/useRoomAbbreviations.ts index b6bd30ba1..81c544419 100644 --- a/src/app/hooks/useRoomAbbreviations.ts +++ b/src/app/hooks/useRoomAbbreviations.ts @@ -4,7 +4,7 @@ import type { Room } from '$types/matrix-sdk'; import type { RoomAbbreviationsContent } from '$utils/abbreviations'; import { buildAbbreviationsMap } from '$utils/abbreviations'; -import { getAllParents, getStateEvent } from '$utils/room'; +import { getAllParents, getStateEvent } from '$utils/room/hierarchy'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { useMatrixClient } from './useMatrixClient'; import { useStateEvent } from './useStateEvent'; diff --git a/src/app/hooks/useRoomAliases.ts b/src/app/hooks/useRoomAliases.ts index e405843b3..fce7ba3e9 100644 --- a/src/app/hooks/useRoomAliases.ts +++ b/src/app/hooks/useRoomAliases.ts @@ -6,7 +6,7 @@ import type { StateEvents, } from '$types/matrix-sdk'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import type { AsyncState } from './useAsyncCallback'; import { useAsyncCallback } from './useAsyncCallback'; import { useMatrixClient } from './useMatrixClient'; diff --git a/src/app/hooks/useRoomCreators.ts b/src/app/hooks/useRoomCreators.ts index 3d5722595..0378f3e55 100644 --- a/src/app/hooks/useRoomCreators.ts +++ b/src/app/hooks/useRoomCreators.ts @@ -1,7 +1,7 @@ import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { useMemo } from 'react'; import type { IRoomCreateContent } from '$types/matrix/room'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { creatorsSupported } from '$utils/roomSupport'; import { useStateEvent } from './useStateEvent'; import { EventType } from '$types/matrix-sdk'; diff --git a/src/app/hooks/useRoomLatestRenderedEvent.ts b/src/app/hooks/useRoomLatestRenderedEvent.ts index 95284588e..c44e93a5f 100644 --- a/src/app/hooks/useRoomLatestRenderedEvent.ts +++ b/src/app/hooks/useRoomLatestRenderedEvent.ts @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; -import { isMembershipChanged, reactionOrEditEvent } from '$utils/room'; +import { isMembershipChanged, reactionOrEditEvent } from '$utils/room/relations'; export const useRoomLatestRenderedEvent = (room: Room) => { const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents'); diff --git a/src/app/hooks/useRoomMenuActions.ts b/src/app/hooks/useRoomMenuActions.ts new file mode 100644 index 000000000..ee47da83c --- /dev/null +++ b/src/app/hooks/useRoomMenuActions.ts @@ -0,0 +1,125 @@ +import { useCallback, useEffect, useState } from 'react'; +import { useAtomValue } from 'jotai'; +import type { Room } from '$types/matrix-sdk'; + +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { useSpaceOptionally } from '$hooks/useSpace'; +import { getCanonicalAliasOrRoomId, isRoomAlias, removeRoomIdFromMDirect } from '$utils/matrix'; +import { useRoomUnread } from '$state/hooks/unread'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { usePowerLevels } from '$hooks/usePowerLevels'; +import { markAsRead } from '$utils/notifications'; +import { copyToClipboard } from '$utils/dom'; +import { confirm } from '$components/confirm/confirm'; +import { showToast } from '$state/toast'; +import { useOpenRoomSettings } from '$state/hooks/roomSettings'; +import { getMatrixToRoom } from '$plugins/matrix-to'; +import { getViaServers } from '$plugins/via-servers'; +import { useRoomCreators } from '$hooks/useRoomCreators'; +import { useRoomPermissions } from '$hooks/useRoomPermissions'; +import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { mDirectAtom } from '$state/mDirectList'; +import { useRoomNavigate } from '$hooks/useRoomNavigate'; + +export function useRoomMenuActions(room: Room) { + const mx = useMatrixClient(); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); + const unread = useRoomUnread(room.roomId, roomToUnreadAtom); + const powerLevels = usePowerLevels(room); + const creators = useRoomCreators(room); + + const permissions = useRoomPermissions(creators, powerLevels); + const canInvite = permissions.action('invite', mx.getSafeUserId()); + const mDirects = useAtomValue(mDirectAtom); + const isDirectConversation = mDirects.has(room.roomId); + + const openSettingsFn = useOpenRoomSettings(); + const space = useSpaceOptionally(); + const { navigateRoom } = useRoomNavigate(); + + const [invitePrompt, setInvitePrompt] = useState(false); + const [directInvitePrompt, setDirectInvitePrompt] = useState(false); + + const [convertState, convertToRoom] = useAsyncCallback( + useCallback(async () => { + await removeRoomIdFromMDirect(mx, room.roomId); + }, [mx, room.roomId]) + ); + + const handleMarkAsRead = useCallback(() => { + markAsRead(mx, room.roomId, hideReads); + }, [mx, room.roomId, hideReads]); + + const handleInvite = useCallback(() => { + if (isDirectConversation) { + setDirectInvitePrompt(true); + return; + } + setInvitePrompt(true); + }, [isDirectConversation]); + + const handleInviteDirect = useCallback(() => { + setDirectInvitePrompt(false); + setInvitePrompt(true); + }, []); + + const handleConvertAndInvite = useCallback(() => { + if (convertState.status === AsyncStatus.Loading) return; + convertToRoom().catch(() => {}); + }, [convertState.status, convertToRoom]); + + useEffect(() => { + if (convertState.status === AsyncStatus.Success) { + setDirectInvitePrompt(false); + setInvitePrompt(true); + } + }, [convertState.status]); + + const handleCopyLink = useCallback(() => { + const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, room.roomId); + const viaServers = isRoomAlias(roomIdOrAlias) ? undefined : getViaServers(room); + copyToClipboard(getMatrixToRoom(roomIdOrAlias, viaServers)); + }, [mx, room]); + + const handleOpenSettings = useCallback(() => { + openSettingsFn(room.roomId, space?.roomId); + }, [openSettingsFn, room.roomId, space?.roomId]); + + /** Resolves true only when the room was actually left, so callers can keep the menu open otherwise. */ + const handleLeaveRoom = useCallback(async (): Promise => { + const ok = await confirm({ + title: 'Leave Room', + description: 'Are you sure you want to leave this room?', + action: 'Leave', + variant: 'Critical', + }); + if (!ok) return false; + try { + await mx.leave(room.roomId); + return true; + } catch (e) { + showToast(`Failed to leave room: ${e instanceof Error ? e.message : 'unknown error'}`); + return false; + } + }, [mx, room.roomId]); + + return { + handleMarkAsRead, + handleInvite, + handleCopyLink, + handleOpenSettings, + handleLeaveRoom, + canInvite, + unread, + invitePrompt, + setInvitePrompt, + directInvitePrompt, + setDirectInvitePrompt, + handleInviteDirect, + handleConvertAndInvite, + convertState, + navigateRoom, + }; +} diff --git a/src/app/hooks/useRoomNavigate.ts b/src/app/hooks/useRoomNavigate.ts index 45945ca4f..8e87d18d4 100644 --- a/src/app/hooks/useRoomNavigate.ts +++ b/src/app/hooks/useRoomNavigate.ts @@ -10,7 +10,7 @@ import { getSpaceRoomPath, resolveSection, } from '$pages/pathUtils'; -import { getOrphanParents, guessPerfectParent } from '$utils/room'; +import { getOrphanParents, guessPerfectParent } from '$utils/room/hierarchy'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { mDirectAtom } from '$state/mDirectList'; import { lastVisitedRoomAtom } from '$state/room/lastRoom'; diff --git a/src/app/hooks/useRoomState.ts b/src/app/hooks/useRoomState.ts index 24844c4de..4d765e1e1 100644 --- a/src/app/hooks/useRoomState.ts +++ b/src/app/hooks/useRoomState.ts @@ -1,6 +1,7 @@ -import type { MatrixEvent, Room, RoomStateEventHandlerMap } from '$types/matrix-sdk'; +import type { MatrixEvent, Room } from '$types/matrix-sdk'; import { Direction, RoomStateEvent } from '$types/matrix-sdk'; -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; export type StateKeyToEvents = Map; export type StateTypeToState = Map; @@ -24,17 +25,12 @@ export const useRoomState = (room: Room): StateTypeToState => { const [state, setState] = useState(getState); - useEffect(() => { - const roomState = room.getLiveTimeline().getState(Direction.Forward); - const handler: RoomStateEventHandlerMap[RoomStateEvent.Events] = () => { - setState(getState()); - }; + const roomState = useMemo(() => room.getLiveTimeline().getState(Direction.Forward), [room]); + const handler = useCallback(() => { + setState(getState()); + }, [getState]); - roomState?.on(RoomStateEvent.Events, handler); - return () => { - roomState?.removeListener(RoomStateEvent.Events, handler); - }; - }, [room, getState]); + useMatrixEvent(roomState, RoomStateEvent.Events, handler); return state; }; diff --git a/src/app/hooks/useRoomWidgets.ts b/src/app/hooks/useRoomWidgets.ts index 45725db4a..e605fea4c 100644 --- a/src/app/hooks/useRoomWidgets.ts +++ b/src/app/hooks/useRoomWidgets.ts @@ -2,7 +2,7 @@ import type { Room, MatrixEvent, MatrixClient } from '$types/matrix-sdk'; import { useCallback, useMemo } from 'react'; import type { IWidget } from 'matrix-widget-api'; -import { getStateEvents } from '$utils/room'; +import { getStateEvents } from '$utils/room/hierarchy'; import { useStateEventCallback } from './useStateEventCallback'; import { useForceUpdate } from './useForceUpdate'; import { CustomStateEvent } from '$types/matrix/room'; diff --git a/src/app/hooks/useSidebarItems.ts b/src/app/hooks/useSidebarItems.ts index 1b366ebb8..93b4a02db 100644 --- a/src/app/hooks/useSidebarItems.ts +++ b/src/app/hooks/useSidebarItems.ts @@ -2,7 +2,7 @@ import type { Dispatch, SetStateAction } from 'react'; import { useCallback, useEffect, useState } from 'react'; import type { MatrixClient } from '$types/matrix-sdk'; -import { getAccountData, isSpace } from '$utils/room'; +import { getAccountData, isSpace } from '$utils/room/hierarchy'; import { useMatrixClient } from './useMatrixClient'; import { useAccountDataCallback } from './useAccountDataCallback'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; diff --git a/src/app/hooks/useSidebarWidth.ts b/src/app/hooks/useSidebarWidth.ts new file mode 100644 index 000000000..da22de9a7 --- /dev/null +++ b/src/app/hooks/useSidebarWidth.ts @@ -0,0 +1,29 @@ +import { useEffect, useState } from 'react'; +import { useSetAtom } from 'jotai'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { isResizingSidebarAtom } from '$state/isResizingSidebar'; +import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; + +export function useSidebarWidth() { + const setIsResizingSidebar = useSetAtom(isResizingSidebarAtom); + const [roomSidebarWidth, setRoomSidebarWidth] = useSetting(settingsAtom, 'roomSidebarWidth'); + const [curWidth, setCurWidth] = useState(roomSidebarWidth); + useEffect(() => { + setCurWidth(roomSidebarWidth); + }, [roomSidebarWidth]); + const screenSize = useScreenSizeContext(); + const isMobile = screenSize === ScreenSize.Mobile; + const hideText = curWidth <= 80 && !isMobile; + const [oldSidebar] = useSetting(settingsAtom, 'oldSidebar'); + return { + curWidth, + setCurWidth, + roomSidebarWidth, + setRoomSidebarWidth, + setIsResizingSidebar, + isMobile, + hideText, + oldSidebar, + }; +} diff --git a/src/app/hooks/useSpaceHierarchy.ts b/src/app/hooks/useSpaceHierarchy.ts index fe627c6ce..81d51d1a2 100644 --- a/src/app/hooks/useSpaceHierarchy.ts +++ b/src/app/hooks/useSpaceHierarchy.ts @@ -7,7 +7,7 @@ import { useInfiniteQuery } from '@tanstack/react-query'; import type { MSpaceChildContent } from '$types/matrix/room'; import { roomToParentsAtom } from '$state/room/roomToParents'; -import { getAllParents, getStateEvents, isValidChild } from '$utils/room'; +import { getAllParents, getStateEvents, isValidChild } from '$utils/room/hierarchy'; import { isRoomId } from '$utils/matrix'; import type { SortFunc } from '$utils/sort'; import { byOrderKey, byTsOldToNew, factoryRoomIdByActivity } from '$utils/sort'; @@ -168,13 +168,19 @@ const getSpaceHierarchy = ( return hierarchy; }; -export const useSpaceHierarchy = ( +/** + * Shared reactive wrapper: compute a hierarchy value and re-compute when a + * SpaceChild event fires on the space or any of its descendants. + * + * The {@link useMemo} factory receives the spaceId as its single argument so + * callers can pass their own parameterized closure (e.g. + * {@link getSpaceHierarchy} or {@link getSpaceJoinedHierarchy}). + */ +const useReactiveHierarchy = ( spaceId: string, - spaceRooms: Set, - getRoom: (roomId: string) => Room | undefined, - excludeRoom: (parentId: string, roomId: string, depth: number) => boolean, - closedCategory: (spaceId: string) => boolean -): SpaceHierarchy[] => { + factory: (spaceId: string) => T, + deps: unknown[] +): T => { const mx = useMatrixClient(); const roomToParents = useAtomValue(roomToParentsAtom); @@ -182,8 +188,9 @@ export const useSpaceHierarchy = ( const hierarchy = useMemo(() => { void hierarchyKey; - return getSpaceHierarchy(spaceId, spaceRooms, getRoom, excludeRoom, closedCategory); - }, [spaceId, spaceRooms, getRoom, closedCategory, excludeRoom, hierarchyKey]); + return factory(spaceId); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [spaceId, ...deps, hierarchyKey]); useStateEventCallback( mx, @@ -204,6 +211,19 @@ export const useSpaceHierarchy = ( return hierarchy; }; +export const useSpaceHierarchy = ( + spaceId: string, + spaceRooms: Set, + getRoom: (roomId: string) => Room | undefined, + excludeRoom: (parentId: string, roomId: string, depth: number) => boolean, + closedCategory: (spaceId: string) => boolean +): SpaceHierarchy[] => + useReactiveHierarchy( + spaceId, + (sid) => getSpaceHierarchy(sid, spaceRooms, getRoom, excludeRoom, closedCategory), + [spaceRooms, getRoom, closedCategory, excludeRoom] + ); + const getSpaceJoinedHierarchy = ( rootSpaceId: string, getRoom: GetRoomCallback, @@ -292,7 +312,6 @@ export const useSpaceJoinedHierarchy = ( sortByActivity: (spaceId: string) => boolean ): HierarchyItem[] => { const mx = useMatrixClient(); - const roomToParents = useAtomValue(roomToParentsAtom); const sortRoomItems = useCallback( (sId: string, items: HierarchyItem[]) => { @@ -304,30 +323,11 @@ export const useSpaceJoinedHierarchy = ( [mx, sortByActivity] ); - const [hierarchyKey, setHierarchyKey] = useState(0); - - const hierarchy = useMemo(() => { - void hierarchyKey; - return getSpaceJoinedHierarchy(spaceId, getRoom, excludeRoom, sortRoomItems); - }, [spaceId, getRoom, excludeRoom, sortRoomItems, hierarchyKey]); - - useStateEventCallback( - mx, - useCallback( - (mEvent) => { - if (mEvent.getType() !== (EventType.SpaceChild as string)) return; - const eventRoomId = mEvent.getRoomId(); - if (!eventRoomId) return; - - if (spaceId === eventRoomId || getAllParents(roomToParents, eventRoomId).has(spaceId)) { - setHierarchyKey((k) => k + 1); - } - }, - [spaceId, roomToParents, setHierarchyKey] - ) + return useReactiveHierarchy( + spaceId, + (sid) => getSpaceJoinedHierarchy(sid, getRoom, excludeRoom, sortRoomItems), + [getRoom, excludeRoom, sortRoomItems] ); - - return hierarchy; }; // we will paginate until 5000 items diff --git a/src/app/hooks/useStateEvent.ts b/src/app/hooks/useStateEvent.ts index 5b9bd6631..40eee47b7 100644 --- a/src/app/hooks/useStateEvent.ts +++ b/src/app/hooks/useStateEvent.ts @@ -1,7 +1,7 @@ import type { Room, StateEvents } from '$types/matrix-sdk'; import { useCallback, useMemo } from 'react'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { useStateEventCallback } from './useStateEventCallback'; import { useForceUpdate } from './useForceUpdate'; diff --git a/src/app/pages/auth/login/OidcLogin.tsx b/src/app/pages/auth/login/OidcLogin.tsx index 7bc48828b..6606bccef 100644 --- a/src/app/pages/auth/login/OidcLogin.tsx +++ b/src/app/pages/auth/login/OidcLogin.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import type { ValidatedAuthMetadata } from '$types/matrix-sdk'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncButton } from '$components/AsyncButton'; import { useAuthServer } from '$hooks/useAuthServer'; import { InfoCard } from '$components/info-card'; import { getLoginPath } from '$pages/pathUtils'; @@ -66,20 +67,21 @@ export function OidcLoginButton({ {errorMessage && ( )} - + ); } diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index 7feff4cf0..128d42d11 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -23,15 +23,14 @@ import { import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; +import { getAccountData, getStateEvent } from '$utils/room/hierarchy'; import { - getAccountData, - getMemberDisplayName, getNotificationType, - getStateEvent, isNotificationEvent, getMDirects, isDMRoom, -} from '$utils/room'; +} from '$utils/room/unread'; +import { getMemberDisplayName } from '$utils/room/display'; import { NotificationType } from '$types/matrix/room'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 1fb7cbed0..897c11a57 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from 'react'; import { IconSizesProvider } from '$components/icons/phosphor'; import { ShareTargetFeature } from '$features/share-target/ShareTargetFeature'; -import { useIncomingCallSignaling } from '$hooks/useCallSignaling'; +import { useIncomingCallSignaling } from '$features/call/useCallSignaling'; import { MatrixRTCSessionProvider } from '$hooks/useMatrixRTCSession'; import { BackgroundNotifications } from './BackgroundNotifications'; import { DesktopUpdater } from './DesktopUpdater'; diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index e983ec89c..25301c7ae 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -11,7 +11,7 @@ import { Spinner, Text, } from 'folds'; -import type { HttpApiEventHandlerMap, MatrixClient } from '$types/matrix-sdk'; +import type { MatrixClient } from '$types/matrix-sdk'; import { HttpApiEvent } from '$types/matrix-sdk'; import FocusTrap from 'focus-trap-react'; import type { MouseEventHandler, ReactNode } from 'react'; @@ -35,6 +35,7 @@ import { MatrixClientProvider } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useSyncState } from '$hooks/useSyncState'; import { useCrossSigningResetDetect } from '$hooks/useCrossSigningResetDetect'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; import { stopPropagation } from '$utils/keyboard'; import { AuthMetadataProvider, getSessionAuthMetadata } from '$hooks/useAuthMetadata'; import { @@ -220,24 +221,19 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) { } const useLogoutListener = (mx?: MatrixClient) => { - useEffect(() => { - const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { - Sentry.addBreadcrumb({ - category: 'auth', - message: 'Session forcibly logged out by server', - level: 'warning', - }); - if (mx) stopClient(mx); - await mx?.clearStores(); - window.localStorage.clear(); - window.location.reload(); - }; - - mx?.on(HttpApiEvent.SessionLoggedOut, handleLogout); - return () => { - mx?.removeListener(HttpApiEvent.SessionLoggedOut, handleLogout); - }; + const handleLogout = useCallback(async () => { + Sentry.addBreadcrumb({ + category: 'auth', + message: 'Session forcibly logged out by server', + level: 'warning', + }); + if (mx) stopClient(mx); + await mx?.clearStores(); + window.localStorage.clear(); + window.location.reload(); }, [mx]); + + useMatrixEvent(mx, HttpApiEvent.SessionLoggedOut, handleLogout); }; type ClientRootProps = { diff --git a/src/app/pages/client/SpecVersions.tsx b/src/app/pages/client/SpecVersions.tsx index d89c95a45..6bd96b4a1 100644 --- a/src/app/pages/client/SpecVersions.tsx +++ b/src/app/pages/client/SpecVersions.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from 'react'; import { useCallback, useState } from 'react'; -import { Box, Button, Dialog, config, Spinner, Text, color } from 'folds'; +import { Box, Button, Dialog, config, Text } from 'folds'; import { useAtomValue, useSetAtom } from 'jotai'; import { SpecVersionsLoader } from '$components/SpecVersionsLoader'; import { SpecVersionsProvider } from '$hooks/useSpecVersions'; @@ -11,6 +11,8 @@ import { activeSessionIdAtom, sessionsAtom, type Session } from '$state/sessions import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useClientConfig } from '$hooks/useClientConfig'; import type { SpecVersions } from '../../cs-api'; +import { AsyncError } from '$components/AsyncError'; +import { AsyncButton } from '$components/AsyncButton'; const EMPTY_VERSIONS: SpecVersions = { versions: [] }; @@ -100,22 +102,19 @@ function HomeserverOfflineError({ baseUrl, onRetry }: HomeserverOfflineErrorProp )} )} - - {logoutState.status === AsyncStatus.Error && ( - - Failed to logout. {logoutState.error.message} - - )} + + diff --git a/src/app/pages/client/client-non-ui/notifications.tsx b/src/app/pages/client/client-non-ui/notifications.tsx index 355c7ed2e..15d784cc8 100644 --- a/src/app/pages/client/client-non-ui/notifications.tsx +++ b/src/app/pages/client/client-non-ui/notifications.tsx @@ -34,13 +34,9 @@ import { mDirectAtom } from '$state/mDirectList'; import { allInvitesAtom } from '$state/room-list/inviteList'; import { usePreviousValue } from '$hooks/usePreviousValue'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { - getMemberDisplayName, - getNotificationType, - getStateEvent, - isDMRoom, - isNotificationEvent, -} from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; +import { getNotificationType, isDMRoom, isNotificationEvent } from '$utils/room/unread'; +import { getMemberDisplayName } from '$utils/room/display'; import { NotificationType } from '$types/matrix/room'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; diff --git a/src/app/pages/client/direct/Direct.tsx b/src/app/pages/client/direct/Direct.tsx index cae9f3903..13716b8b3 100644 --- a/src/app/pages/client/direct/Direct.tsx +++ b/src/app/pages/client/direct/Direct.tsx @@ -1,11 +1,8 @@ import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useAtom, useAtomValue, useSetAtom } from 'jotai'; -import { Avatar, Box, Button, IconButton, Menu, MenuItem, Text, config, toRem } from 'folds'; +import { useAtom, useAtomValue } from 'jotai'; +import { Avatar, Box, Button, Text, toRem } from 'folds'; import { At, - Checks, - composerIcon, - DotsThreeOutlineVerticalIcon, dropzoneIcon, menuIcon, getPhosphorSize, @@ -35,10 +32,9 @@ import { makeNavCategoryId } from '$state/closedNavCategories'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { useCategoryHandler } from '$hooks/useCategoryHandler'; import { useNavToActivePathMapper } from '$hooks/useNavToActivePathMapper'; -import { PageNav, PageNavContent, PageNavHeader } from '$components/page'; +import { PageNavContent, PageNavHeaderWithMenu } from '$components/page'; +import { PageNavShell } from '$components/page/PageNavShell'; import { useClosedNavCategoriesAtom } from '$state/hooks/closedNavCategories'; -import { useRoomsUnread } from '$state/hooks/unread'; -import { markAsRead } from '$utils/notifications'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { @@ -47,93 +43,35 @@ import { } from '$hooks/useRoomsNotificationPreferences'; import { useDirectCreateSelected } from '$hooks/router/useRouteSelected'; import { useDirectRooms } from './useDirectRooms'; -import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; -import { useScreenSizeContext, ScreenSize } from '$hooks/useScreenSize'; -import { isResizingSidebarAtom } from '$state/isResizingSidebar'; -import { UserQuickTools } from '../sidebar/UserQuickTools'; -import { ResponsiveMenu } from '$components/ResponsiveMenu'; +import { useSidebarWidth } from '$hooks/useSidebarWidth'; import { useMenuAnchor } from '$hooks/useMenuAnchor'; +import { NavMenu } from '$components/nav/NavMenu'; type DirectMenuProps = { requestClose: () => void; }; const DirectMenu = forwardRef(({ requestClose }, ref) => { - const mx = useMatrixClient(); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); const orphanRooms = useDirectRooms(); - const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); - const handleMarkAsRead = () => { - if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); - requestClose(); - }; - - return ( - - - - - Mark as Read - - - - - ); + return ; }); +DirectMenu.displayName = 'DirectMenu'; function DirectHeader({ hideText }: { hideText?: boolean }) { const menu = useMenuAnchor(); return ( - <> - - {hideText ? ( - - - - - - ) : ( - - - - Direct Messages - - - - - {composerIcon(DotsThreeOutlineVerticalIcon, { - weight: menu.anchor ? 'fill' : 'regular', - })} - - - - )} - - } - /> - + + } + menu={} + anchor={menu.anchor} + requestClose={menu.close} + triggerProps={menu.triggerProps} + /> ); } @@ -176,13 +114,16 @@ export function Direct() { const roomToUnread = useAtomValue(roomToUnreadAtom); const navigate = useNavigate(); const [customDMCards] = useSetting(settingsAtom, 'customDMCards'); - const setIsResizingSidebar = useSetAtom(isResizingSidebarAtom); - const [roomSidebarWidth, setRoomSidebarWidth] = useSetting(settingsAtom, 'roomSidebarWidth'); - const [curWidth, setCurWidth] = useState(roomSidebarWidth); - - useEffect(() => { - setCurWidth(roomSidebarWidth); - }, [roomSidebarWidth]); + const { + curWidth, + setCurWidth, + roomSidebarWidth, + setRoomSidebarWidth, + setIsResizingSidebar, + isMobile, + hideText, + oldSidebar, + } = useSidebarWidth(); const [joinCallOnSingleClick] = useSetting(settingsAtom, 'joinCallOnSingleClick'); @@ -246,133 +187,109 @@ export function Direct() { closedCategories.has(categoryId) ); - const screenSize = useScreenSizeContext(); - const isMobile = screenSize === ScreenSize.Mobile; - const hideText = curWidth <= 80 && !isMobile; - const [oldSidebar] = useSetting(settingsAtom, 'oldSidebar'); - return ( - } + curWidth={curWidth} + setCurWidth={setCurWidth} + roomSidebarWidth={roomSidebarWidth} + setRoomSidebarWidth={setRoomSidebarWidth} + setIsResizingSidebar={setIsResizingSidebar} + isMobile={isMobile} + oldSidebar={oldSidebar} > - - - {noRoomToDisplay ? ( - - ) : ( - - - - - navigate(getDirectCreatePath())}> - - - - {menuIcon(Plus)} - - {!hideText && ( - - - Create Chat - - - )} - - - - - - - - - {!hideText && 'Chats'} - - -
+ ) : ( + + + + + navigate(getDirectCreatePath())}> + + + + {menuIcon(Plus)} + + {!hideText && ( + + + Create Chat + + + )} + + + + + + + + - {virtualizer.getVirtualItems().map((vItem) => { - const roomId = sortedDirects[vItem.index]; - if (!roomId) return null; - const room = mx.getRoom(roomId); - if (!room) return null; - const selected = selectedRoomId === roomId; + {!hideText && 'Chats'} + + +
+ {virtualizer.getVirtualItems().map((vItem) => { + const roomId = sortedDirects[vItem.index]; + if (!roomId) return null; + const room = mx.getRoom(roomId); + if (!room) return null; + const selected = selectedRoomId === roomId; - return ( - +
-
- -
- - ); - })} -
- -
- - - )} - - {!isMobile && ( - + +
+
+ ); + })} +
+
+
+ + )} - {!oldSidebar && !isMobile && } - + ); } diff --git a/src/app/pages/client/explore/Explore.tsx b/src/app/pages/client/explore/Explore.tsx index c89c992f3..c3f74eef6 100644 --- a/src/app/pages/client/explore/Explore.tsx +++ b/src/app/pages/client/explore/Explore.tsx @@ -1,19 +1,7 @@ import type { FormEventHandler, MouseEventHandler } from 'react'; -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { - Avatar, - Box, - Button, - Dialog, - Header, - IconButton, - Input, - Text, - color, - config, - toRem, -} from 'folds'; +import { Avatar, Box, Button, Dialog, Header, IconButton, Input, Text, color, config } from 'folds'; import { Compass, HardDrives, @@ -38,18 +26,14 @@ import { useClientConfig } from '$hooks/useClientConfig'; import { useExploreFeaturedSelected, useExploreServer } from '$hooks/router/useRouteSelected'; import { useExploreServers } from '$hooks/useExploreServers'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncError } from '$components/AsyncError'; import { useNavToActivePathMapper } from '$hooks/useNavToActivePathMapper'; -import { PageNav, PageNavContent, PageNavHeader } from '$components/page'; -import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; -import { settingsAtom } from '$state/settings'; -import { useSetting } from '$state/hooks/settings'; +import { PageNavContent, PageNavHeader } from '$components/page'; +import { PageNavShell } from '$components/page/PageNavShell'; +import { useSidebarWidth } from '$hooks/useSidebarWidth'; import { getMxIdServer } from '$utils/mxIdHelper'; import { isServerName } from '$utils/matrix'; -import { useScreenSizeContext, ScreenSize } from '$hooks/useScreenSize'; -import { isResizingSidebarAtom } from '$state/isResizingSidebar'; -import { useSetAtom } from 'jotai'; -import { UserQuickTools } from '../sidebar/UserQuickTools'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; type AddServerProps = { @@ -139,11 +123,11 @@ function AddServer({ hideText, onAddServer }: AddServerProps) { {serverError} )} - {exploreState.status === AsyncStatus.Error && ( - - Failed to load public rooms. Please try again. - - )} + {/* - - + @@ -642,7 +626,6 @@ function SpamInvites({ const declining = declineAllStatus.status === AsyncStatus.Loading; const reporting = reportAllStatus.status === AsyncStatus.Loading; const blocking = blockAllStatus.status === AsyncStatus.Loading; - const loading = blocking || reporting || declining; return ( @@ -662,48 +645,57 @@ function SpamInvites({ subTitle="Some of the following invites may contain harmful content or have been sent by banned users." > - + {reportRoomSupported && reportAllStatus.status !== AsyncStatus.Success && ( - + )} {unignoredUsers.length > 0 && ( - + )} diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 5a1ee4f9a..1b969f8d3 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -21,7 +21,7 @@ import type { InboxNotificationsPathSearchParams } from '$pages/paths'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { SequenceCard } from '$components/sequence-card'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; -import { getRoomAvatarUrl } from '$utils/room'; +import { getRoomAvatarUrl } from '$utils/room/display'; import { ScrollTopContainer } from '$components/scroll-top-container'; import { useInterval } from '$hooks/useInterval'; import { useSetting } from '$state/hooks/settings'; diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index 57a429044..ac836775e 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -15,7 +15,7 @@ import { } from '$components/sidebar'; import { RoomAvatar } from '$components/room-avatar'; import { UserAvatar } from '$components/user-avatar'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room'; +import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { nameInitials } from '$utils/common'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index 4ba3c0d2f..24d86af27 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -1,6 +1,5 @@ import { forwardRef, useMemo } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Box, Menu, MenuItem, Text, config, toRem } from 'folds'; import { useAtomValue } from 'jotai'; import { useDirects } from '$state/hooks/roomList'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -9,57 +8,25 @@ import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { getDirectPath, joinPathComponent } from '$pages/pathUtils'; import { useRoomsUnread } from '$state/hooks/unread'; -import { - SidebarAvatar, - SidebarItemLeft, - SidebarUnreadBadge, - SidebarItemTooltip, -} from '$components/sidebar'; +import { SidebarTab } from '$components/sidebar'; import { useDirectSelected } from '$hooks/router/useRouteSelected'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { useNavToActivePathAtom } from '$state/hooks/navToActivePath'; -import { markAsRead } from '$utils/notifications'; -import { Checks, menuIcon, getPhosphorIconSize, User } from '$components/icons/phosphor'; -import { settingsAtom } from '$state/settings'; -import { useSetting } from '$state/hooks/settings'; +import { getPhosphorIconSize, User } from '$components/icons/phosphor'; import { useDirectRooms } from '$pages/client/direct/useDirectRooms'; import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; -import { ResponsiveMenu } from '$components/ResponsiveMenu'; import { useMenuAnchor } from '$hooks/useMenuAnchor'; +import { NavMenu } from '$components/nav/NavMenu'; type DirectMenuProps = { requestClose: () => void; }; const DirectMenu = forwardRef(({ requestClose }, ref) => { const orphanRooms = useDirectRooms(); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); - const mx = useMatrixClient(); - const handleMarkAsRead = () => { - if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); - requestClose(); - }; - - return ( - - - - - Mark as Read - - - - - ); + return ; }); +DirectMenu.displayName = 'DirectMenu'; export function DirectTab() { const navigate = useNavigate(); @@ -77,7 +44,7 @@ export function DirectTab() { return directs.filter((id) => !sidebarSet.has(id)); }, [directs, sidebarRoomIds]); const directUnread = useRoomsUnread(overflowDirects, roomToUnreadAtom); - const menu = useMenuAnchor(); + const menuAnchor = useMenuAnchor(); const directSelected = useDirectSelected(); @@ -95,42 +62,24 @@ export function DirectTab() { }; return ( - - - {(triggerRef) => ( - } - > - - - - - )} - - {directUnread && ( - 0} - count={directUnread.highlight > 0 ? directUnread.highlight : directUnread.total} - dm - /> - )} - + + } + selected={directSelected} + tooltip="Direct Messages" + onClick={handleDirectClick} + menu={} + menuAnchor={menuAnchor} + unreadHighlight={directUnread ? directUnread.highlight > 0 : false} + unreadCount={ + directUnread + ? directUnread.highlight > 0 + ? directUnread.highlight + : directUnread.total + : 0 + } + dm + /> ); } diff --git a/src/app/pages/client/sidebar/HomeTab.tsx b/src/app/pages/client/sidebar/HomeTab.tsx index 17f57e812..405fac523 100644 --- a/src/app/pages/client/sidebar/HomeTab.tsx +++ b/src/app/pages/client/sidebar/HomeTab.tsx @@ -1,6 +1,5 @@ import { forwardRef } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Box, Menu, MenuItem, Text, config, toRem } from 'folds'; import { useAtomValue } from 'jotai'; import { useOrphanRooms } from '$state/hooks/roomList'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -10,56 +9,24 @@ import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { getHomePath, joinPathComponent } from '$pages/pathUtils'; import { useRoomsUnread } from '$state/hooks/unread'; -import { - SidebarAvatar, - SidebarItemLeft, - SidebarUnreadBadge, - SidebarItemTooltip, -} from '$components/sidebar'; +import { SidebarTab } from '$components/sidebar'; import { useHomeSelected } from '$hooks/router/useRouteSelected'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { useNavToActivePathAtom } from '$state/hooks/navToActivePath'; -import { markAsRead } from '$utils/notifications'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; -import { useHomeRooms } from '$pages/client/home/useHomeRooms'; -import { Checks, House, menuIcon, getPhosphorIconSize } from '$components/icons/phosphor'; -import { ResponsiveMenu } from '$components/ResponsiveMenu'; +import { House, getPhosphorIconSize } from '$components/icons/phosphor'; import { useMenuAnchor } from '$hooks/useMenuAnchor'; +import { NavMenu } from '$components/nav/NavMenu'; +import { useHomeRooms } from '$pages/client/home/useHomeRooms'; type HomeMenuProps = { requestClose: () => void; }; const HomeMenu = forwardRef(({ requestClose }, ref) => { const orphanRooms = useHomeRooms(); - const [hideReads] = useSetting(settingsAtom, 'hideReads'); - const unread = useRoomsUnread(orphanRooms, roomToUnreadAtom); - const mx = useMatrixClient(); - const handleMarkAsRead = () => { - if (!unread) return; - orphanRooms.forEach((rId) => markAsRead(mx, rId, hideReads)); - requestClose(); - }; - - return ( - - - - - Mark as Read - - - - - ); + return ; }); +HomeMenu.displayName = 'HomeMenu'; export function HomeTab() { const navigate = useNavigate(); @@ -72,7 +39,7 @@ export function HomeTab() { const orphanRooms = useOrphanRooms(mx, allRoomsAtom, mDirects, roomToParents); const homeUnread = useRoomsUnread(orphanRooms, roomToUnreadAtom); const homeSelected = useHomeSelected(); - const menu = useMenuAnchor(); + const menuAnchor = useMenuAnchor(); const handleHomeClick = () => { const activePath = navToActivePath.get('home'); @@ -85,41 +52,19 @@ export function HomeTab() { }; return ( - - - {(triggerRef) => ( - } - > - - - - - )} - - {homeUnread && ( - 0} - count={homeUnread.highlight > 0 ? homeUnread.highlight : homeUnread.total} - /> - )} - + + } + selected={homeSelected} + tooltip="Home" + onClick={handleHomeClick} + menu={} + menuAnchor={menuAnchor} + unreadHighlight={homeUnread ? homeUnread.highlight > 0 : false} + unreadCount={ + homeUnread ? (homeUnread.highlight > 0 ? homeUnread.highlight : homeUnread.total) : 0 + } + /> ); } diff --git a/src/app/pages/client/space/RoomProvider.tsx b/src/app/pages/client/space/RoomProvider.tsx index bd5cada12..9553e99e0 100644 --- a/src/app/pages/client/space/RoomProvider.tsx +++ b/src/app/pages/client/space/RoomProvider.tsx @@ -7,7 +7,7 @@ import { IsDirectRoomProvider, DisplayedEventIdProvider, RoomProvider } from '$h import { useMatrixClient } from '$hooks/useMatrixClient'; import { JoinBeforeNavigate } from '$features/join-before-navigate'; import { useSpace } from '$hooks/useSpace'; -import { getAllParents, getSpaceChildren } from '$utils/room'; +import { getAllParents, getSpaceChildren } from '$utils/room/hierarchy'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { allRoomsAtom } from '$state/room-list/roomList'; import { useSearchParamsViaServers } from '$hooks/router/useSearchParamsViaServers'; diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index 4d6ee8ca1..dc597ab05 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -1,6 +1,6 @@ import type { ReactElement } from 'react'; import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useAtom, useAtomValue, useSetAtom } from 'jotai'; +import { useAtom, useAtomValue } from 'jotai'; import { Avatar, Box, @@ -10,7 +10,6 @@ import { Menu, MenuItem, Modal, - Spinner, Text, color, config, @@ -40,7 +39,8 @@ import { useRoomName } from '$hooks/useRoomMeta'; import type { HierarchyItem } from '$hooks/useSpaceHierarchy'; import { useSpaceJoinedHierarchy } from '$hooks/useSpaceHierarchy'; import { allRoomsAtom } from '$state/room-list/roomList'; -import { PageNav, PageNavContent, PageNavHeader } from '$components/page'; +import { PageNavContent, PageNavHeader } from '$components/page'; +import { PageNavShell } from '$components/page/PageNavShell'; import { usePowerLevels } from '$hooks/usePowerLevels'; import { useRecursiveChildScopeFactory, useSpaceChildren } from '$state/hooks/roomList'; import { @@ -83,14 +83,15 @@ import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { ContainerColor } from '$styles/ContainerColor.css'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { BreakWord } from '$styles/Text.css'; +import { AsyncButton } from '$components/AsyncButton'; +import { AsyncError } from '$components/AsyncError'; import { InviteUserPrompt } from '$components/invite-user-prompt'; import { useCallEmbed } from '$hooks/useCallEmbed'; import { createDebugLogger } from '$utils/debugLogger'; import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; -import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; +import { useSidebarWidth } from '$hooks/useSidebarWidth'; import { RoomAvatar } from '$components/room-avatar'; -import { getRoomAvatarUrl } from '$utils/room'; +import { getRoomAvatarUrl } from '$utils/room/display'; import { nameInitials } from '$utils/common'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { CustomStateEvent } from '$types/matrix/room'; @@ -99,8 +100,6 @@ import { ModalWide } from '$styles/Modal.css'; import { ImageViewer } from '$components/image-viewer'; import { reportMediaLoadFailure } from '$utils/mediaLoadDiagnostics'; import * as css from './styles.css'; -import { isResizingSidebarAtom } from '$state/isResizingSidebar'; -import { UserQuickTools } from '../sidebar/UserQuickTools'; import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { useOpenRoomSettings } from '$state/hooks/roomSettings'; @@ -455,11 +454,7 @@ function SpaceTombstone({ roomId, replacementRoomId }: SpaceTombstoneProps) { Space Upgraded This space has been replaced and is no longer active. - {joinState.status === AsyncStatus.Error && ( - - {(joinState.error as Error)?.message ?? 'Failed to join replacement space!'} - - )} + {replacementRoom?.getMyMembership() === KnownMembership.Join || @@ -468,21 +463,19 @@ function SpaceTombstone({ roomId, replacementRoomId }: SpaceTombstoneProps) { Open New Space ) : ( - + )} @@ -510,12 +503,16 @@ export function Space() { const allJoinedRooms = useMemo(() => new Set(allRooms), [allRooms]); const notificationPreferences = useRoomsNotificationPreferencesContext(); - const setIsResizingSidebar = useSetAtom(isResizingSidebarAtom); - const [roomSidebarWidth, setRoomSidebarWidth] = useSetting(settingsAtom, 'roomSidebarWidth'); - const [curWidth, setCurWidth] = useState(roomSidebarWidth); - useEffect(() => { - setCurWidth(roomSidebarWidth); - }, [roomSidebarWidth]); + const { + curWidth, + setCurWidth, + roomSidebarWidth, + setRoomSidebarWidth, + setIsResizingSidebar, + isMobile, + hideText, + oldSidebar, + } = useSidebarWidth(); const [showRoomIconGeneral] = useSetting(settingsAtom, 'showRoomIcon'); const [showRoomIconArray] = useSetting(settingsAtom, 'perRoomShowRoomIcon'); @@ -804,199 +801,173 @@ export function Space() { const getToLink = (roomId: string) => getSpaceRoomPath(spaceIdOrAlias, getCanonicalAliasOrRoomId(mx, roomId)); - const screenSize = useScreenSizeContext(); - const isMobile = screenSize === ScreenSize.Mobile; - const hideText = curWidth <= 80 && !isMobile; - const [oldSidebar] = useSetting(settingsAtom, 'oldSidebar'); - return ( - } + curWidth={curWidth} + setCurWidth={setCurWidth} + roomSidebarWidth={roomSidebarWidth} + setRoomSidebarWidth={setRoomSidebarWidth} + setIsResizingSidebar={setIsResizingSidebar} + isMobile={isMobile} + oldSidebar={oldSidebar} > - - - - - {tombstoneEvent && ( - - )} - - - - - - - {menuIcon(Flag, { weight: lobbySelected ? 'fill' : 'regular' })} - + + + {tombstoneEvent && ( + + )} + + + + + + + {menuIcon(Flag, { weight: lobbySelected ? 'fill' : 'regular' })} + + {!hideText && ( + + + Lobby + + + )} + + + + + + + + + + {menuIcon(MagnifyingGlass, { + weight: searchSelected ? 'fill' : 'regular', + })} + + {!hideText && ( - - - Lobby - - + + Message Search + )} - - - - - - - - - {menuIcon(MagnifyingGlass, { - weight: searchSelected ? 'fill' : 'regular', - })} - - - {!hideText && ( - - Message Search - - )} - - - - - - - - {virtualizedItems.map((vItem) => { - const hierarchyItem = hierarchy[vItem.index]; - if (!hierarchyItem) return null; - const { roomId, depth: itemDepth } = hierarchyItem; - const depth = itemDepth ?? 0; - const room = mx.getRoom(roomId); - const renderDepth = room?.isSpaceRoom() ? depth - 2 : depth - 1; - if (!room) return null; - if (depth === subspaceHierarchyLimit && room.isSpaceRoom()) { - return ( - -
- -
-
- ); - } - - const paddingTop = getCategoryPadding(depth); - const paddingLeft = `calc(${renderDepth} * ${config.space.S400})`; - - if (room.isSpaceRoom()) { - const categoryId = makeNavCategoryId(space.roomId, roomId); - const closedViaCategory = getInClosedCategories(space.roomId, roomId); - - return ( - -
- - - {!hideText && (roomId === space.roomId ? 'Rooms' : room?.name)} - - -
-
- ); - } - +
+
+
+
+
+ + {virtualizedItems.map((vItem) => { + const hierarchyItem = hierarchy[vItem.index]; + if (!hierarchyItem) return null; + const { roomId, depth: itemDepth } = hierarchyItem; + const depth = itemDepth ?? 0; + const room = mx.getRoom(roomId); + const renderDepth = room?.isSpaceRoom() ? depth - 2 : depth - 1; + if (!room) return null; + if (depth === subspaceHierarchyLimit && room.isSpaceRoom()) { return (
-
); - })} - {getConnectorSVG(hierarchy, virtualizedItems)} -
- {!isMobile &&
} - - - - {!isMobile && ( - - )} - {!oldSidebar && !isMobile && } - + } + + const paddingTop = getCategoryPadding(depth); + const paddingLeft = `calc(${renderDepth} * ${config.space.S400})`; + + if (room.isSpaceRoom()) { + const categoryId = makeNavCategoryId(space.roomId, roomId); + const closedViaCategory = getInClosedCategories(space.roomId, roomId); + + return ( + +
+ + + {!hideText && (roomId === space.roomId ? 'Rooms' : room?.name)} + + +
+
+ ); + } + + return ( + +
+ +
+
+ ); + })} + {getConnectorSVG(hierarchy, virtualizedItems)} + + {!isMobile &&
} + + + ); } diff --git a/src/app/plugins/custom-emoji/utils.ts b/src/app/plugins/custom-emoji/utils.ts index 6e276174b..2b52ab760 100644 --- a/src/app/plugins/custom-emoji/utils.ts +++ b/src/app/plugins/custom-emoji/utils.ts @@ -1,6 +1,6 @@ import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { getAccountData, getStateEvent, getStateEvents } from '$utils/room'; +import { getAccountData, getStateEvent, getStateEvents } from '$utils/room/hierarchy'; import type { IImageInfo } from '$types/matrix/common'; import type { ImageUsage } from './types'; diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index a4dd5c270..187ca61c7 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -24,7 +24,7 @@ import { isRoomAlias, mxcUrlToHttp, } from '$utils/matrix'; -import { getMemberDisplayName } from '$utils/room'; +import { getMemberDisplayName } from '$utils/room/display'; import { type Nicknames } from '$state/nicknames'; import { sanitizeForRegex, URL_REG } from '$utils/regex'; import { splitEmojiText } from '$utils/emojiDetection'; diff --git a/src/app/plugins/recent-emoji.ts b/src/app/plugins/recent-emoji.ts index 580e02ef5..699098cb0 100644 --- a/src/app/plugins/recent-emoji.ts +++ b/src/app/plugins/recent-emoji.ts @@ -1,6 +1,6 @@ import type { MatrixClient } from '$types/matrix-sdk'; -import { getAccountData } from '$utils/room'; +import { getAccountData } from '$utils/room/hierarchy'; import type { IEmoji } from './emoji'; import { emojis } from './emoji'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; diff --git a/src/app/plugins/via-servers.ts b/src/app/plugins/via-servers.ts index 0a7d560a7..1e5a46f23 100644 --- a/src/app/plugins/via-servers.ts +++ b/src/app/plugins/via-servers.ts @@ -3,7 +3,7 @@ import { creatorsSupported } from '$utils/roomSupport'; import type { Room } from '$types/matrix-sdk'; import type { IRoomCreateContent } from '$types/matrix/room'; import type { IPowerLevels } from '$hooks/usePowerLevels'; -import { getStateEvent } from '$utils/room'; +import { getStateEvent } from '$utils/room/hierarchy'; import { EventType } from '$types/matrix-sdk'; export const getViaServers = (room: Room): string[] => { diff --git a/src/app/state/backupRestore.ts b/src/app/state/backupRestore.ts index 62f7e827c..8b411ebee 100644 --- a/src/app/state/backupRestore.ts +++ b/src/app/state/backupRestore.ts @@ -8,13 +8,13 @@ export enum BackupProgressStatus { Loading, Done, } -export type ProgressData = { +type ProgressData = { downloaded: number; successes: number; failures: number; total: number; }; -export type IBackupProgress = +type IBackupProgress = | { status: BackupProgressStatus.Idle; } diff --git a/src/app/state/bookmarks.ts b/src/app/state/bookmarks.ts index bc9239aad..5f7d26cfe 100644 --- a/src/app/state/bookmarks.ts +++ b/src/app/state/bookmarks.ts @@ -5,6 +5,7 @@ import { useCallback, useEffect } from 'react'; import type { BookmarkItemContent } from '$types/matrix-sdk-events'; import { listBookmarks } from '$features/bookmarks/bookmarkRepository'; import { MATRIX_SABLE_UNSTABLE_BOOKMARKS_INDEX_EVENT } from '$unstable/prefixes'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; export const bookmarkListAtom = atom([]); export const bookmarkLoadingAtom = atom(false); @@ -43,16 +44,14 @@ export const useBindBookmarksAtom = (mx: MatrixClient, bookmarks: typeof bookmar refresh(); }, [refresh]); - useEffect(() => { - const handleAccountData = (event: MatrixEvent) => { + const handleAccountData = useCallback( + (event: MatrixEvent) => { if (event.getType() === MATRIX_SABLE_UNSTABLE_BOOKMARKS_INDEX_EVENT) { refresh(); } - }; + }, + [refresh] + ); - mx.on(ClientEvent.AccountData, handleAccountData); - return () => { - mx.removeListener(ClientEvent.AccountData, handleAccountData); - }; - }, [mx, refresh]); + useMatrixEvent(mx, ClientEvent.AccountData, handleAccountData); }; diff --git a/src/app/state/callEmbed.ts b/src/app/state/callEmbed.ts index 3353c3d1f..3dcc6c745 100644 --- a/src/app/state/callEmbed.ts +++ b/src/app/state/callEmbed.ts @@ -68,7 +68,7 @@ export type IncomingCall = { isDirect: boolean; }; -export type AutoJoinCallIntent = { +type AutoJoinCallIntent = { roomId: string; video: boolean; }; diff --git a/src/app/state/hooks/desktopSettings.ts b/src/app/state/hooks/desktopSettings.ts index 8bb8eb13b..b3bdc3663 100644 --- a/src/app/state/hooks/desktopSettings.ts +++ b/src/app/state/hooks/desktopSettings.ts @@ -11,7 +11,7 @@ import { desktopSettingsSyncingAtom, } from '$state/desktopSettings'; -export type DesktopSettingSetter = +type DesktopSettingSetter = | DesktopSettings[K] | ((value: DesktopSettings[K]) => DesktopSettings[K]); diff --git a/src/app/state/hooks/roomList.ts b/src/app/state/hooks/roomList.ts index 248f35851..14685cdf5 100644 --- a/src/app/state/hooks/roomList.ts +++ b/src/app/state/hooks/roomList.ts @@ -3,7 +3,7 @@ import { useAtomValue } from 'jotai'; import { selectAtom } from 'jotai/utils'; import type { MatrixClient } from '$types/matrix-sdk'; import { useCallback, useMemo } from 'react'; -import { getAllParents, isRoom, isSpace } from '$utils/room'; +import { getAllParents, isRoom, isSpace } from '$utils/room/hierarchy'; import type { RoomToParents } from '$types/matrix/room'; import { compareRoomsEqual } from '$state/room-list/utils'; diff --git a/src/app/state/list.ts b/src/app/state/list.ts index 0d9cf52ed..2749f70bd 100644 --- a/src/app/state/list.ts +++ b/src/app/state/list.ts @@ -1,6 +1,6 @@ import { atom } from 'jotai'; -export type ListAction = +type ListAction = | { type: 'PUT'; item: T | T[]; @@ -42,4 +42,3 @@ export const createListAtom = () => { } ); }; -export type TListAtom = ReturnType>; diff --git a/src/app/state/mDirectList.ts b/src/app/state/mDirectList.ts index 9f3123145..82e5ff4c9 100644 --- a/src/app/state/mDirectList.ts +++ b/src/app/state/mDirectList.ts @@ -3,9 +3,10 @@ import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; import { ClientEvent, EventType } from '$types/matrix-sdk'; import { useEffect } from 'react'; -import { getAccountData, getMDirects } from '$utils/room'; +import { getAccountData } from '$utils/room/hierarchy'; +import { getMDirects } from '$utils/room/unread'; -export type MDirectAction = { +type MDirectAction = { type: 'INITIALIZE' | 'UPDATE'; rooms: Set; }; diff --git a/src/app/state/modal.ts b/src/app/state/modal.ts index a95be26ab..e6399a686 100644 --- a/src/app/state/modal.ts +++ b/src/app/state/modal.ts @@ -14,7 +14,7 @@ export enum ModalType { ReadReceipts = 'read_receipts', } -export type ModalState = +type ModalState = | { type: ModalType.MobileOptions; options: OptionMenuProps } | { type: ModalType.Delete; room: Room; mEvent: MatrixEvent } | { type: ModalType.Forward; room: Room; mEvent: MatrixEvent } diff --git a/src/app/state/nativeNotificationReplies.ts b/src/app/state/nativeNotificationReplies.ts index 4eb886d44..960dcf3ba 100644 --- a/src/app/state/nativeNotificationReplies.ts +++ b/src/app/state/nativeNotificationReplies.ts @@ -10,7 +10,7 @@ export type NativeNotificationReply = { text: string; createdAt: number; }; -export type NativeActionPayload = { +type NativeActionPayload = { actionId: string; inputValue?: string | null; notification: { diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index 8e90abcc4..10525f64a 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -24,25 +24,14 @@ export type TUploadItem = { formatted_body?: string; }; -export type TUploadListAtom = ReturnType>; +type TUploadListAtom = ReturnType>; export const roomIdToUploadItemsAtomFamily = atomFamily(createListAtom); export const roomUploadAtomFamily = createUploadAtomFamily(); -export type RoomIdToMsgAction = - | { - type: 'PUT'; - roomId: string; - msg: Descendant[]; - } - | { - type: 'DELETE'; - roomId: string; - }; - const createMsgDraftAtom = () => atom([]); -export type TMsgDraftAtom = ReturnType; +type TMsgDraftAtom = ReturnType; export const roomIdToMsgDraftAtomFamily = atomFamily(() => createMsgDraftAtom() ); @@ -55,7 +44,7 @@ export type IReplyDraft = { relation?: IEventRelation | undefined; }; const createReplyDraftAtom = () => atom(undefined); -export type TReplyDraftAtom = ReturnType; +type TReplyDraftAtom = ReturnType; export const roomIdToReplyDraftAtomFamily = atomFamily(() => createReplyDraftAtom() ); diff --git a/src/app/state/room/roomToOpenThread.ts b/src/app/state/room/roomToOpenThread.ts index 0a60fa4a7..a623bafd6 100644 --- a/src/app/state/room/roomToOpenThread.ts +++ b/src/app/state/room/roomToOpenThread.ts @@ -2,7 +2,7 @@ import { atom } from 'jotai'; import { atomFamily } from 'jotai/utils'; const createOpenThreadAtom = () => atom(undefined); -export type TOpenThreadAtom = ReturnType; +type TOpenThreadAtom = ReturnType; /** * Tracks the currently-open thread root event ID per room. diff --git a/src/app/state/room/roomToParents.ts b/src/app/state/room/roomToParents.ts index 7a77f86b3..7ed4ca600 100644 --- a/src/app/state/room/roomToParents.ts +++ b/src/app/state/room/roomToParents.ts @@ -18,10 +18,10 @@ import { isSpace, isValidChild, mapParentWithChildren, -} from '$utils/room'; +} from '$utils/room/hierarchy'; import { useSyncState } from '$hooks/useSyncState'; -export type RoomToParentsAction = +type RoomToParentsAction = | { type: 'INITIALIZE'; roomToParents: RoomToParents; diff --git a/src/app/state/room/roomToThreadBrowser.ts b/src/app/state/room/roomToThreadBrowser.ts index ae3c72abb..ffa955fd2 100644 --- a/src/app/state/room/roomToThreadBrowser.ts +++ b/src/app/state/room/roomToThreadBrowser.ts @@ -2,7 +2,7 @@ import { atom } from 'jotai'; import { atomFamily } from 'jotai/utils'; const createThreadBrowserAtom = () => atom(false); -export type TThreadBrowserAtom = ReturnType; +type TThreadBrowserAtom = ReturnType; /** * Tracks whether the thread browser panel is open per room. diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 801de7eb6..12a62b698 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -12,21 +12,22 @@ import { RoomEvent, SyncState, EventType, ClientEvent, KnownMembership } from '$ import { useCallback, useEffect } from 'react'; import type { RoomToUnread, UnreadInfo, Unread } from '$types/matrix/room'; import { NotificationType } from '$types/matrix/room'; +import { getAllParents } from '$utils/room/hierarchy'; import { - getAllParents, getNotificationType, getUnreadInfo, getUnreadInfos, getUnreadInfosForRooms, isNotificationEvent, -} from '$utils/room'; +} from '$utils/room/unread'; import { useSyncState } from '$hooks/useSyncState'; import { useRoomsNotificationPreferencesContext } from '$hooks/useRoomsNotificationPreferences'; +import { useMatrixEvent } from '$hooks/useMatrixEvent'; import { getClientSyncDiagnostics, getSlidingSyncManager } from '$client/initMatrix'; import { mDirectAtom } from '$state/mDirectList'; import { roomToParentsAtom } from './roomToParents'; -export type RoomToUnreadAction = +type RoomToUnreadAction = | { type: 'RESET'; unreadInfos: UnreadInfo[]; @@ -245,8 +246,8 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo ) ); - useEffect(() => { - const handleTimelineEvent = ( + const handleTimelineEvent = useCallback( + ( mEvent: MatrixEvent, room: Room | undefined, toStartOfTimeline: boolean | undefined, @@ -292,15 +293,14 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }); } } - }; - mx.on(RoomEvent.Timeline, handleTimelineEvent); - return () => { - mx.removeListener(RoomEvent.Timeline, handleTimelineEvent); - }; - }, [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects]); + }, + [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects] + ); - useEffect(() => { - const handleReceipt = (mEvent: MatrixEvent, room: Room) => { + useMatrixEvent(mx, RoomEvent.Timeline, handleTimelineEvent); + + const handleReceipt = useCallback( + (mEvent: MatrixEvent, room: Room) => { const myUserId = mx.getUserId(); if (!myUserId) return; if (room.isSpaceRoom()) return; @@ -322,12 +322,11 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo } publishUnreadAction({ type: 'PUT', unreadInfo }); } - }; - mx.on(RoomEvent.Receipt, handleReceipt); - return () => { - mx.removeListener(RoomEvent.Receipt, handleReceipt); - }; - }, [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects]); + }, + [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects] + ); + + useMatrixEvent(mx, RoomEvent.Receipt, handleReceipt); useEffect(() => { const roomListeners = new Map(); @@ -366,8 +365,8 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }; }, [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects]); - useEffect(() => { - const handleRoomAccountData = (mEvent: MatrixEvent, room: Room) => { + const handleRoomAccountData = useCallback( + (mEvent: MatrixEvent, room: Room) => { if (room.isSpaceRoom()) return; if (mEvent.getType() !== (EventType.FullyRead as string)) return; @@ -380,12 +379,11 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo return; } publishUnreadAction({ type: 'PUT', unreadInfo }); - }; - mx.on(RoomEvent.AccountData, handleRoomAccountData); - return () => { - mx.removeListener(RoomEvent.AccountData, handleRoomAccountData); - }; - }, [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects]); + }, + [publishUnreadAction, shouldApplyUnreadFixup, mDirects] + ); + + useMatrixEvent(mx, RoomEvent.AccountData, handleRoomAccountData); useEffect(() => { publishUnreadAction({ @@ -397,28 +395,27 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }); }, [mx, publishUnreadAction, roomsNotificationPreferences, shouldApplyUnreadFixup, mDirects]); - useEffect(() => { - const handleMembershipChange = (room: Room, membership: string) => { + const handleMembershipChange = useCallback( + (room: Room, membership: string) => { if (membership !== (KnownMembership.Join as string)) { publishUnreadAction({ type: 'DELETE', roomId: room.roomId, }); } - }; - mx.on(RoomEvent.MyMembership, handleMembershipChange); - return () => { - mx.removeListener(RoomEvent.MyMembership, handleMembershipChange); - }; - }, [mx, publishUnreadAction]); + }, + [publishUnreadAction] + ); + + useMatrixEvent(mx, RoomEvent.MyMembership, handleMembershipChange); // Seed badge state immediately when a room is first registered with the client // (e.g. after joining or receiving an invite that gets auto-accepted). // This avoids the brief window after refresh where badges are invisible until // the next timeline event arrives. Notifications are NOT triggered here — // ClientNonUIFeatures handles live notification pop-ups via its own listener. - useEffect(() => { - const handleRoomAdded = (room: Room) => { + const handleRoomAdded = useCallback( + (room: Room) => { if (room.isSpaceRoom() || room.getMyMembership() !== (KnownMembership.Join as string)) return; const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup(), @@ -427,10 +424,9 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { publishUnreadAction({ type: 'PUT', unreadInfo }); } - }; - mx.on(ClientEvent.Room, handleRoomAdded as (room: Room) => void); - return () => { - mx.removeListener(ClientEvent.Room, handleRoomAdded as (room: Room) => void); - }; - }, [mx, publishUnreadAction, shouldApplyUnreadFixup, mDirects]); + }, + [publishUnreadAction, shouldApplyUnreadFixup, mDirects] + ); + + useMatrixEvent(mx, ClientEvent.Room, handleRoomAdded); }; diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index 5bfe85d1f..1c623ea9e 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -219,7 +219,7 @@ export const activeSessionIdAtom = atom; } diff --git a/src/app/styles/Text.css.ts b/src/app/styles/Text.css.ts index 4e2bd4b9b..b725bec6f 100644 --- a/src/app/styles/Text.css.ts +++ b/src/app/styles/Text.css.ts @@ -1,7 +1,7 @@ import { style } from '@vanilla-extract/css'; export const BreakWord = style({ - wordBreak: 'break-word', + overflowWrap: 'anywhere', }); export const LineClamp2 = style({ diff --git a/src/app/styles/overrides/TauriDesktop.css b/src/app/styles/overrides/TauriDesktop.css index 5863fde17..b7eda92f5 100644 --- a/src/app/styles/overrides/TauriDesktop.css +++ b/src/app/styles/overrides/TauriDesktop.css @@ -91,6 +91,8 @@ color: var(--sable-bg-on-container); background: color-mix(in srgb, var(--sable-bg-on-container) 10%, transparent); white-space: nowrap; + max-width: 50vw; + text-overflow: ellipsis; } .tauri-titlebar-status__label--success { diff --git a/src/app/theme/cache.ts b/src/app/theme/cache.ts index e70d9f256..f6464250f 100644 --- a/src/app/theme/cache.ts +++ b/src/app/theme/cache.ts @@ -4,7 +4,7 @@ const DB_VERSION = 1; const STORE = 'themes'; const UPDATE_CHANNEL = 'sable-theme-cache-updates'; -export type CachedThemeEntry = { +type CachedThemeEntry = { url: string; cssText: string; cachedAt: number; @@ -25,16 +25,6 @@ export type ThemeCacheUpdate = { contentHash: string; }; -export type ThemeCacheStats = { - entries: number; - localEntries: number; - remoteEntries: number; - totalBytes: number; - localBytes: number; - remoteBytes: number; - lastCheckedAt?: number; -}; - const updateListeners = new Set<(update: ThemeCacheUpdate) => void>(); let updateChannel: BroadcastChannel | undefined; diff --git a/src/app/theme/catalog.ts b/src/app/theme/catalog.ts index f6bab6a9e..1acf7ba02 100644 --- a/src/app/theme/catalog.ts +++ b/src/app/theme/catalog.ts @@ -1,7 +1,7 @@ import { parseGithubRawBaseUrl, rawFileUrl, type GithubRawParts } from './githubRaw'; import { fetch } from '$utils/fetch'; -export type GithubContentItem = { +type GithubContentItem = { name: string; path: string; type: 'file' | 'dir'; @@ -24,12 +24,6 @@ export type ThemeCatalogBundle = { tweaks: TweakCatalogEntry[]; }; -export type ThemeCatalogManifest = { - version?: number; - themes?: ThemePair[]; - tweaks?: TweakCatalogEntry[]; -}; - export type ListThemeCatalogOptions = { manifestUrl?: string | null; }; diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index 93124f160..bcda50f86 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -151,56 +151,6 @@ export class ASCIILexicalTable { return str; } - previous(str: string): string | undefined { - if (!this.has(str)) return undefined; - let prev = str; - const lastCode = prev.charCodeAt(prev.length - 1); - prev = prev.slice(0, prev.length - 1); - - if (lastCode === this.startCode) { - if (prev.length === 0) return undefined; - return prev; - } - - prev += String.fromCharCode(lastCode - 1); - while (prev.length < this.maxStrWidth) { - prev += String.fromCodePoint(this.endCode); - } - return prev; - } - - next(str: string): string | undefined { - if (!this.has(str)) return undefined; - let next = str; - - if (next.length < this.maxStrWidth) { - next += String.fromCharCode(this.startCode); - return next; - } - - for (let i = next.length - 1; i >= 0; i -= 1) { - const lastCode = next.charCodeAt(i); - if (lastCode !== this.endCode) { - next = next.slice(0, i) + String.fromCharCode(lastCode + 1); - return next; - } - next = next.slice(0, i); - } - return undefined; - } - - between(a: string, b: string): string | undefined { - if (!this.has(a) || !this.has(b)) { - return undefined; - } - - const centerIndex = Math.floor((this.index(a) + this.index(b)) / 2); - - const str = this.get(centerIndex); - if (str === a || str === b) return undefined; - return str; - } - nBetween(n: number, a: string, b: string): string[] | undefined { if (n <= 0 || !this.has(a) || !this.has(b)) { return undefined; diff --git a/src/app/utils/common.ts b/src/app/utils/common.ts index d59916bb7..3f590320a 100644 --- a/src/app/utils/common.ts +++ b/src/app/utils/common.ts @@ -141,6 +141,17 @@ export const suffixRename = (name: string, validator: (newName: string) => boole export const replaceSpaceWithDash = (str: string): string => str.replace(/ /g, '-'); +/** Trigger a browser download of a JSON file. */ +export const downloadJsonFile = (content: string, fileNamePrefix: string): void => { + const blob = new Blob([content], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${fileNamePrefix}-${Date.now()}.json`; + a.click(); + URL.revokeObjectURL(url); +}; + export const splitWithSpace = (content: string): string[] => { const trimmedContent = content.trim(); if (trimmedContent === '') return []; diff --git a/src/app/utils/key-symbol.ts b/src/app/utils/key-symbol.ts index 00dd1042a..205c48c49 100644 --- a/src/app/utils/key-symbol.ts +++ b/src/app/utils/key-symbol.ts @@ -1,9 +1,3 @@ export enum KeySymbol { Command = '⌘', - Shift = '⇧', - Option = '⌥', - Control = '⌃', - Hyper = '✦', - Super = '❖', - Escape = '⎋', } diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index df72ca00a..09e0f9f98 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -25,7 +25,8 @@ import type { IImageInfo, IThumbnailContent, IVideoInfo } from '$types/matrix/co import * as Sentry from '@sentry/react'; import { encryptBlobInWorker } from '$utils/mediaWorker'; import { encryptAttachmentStreaming } from '$utils/attachmentCrypto'; -import { getEventReactions, getStateEvent } from './room'; +import { getEventReactions } from './room/relations'; +import { getStateEvent } from './room/hierarchy'; import { getReactionContent } from './messageReaction'; import { matchMxId, validMxId } from './mxIdHelper'; diff --git a/src/app/utils/mediaUrl.test.ts b/src/app/utils/mediaUrl.test.ts new file mode 100644 index 000000000..ca61def03 --- /dev/null +++ b/src/app/utils/mediaUrl.test.ts @@ -0,0 +1,136 @@ +// oxlint-disable typescript/no-explicit-any +import { describe, expect, it, vi, afterEach } from 'vitest'; + +const hoistedGetSessionScope = vi.hoisted(() => vi.fn<() => string>(() => 'session_abc')); +const hoistedIsTauri = vi.hoisted(() => vi.fn<() => boolean>(() => false)); +const hoistedConvertFileSrc = vi.hoisted(() => + vi.fn<(url: string, protocol: string) => string>( + (url: string, protocol: string) => `${protocol}://${url}` + ) +); + +vi.mock('@tauri-apps/api/core', () => ({ + isTauri: hoistedIsTauri, + convertFileSrc: hoistedConvertFileSrc, +})); + +vi.mock('./mediaTransport', () => ({ + getCurrentMediaSessionScope: hoistedGetSessionScope, +})); + +import { rewriteAuthenticatedMediaUrl } from './mediaUrl'; + +afterEach(() => { + hoistedIsTauri.mockReset(); + hoistedIsTauri.mockReturnValue(false); + hoistedGetSessionScope.mockReset(); + hoistedGetSessionScope.mockReturnValue('session_abc'); +}); + +const VERSION_SNIPPET = '__sable_media_cache=3'; + +// ── Tests ─────────────────────────────────────────────────────────────────── + +describe('rewriteAuthenticatedMediaUrl', () => { + describe('non-Tauri passthrough', () => { + it('returns the URL unchanged when not in Tauri', () => { + const url = 'https://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + expect(rewriteAuthenticatedMediaUrl(url)).toBe(url); + }); + + it('returns null for null input (non-Tauri)', () => { + expect(rewriteAuthenticatedMediaUrl(null)).toBeNull(); + }); + }); + + describe('null / falsy input', () => { + it('returns null for null input in Tauri', () => { + hoistedIsTauri.mockReturnValue(true); + expect(rewriteAuthenticatedMediaUrl(null)).toBeNull(); + }); + }); + + describe('authenticated prefix rewriting (Tauri)', () => { + const prefixes = [ + '/_matrix/client/v1/media/', + '/_matrix/media/v3/download/', + '/_matrix/media/v3/thumbnail/', + '/_matrix/media/r0/download/', + '/_matrix/media/r0/thumbnail/', + ]; + + it.each(prefixes)('rewrites URLs starting with %s', (prefix) => { + hoistedIsTauri.mockReturnValue(true); + const url = `https://matrix.example.com${prefix}example.com/abc123`; + const result = rewriteAuthenticatedMediaUrl(url); + expect(result).not.toBeNull(); + expect(result).toContain('sable-media://'); + expect(result).toContain(VERSION_SNIPPET); + expect(result).toContain('__sable_media_session=session_abc'); + }); + }); + + describe('idempotency', () => { + it('returns an already-rewritten URL unchanged', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'https://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + const first = rewriteAuthenticatedMediaUrl(url) as string; + const second = rewriteAuthenticatedMediaUrl(first); + expect(second).toBe(first); + }); + + it('returns an already-rewritten sable-media:// URL unchanged', () => { + hoistedIsTauri.mockReturnValue(true); + const alreadyRewritten = + 'sable-media://https://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + const withVersion = `${alreadyRewritten}?${VERSION_SNIPPET}&__sable_media_session=session_abc`; + expect(rewriteAuthenticatedMediaUrl(withVersion)).toBe(withVersion); + }); + }); + + describe('session scoping', () => { + it('includes a session-scoped token in the rewritten URL', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'https://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + const result = rewriteAuthenticatedMediaUrl(url); + expect(result).toContain('__sable_media_session=session_abc'); + }); + + it('produces different URLs for different session scopes', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'https://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + + hoistedGetSessionScope.mockReturnValue('session_alice'); + const aliceUrl = rewriteAuthenticatedMediaUrl(url); + + hoistedGetSessionScope.mockReturnValue('session_bob'); + const bobUrl = rewriteAuthenticatedMediaUrl(url); + + expect(aliceUrl).not.toBeNull(); + expect(bobUrl).not.toBeNull(); + expect(aliceUrl).not.toEqual(bobUrl); + expect(aliceUrl).toContain('__sable_media_session=session_alice'); + expect(bobUrl).toContain('__sable_media_session=session_bob'); + }); + }); + + describe('non-media URLs', () => { + it('leaves non-Matrix URLs unchanged in Tauri', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'https://example.com/some/image.png'; + expect(rewriteAuthenticatedMediaUrl(url)).toBe(url); + }); + + it('leaves invalid URLs unchanged', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'not-a-url'; + expect(rewriteAuthenticatedMediaUrl(url)).toBe(url); + }); + + it('leaves non-http/https protocol URLs unchanged', () => { + hoistedIsTauri.mockReturnValue(true); + const url = 'ftp://matrix.example.com/_matrix/media/v3/download/example.com/abc123'; + expect(rewriteAuthenticatedMediaUrl(url)).toBe(url); + }); + }); +}); diff --git a/src/app/utils/room.reply.test.ts b/src/app/utils/room.reply.test.ts index f91731b17..8ceb7d175 100644 --- a/src/app/utils/room.reply.test.ts +++ b/src/app/utils/room.reply.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it } from 'vitest'; import { EventType, RelationType } from '$types/matrix-sdk'; import type { EventTimelineSet, MatrixEvent, Room } from '$types/matrix-sdk'; -import { extractReplyDraftBody, findRoomEventById, resolveReplyDraftTarget } from './room'; +import { + extractReplyDraftBody, + findRoomEventById, + resolveReplyDraftTarget, +} from './room/relations'; /* oxlint-disable typescript/no-explicit-any */ diff --git a/src/app/utils/room.spaceLeave.test.ts b/src/app/utils/room.spaceLeave.test.ts index ee62496b6..3cb0c38a4 100644 --- a/src/app/utils/room.spaceLeave.test.ts +++ b/src/app/utils/room.spaceLeave.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { EventType, KnownMembership, RoomType } from '$types/matrix-sdk'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { getJoinedSpaceChildrenLeaveOrder, getJoinedSpaceChildrenSummary } from './room'; +import { getJoinedSpaceChildrenLeaveOrder, getJoinedSpaceChildrenSummary } from './room/hierarchy'; /* oxlint-disable typescript/no-explicit-any */ diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts deleted file mode 100644 index c16917f6f..000000000 --- a/src/app/utils/room.ts +++ /dev/null @@ -1,1344 +0,0 @@ -import type { - AccountDataEvents, - EventTimelineSet, - IMentions, - IPowerLevelsContent, - IPushRule, - IPushRules, - IThreadBundledRelationship, - MatrixClient, - MatrixEvent, - Room, - RoomMember, - StateEvents, -} from '$types/matrix-sdk'; -import { - EventTimeline, - EventType, - NotificationCountType, - PushRuleActionName, - RelationType, - MsgType, - KnownMembership, - RoomType, -} from '$types/matrix-sdk'; - -import type { IRoomCreateContent, RoomToParents, UnreadInfo } from '$types/matrix/room'; -import { NotificationType } from '$types/matrix/room'; -import { getMxIdLocalPart } from '$utils/matrix'; -import { mxcUrlToHttp } from './mediaUrl'; - -export const getStateEvent = ( - room: Room, - eventType: keyof StateEvents, - stateKey = '' -): MatrixEvent | undefined => - room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType, stateKey) ?? - undefined; - -export const getStateEvents = (room: Room, eventType: keyof StateEvents): MatrixEvent[] => - room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType) ?? []; - -export const getAccountData = ( - mx: MatrixClient, - eventType: keyof AccountDataEvents -): MatrixEvent | undefined => mx.getAccountData(eventType); - -export const getMDirects = (mDirectEvent: MatrixEvent): Set => { - const roomIds = new Set(); - const userIdToDirects = mDirectEvent?.getContent(); - - if (userIdToDirects === undefined) return roomIds; - - Object.keys(userIdToDirects).forEach((userId) => { - const directs = userIdToDirects[userId]; - if (Array.isArray(directs)) { - directs.forEach((id) => { - if (typeof id === 'string') roomIds.add(id); - }); - } - }); - - return roomIds; -}; - -export const isDirectInvite = (room: Room | null, myUserId: string | null): boolean => { - if (!room || !myUserId) return false; - const me = room.getMember(myUserId); - const memberEvent = me?.events?.member; - const content = memberEvent?.getContent(); - return content?.is_direct === true; -}; - -export const isSpace = (room: Room | null): boolean => { - if (!room) return false; - const event = getStateEvent(room, EventType.RoomCreate); - if (!event) return false; - return event.getContent().type === RoomType.Space; -}; - -export const isRoom = (room: Room | null): boolean => { - if (!room) return false; - const event = getStateEvent(room, EventType.RoomCreate); - if (!event) return true; - return event.getContent().type !== RoomType.Space; -}; - -export const isUnsupportedRoom = (room: Room | null): boolean => { - if (!room) return false; - const event = getStateEvent(room, EventType.RoomCreate); - if (!event) return true; // Consider room unsupported if m.room.create event doesn't exist - return event.getContent().type !== undefined && event.getContent().type !== RoomType.Space; -}; - -/** - * Detects if a room is a direct message room using multiple signals for robustness: - * 1. Primary: checks if room is in mDirects set (from m.direct account data) - * 2. Fallback: checks if room has exactly 2 joined members (classic DM heuristic) - * - * The fallback handles cases where m.direct account data is incomplete or outdated. - */ -export const isDMRoom = (room: Room, mDirects?: Set): boolean => { - // Primary signal: check m.direct account data - if (mDirects?.has(room.roomId)) { - return true; - } - - // Fallback: use member count heuristic for untagged DMs - // Only applies to non-space rooms with exactly 2 members (you + them) - if (!room.isSpaceRoom() && room.getJoinedMemberCount() === 2) { - return true; - } - - return false; -}; - -export function isValidChild(mEvent: MatrixEvent): boolean { - return ( - mEvent.getType() === (EventType.SpaceChild as string) && - Array.isArray(mEvent.getContent<{ via: string[] }>().via) - ); -} - -export const getAllParents = (roomToParents: RoomToParents, roomId: string): Set => { - const allParents = new Set(); - - const addAllParentIds = (rId: string) => { - if (allParents.has(rId)) return; - allParents.add(rId); - - const parents = roomToParents.get(rId); - parents?.forEach((id) => addAllParentIds(id)); - }; - addAllParentIds(roomId); - allParents.delete(roomId); - return allParents; -}; - -export const getSpaceChildren = (room: Room) => - getStateEvents(room, EventType.SpaceChild).reduce((filtered, mEvent) => { - const stateKey = mEvent.getStateKey(); - if (isValidChild(mEvent) && stateKey) { - filtered.push(stateKey); - } - return filtered; - }, []); - -export const getJoinedSpaceChildrenLeaveOrder = ( - mx: MatrixClient, - rootSpaceId: string -): string[] => { - const leaveOrder: string[] = []; - const visited = new Set(); - - const isJoinedChild = (room: Room): boolean => - room.getMyMembership() === (KnownMembership.Join as string) && - !getStateEvent(room, EventType.RoomTombstone); - - const visitSpace = (spaceId: string) => { - if (visited.has(spaceId)) return; - visited.add(spaceId); - - const space = mx.getRoom(spaceId); - if (!space || !isJoinedChild(space)) return; - - getSpaceChildren(space).forEach((childId) => { - if (visited.has(childId)) return; - - const child = mx.getRoom(childId); - if (!child || !isJoinedChild(child)) return; - - if (child.isSpaceRoom()) { - visitSpace(childId); - return; - } - - visited.add(childId); - leaveOrder.push(childId); - }); - - if (spaceId !== rootSpaceId) { - leaveOrder.push(spaceId); - } - }; - - visitSpace(rootSpaceId); - - return leaveOrder.filter((id) => id !== rootSpaceId); -}; - -export type JoinedSpaceChildrenSummary = { - leaveOrder: string[]; - roomCount: number; - subspaceCount: number; -}; - -export const getJoinedSpaceChildrenSummary = ( - mx: MatrixClient, - rootSpaceId: string -): JoinedSpaceChildrenSummary => { - const leaveOrder = getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId); - let roomCount = 0; - let subspaceCount = 0; - - leaveOrder.forEach((id) => { - const room = mx.getRoom(id); - if (room?.isSpaceRoom()) { - subspaceCount += 1; - } else { - roomCount += 1; - } - }); - - return { leaveOrder, roomCount, subspaceCount }; -}; - -export const getRecursiveSpaceLeaveOrder = (mx: MatrixClient, rootSpaceId: string): string[] => [ - ...getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId), - rootSpaceId, -]; - -export const mapParentWithChildren = ( - roomToParents: RoomToParents, - roomId: string, - children: string[] -) => { - const allParents = getAllParents(roomToParents, roomId); - children.forEach((childId) => { - if (allParents.has(childId)) { - // Space cycle detected. - return; - } - const parents = roomToParents.get(childId) ?? new Set(); - parents.add(roomId); - roomToParents.set(childId, parents); - }); -}; - -export const getRoomToParents = (mx: MatrixClient): RoomToParents => { - const map: RoomToParents = new Map(); - mx.getRooms() - .filter((room) => isSpace(room) && room.getMyMembership() === (KnownMembership.Join as string)) - .forEach((room) => mapParentWithChildren(map, room.roomId, getSpaceChildren(room))); - - return map; -}; - -export const getOrphanParents = (roomToParents: RoomToParents, roomId: string): string[] => { - const parents = getAllParents(roomToParents, roomId); - return Array.from(parents).filter((parentRoomId) => !roomToParents.has(parentRoomId)); -}; - -const hasNotifyPushAction = (actions: IPushRule['actions']): boolean => - actions.some((a) => typeof a === 'string' && a === PushRuleActionName.Notify); - -const findRoomMuteOverrideRule = ( - overrideRules: IPushRule[] | undefined, - roomId: string -): IPushRule | undefined => - overrideRules?.find( - (rule) => - rule.rule_id === roomId && rule.rule_id.startsWith('!') && !hasNotifyPushAction(rule.actions) - ); - -export const getNotificationType = (mx: MatrixClient, roomId: string): NotificationType => { - const overrideRules = mx.getAccountData(EventType.PushRules)?.getContent() - ?.global?.override; - if (findRoomMuteOverrideRule(overrideRules, roomId)) { - return NotificationType.Mute; - } - - let roomPushRule: IPushRule | undefined; - try { - roomPushRule = mx.getRoomPushRule('global', roomId); - } catch { - roomPushRule = undefined; - } - - if (!roomPushRule) { - return NotificationType.Default; - } - - if ((roomPushRule.actions[0] as string) === 'notify') return NotificationType.AllMessages; - return NotificationType.MentionsAndKeywords; -}; - -const NOTIFICATION_EVENT_TYPES = new Set([ - 'm.room.create', - 'm.room.message', - 'm.room.encrypted', - 'm.room.member', - 'm.sticker', - 'm.reaction', -]); -export const isNotificationEvent = (mEvent: MatrixEvent, room?: Room, userId?: string) => { - const eType = mEvent.getType(); - if (!NOTIFICATION_EVENT_TYPES.has(eType)) { - return false; - } - if (eType === 'm.room.member') return false; - - if (mEvent.isRedacted()) return false; - const relation = mEvent.getRelation(); - const relationType = relation?.rel_type; - - // Filter out edits - they shouldn't count as new notifications - if (relationType === 'm.replace') return false; - - // For reactions: only count them if they're reactions to the current user's messages - if (relationType === 'm.annotation') { - if (!room || !userId || !relation) { - // If we don't have room/userId/relation context, filter out all reactions (safe default) - return false; - } - // Get the event being reacted to - const reactedToEventId = relation.event_id; - if (!reactedToEventId) return false; - - const reactedToEvent = room.findEventById(reactedToEventId); - // Only count as notification if the reacted-to message was sent by current user - return reactedToEvent?.getSender() === userId; - } - - return true; -}; - -export const roomHaveNotification = (room: Room): boolean => { - const total = room.getUnreadNotificationCount(NotificationCountType.Total); - const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); - - return total > 0 || highlight > 0; -}; - -export const roomHaveUnread = (mx: MatrixClient, room: Room) => { - if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return false; - const userId = mx.getUserId(); - if (!userId) return false; - const readUpToId = room.getEventReadUpTo(userId); - const liveEvents = room.getLiveTimeline().getEvents(); - - if (!readUpToId) { - return false; - } - - const latestEvent = liveEvents[liveEvents.length - 1]; - - if (latestEvent?.getSender() === userId) { - return false; - } - - for (let i = liveEvents.length - 1; i >= 0; i -= 1) { - const event = liveEvents[i]; - if (!event) return false; - if (event.getId() === readUpToId) { - return false; - } - if (isNotificationEvent(event, room, userId)) { - return true; - } - } - return false; -}; - -type UnreadInfoOptions = { - applyFixup?: boolean; - mDirects?: Set; -}; - -const unreadInfoFixupInProgress = new WeakSet(); - -export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadInfo => { - if (getNotificationType(room.client, room.roomId) === NotificationType.Mute) { - return { roomId: room.roomId, highlight: 0, total: 0 }; - } - - const userId = room.client.getUserId(); - if (userId && options?.applyFixup && !unreadInfoFixupInProgress.has(room)) { - unreadInfoFixupInProgress.add(room); - try { - room.fixupNotifications(userId); - } finally { - unreadInfoFixupInProgress.delete(room); - } - } - - let total = room.getUnreadNotificationCount(NotificationCountType.Total); - const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); - let hasTimelineUnread: boolean | undefined; - const roomHasTimelineUnread = () => { - hasTimelineUnread ??= roomHaveUnread(room.client, room); - return hasTimelineUnread; - }; - - // Check if this is a DM and what notification type it has (using multiple signals for robustness) - const isDM = isDMRoom(room, options?.mDirects); - const notificationType = isDM ? getNotificationType(room.client, room.roomId) : undefined; - const shouldForceDMHighlight = - isDM && - notificationType !== NotificationType.Mute && - notificationType !== NotificationType.MentionsAndKeywords; - - // If our latest main-timeline notification event is confirmed read, clamp its stale count. - // Only apply to the room (non-thread) portion so thread reply counts are preserved. - // Guard: only clamp when the room has NO receipt-confirmed unread events; if roomHaveUnread - // is true then there genuinely are unread messages and the SDK count is not fully stale. - if (userId && total > 0 && highlight === 0 && !roomHasTimelineUnread()) { - const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total); - if (roomTotal > 0) { - const liveEvents = room.getLiveTimeline().getEvents(); - // Exclude the user's own messages: own sent events are always "read" (hasUserReadEvent - // returns true for them), which would cause the clamp to fire incorrectly. - const latestNotification = [...liveEvents] - .toReversed() - .find( - (event) => - !event.isSending() && - event.getSender() !== userId && - isNotificationEvent(event, room, userId) - ); - const latestNotificationId = latestNotification?.getId(); - if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { - // Subtract only the stale main-timeline count; thread totals remain intact. - total -= roomTotal; - } - } - } - - // Fallback: SDK counters are stale/zero but there are receipt-confirmed unread - // messages. Walk the live timeline to compute real counts so the badge number - // and highlight colour reflect actual state rather than a hard-coded stub. - if (total === 0 && highlight === 0 && userId && roomHasTimelineUnread()) { - const readUpToId = room.getEventReadUpTo(userId); - const liveEvents = room.getLiveTimeline().getEvents(); - let fallbackTotal = 0; - let fallbackHighlight = 0; - const pushProcessor = room.client.pushProcessor; - for (let i = liveEvents.length - 1; i >= 0; i -= 1) { - const event = liveEvents[i]; - if (!event) break; - if (event.getId() === readUpToId) break; - if (isNotificationEvent(event, room, userId) && event.getSender() !== userId) { - fallbackTotal += 1; - const pushActions = pushProcessor.actionsForEvent(event); - if (pushActions?.tweaks?.highlight) fallbackHighlight += 1; - } - } - if (fallbackTotal > 0) { - return { - roomId: room.roomId, - highlight: fallbackHighlight, - total: fallbackTotal, - }; - } - } - - // Sliding sync limitation: unvisited rooms don't have read receipt data, but may have - // timeline activity. Check for notification events from others in the timeline to show a - // badge even when SDK counts are 0 (or unreliable without receipts). - if (userId) { - const readUpToId = room.getEventReadUpTo(userId); - - // If we have no read receipt, SDK counts may be unreliable. Always check timeline. - if (!readUpToId) { - const liveEvents = room.getLiveTimeline().getEvents(); - const fullyReadEventId = room - .getAccountData(EventType.FullyRead) - ?.getContent<{ event_id?: string }>()?.event_id; - let hasActivity = false; - for (let i = liveEvents.length - 1; i >= 0; i -= 1) { - const event = liveEvents[i]; - if (!event || event.getId() === fullyReadEventId) break; - if (event.getSender() !== userId && isNotificationEvent(event, room, userId)) { - hasActivity = true; - break; - } - } - - if (hasActivity) { - // If SDK already has counts, use those. Otherwise show dot badge (count=1). - if (total === 0 && highlight === 0) { - return { roomId: room.roomId, highlight: 0, total: 1 }; - } - // SDK has counts but no receipt - trust the counts and show them - return { roomId: room.roomId, highlight, total }; - } - } - } - - // For DMs with Default or AllMessages notification type: if there are unread messages, - // ensure we show a notification badge (treat as highlight for badge color purposes). - // This handles cases where push rules don't properly match (e.g., classic sync with - // member_count condition failures, or sliding sync with limited required_state). - if (shouldForceDMHighlight && total > 0 && highlight === 0) { - return { - roomId: room.roomId, - highlight: total, // Treat all unread messages as highlights for DMs - total, - }; - } - - return { - roomId: room.roomId, - highlight, - total: Math.max(total, highlight), - }; -}; - -export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): UnreadInfo[] => { - const unreadInfos = mx.getRooms().reduce((unread, room) => { - if (room.isSpaceRoom()) return unread; - if (room.getMyMembership() !== 'join') return unread; - if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread; - - // Always call getUnreadInfo - it has fallback logic for sliding sync rooms without receipts - const unreadInfo = getUnreadInfo(room, options); - if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { - unread.push(unreadInfo); - } - - return unread; - }, []); - - return unreadInfos; -}; - -export const getUnreadInfosForRooms = ( - mx: MatrixClient, - roomIds: Iterable, - options?: UnreadInfoOptions -): { unread: UnreadInfo[]; deleted: string[] } => { - const unread: UnreadInfo[] = []; - const deleted: string[] = []; - - for (const roomId of roomIds) { - const room = mx.getRoom(roomId); - if (!room) { - deleted.push(roomId); - continue; - } - // Space unread is derived from children in the atom reducer; skip like - // getUnreadInfos rather than deleting. - if (room.isSpaceRoom()) continue; - if (room.getMyMembership() !== 'join') { - deleted.push(roomId); - continue; - } - if (getNotificationType(mx, room.roomId) === NotificationType.Mute) { - deleted.push(roomId); - continue; - } - - const unreadInfo = getUnreadInfo(room, options); - if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { - unread.push(unreadInfo); - } else { - deleted.push(roomId); - } - } - - return { unread, deleted }; -}; - -/** - * The square-cropped avatar conversion every avatar call site repeats. Goes - * through `mxcUrlToHttp` so the Tauri media rewrite is never bypassed. - */ -export const getAvatarUrl = ( - mx: MatrixClient, - mxcUrl: string | null | undefined, - size: number, - useAuthentication = false -): string | undefined => - mxcUrl - ? (mxcUrlToHttp(mx, mxcUrl, useAuthentication, size, size, 'crop') ?? undefined) - : undefined; - -export const getRoomAvatarUrl = ( - mx: MatrixClient, - room: Room, - size: 32 | 96 = 32, - useAuthentication = false -): string | undefined => getAvatarUrl(mx, room.getMxcAvatarUrl(), size, useAuthentication); - -export const getDirectRoomAvatarUrl = ( - mx: MatrixClient, - room: Room, - size: 32 | 96 = 32, - useAuthentication = false -): string | undefined => { - const mxcUrl = room.getAvatarFallbackMember()?.getMxcAvatarUrl(); - - if (!mxcUrl) { - return getRoomAvatarUrl(mx, room, size, useAuthentication); - } - - return getAvatarUrl(mx, mxcUrl, size, useAuthentication); -}; - -export const trimReplyFromBody = (body: string): string => { - const match = body.match(/^> <.+?> .+\n(>.*\n)*?\n/m); - if (!match) return body; - return body.slice(match[0].length); -}; - -export const trimReplyFromFormattedBody = (formattedBody: string): string => { - const suffix = ''; - const i = formattedBody.lastIndexOf(suffix); - if (i < 0) { - return formattedBody; - } - return formattedBody.slice(i + suffix.length); -}; - -export const getMemberDisplayName = ( - room: Room, - userId: string, - nicknames?: Record -): string | undefined => { - if (nicknames?.[userId]) return nicknames[userId]; - const member = room.getMember(userId); - const name = member?.rawDisplayName; - if (name === userId) return undefined; - if ( - name?.replace( - // oxlint-disable-next-line no-misleading-character-class -- Stripping invisible formatting characters from display names - /[\p{Cc}\p{Cf}\u180B-\u180F\uFE00-\uFE0F\u200B-\u200D\t\n ]/gu, - '' - ).length === 0 - ) - return undefined; - return name; -}; - -export const getTimelineSenderDisplayName = ( - room: Room, - userId: string, - nicknames?: Record, - profileDisplayName?: string -): string => - getMemberDisplayName(room, userId, nicknames) ?? - profileDisplayName ?? - getMxIdLocalPart(userId) ?? - userId; - -export const getMemberSearchStr = ( - member: RoomMember, - query: string, - mxIdToName: (mxId: string) => string, - nicknames?: Record -): string[] => { - const nickname = nicknames?.[member.userId]; - const displayName = - member.rawDisplayName === member.userId ? mxIdToName(member.userId) : member.rawDisplayName; - const idStr = - query.startsWith('@') || query.indexOf(':') > -1 ? member.userId : mxIdToName(member.userId); - - const strings: string[] = []; - if (nickname) strings.push(nickname); - strings.push(displayName, idStr); - return strings; -}; - -export const getMemberAvatarMxc = (room: Room, userId: string): string | undefined => { - const member = room.getMember(userId); - return member?.getMxcAvatarUrl(); -}; - -export const isMembershipChanged = (mEvent: MatrixEvent): boolean => - mEvent.getContent().membership !== mEvent.getPrevContent().membership || - mEvent.getContent().reason !== mEvent.getPrevContent().reason; - -export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string) => - timelineSet.relations.getChildEventsForEvent( - eventId, - RelationType.Annotation, - EventType.Reaction - ); - -export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, eventType: string) => - timelineSet.relations.getChildEventsForEvent(eventId, RelationType.Replace, eventType); - -const getLatestEdit = ( - targetEvent: MatrixEvent, - editEvents: MatrixEvent[] -): MatrixEvent | undefined => { - const eventByTargetSender = (rEvent: MatrixEvent) => - rEvent.getSender() === targetEvent.getSender(); - return editEvents.toSorted((m1, m2) => m2.getTs() - m1.getTs()).find(eventByTargetSender); -}; - -export const getEditedEvent = ( - mEventId: string, - mEvent: MatrixEvent, - timelineSet: EventTimelineSet -): MatrixEvent | undefined => { - const edits = getEventEdits(timelineSet, mEventId, mEvent.getType()); - return edits && getLatestEdit(mEvent, edits.getRelations()); -}; - -export const isEditEvent = (mEvent: MatrixEvent): boolean => { - const relType = mEvent.getRelation()?.rel_type; - if (relType === (RelationType.Replace as string)) return true; - if (mEvent.getContent()['m.new_content'] !== undefined) return true; - return false; -}; - -export const isReactionEvent = (mEvent: MatrixEvent): boolean => - mEvent.getType() === (EventType.Reaction as string); - -const FORWARDABLE_EVENT_TYPES = new Set([ - EventType.RoomMessage as string, - EventType.RoomMessageEncrypted as string, - EventType.Sticker as string, -]); - -export const canForwardEvent = (mEvent: MatrixEvent): boolean => { - if (mEvent.isRedacted()) return false; - if (isEditEvent(mEvent)) return false; - if (mEvent.getType() === (EventType.RoomRedaction as string)) return false; - if (isReactionEvent(mEvent)) return false; - if (typeof mEvent.getStateKey() === 'string') return false; - if (mEvent.isRedaction()) return false; - return FORWARDABLE_EVENT_TYPES.has(mEvent.getType()); -}; - -export const getReactionKey = (mEvent: MatrixEvent): string | undefined => { - const key = mEvent.getRelation()?.key; - if (typeof key === 'string' && key.length > 0) return key; - - const contentRelatesTo = mEvent.getContent()['m.relates_to'] as { key?: string } | undefined; - if (typeof contentRelatesTo?.key === 'string' && contentRelatesTo.key.length > 0) { - return contentRelatesTo.key; - } - - const originalRelatesTo = mEvent.getOriginalContent?.()?.['m.relates_to'] as - | { key?: string } - | undefined; - if (typeof originalRelatesTo?.key === 'string' && originalRelatesTo.key.length > 0) { - return originalRelatesTo.key; - } - - return undefined; -}; - -const readReactionShortcode = ( - content: Record | undefined -): string | undefined => { - if (!content) return undefined; - const shortcode = content.shortcode ?? content['com.beeper.reaction.shortcode']; - return typeof shortcode === 'string' && shortcode.length > 0 ? shortcode : undefined; -}; - -export const getReactionShortcode = (mEvent: MatrixEvent): string | undefined => - readReactionShortcode(mEvent.getContent()) ?? - readReactionShortcode(mEvent.getOriginalContent?.()); - -export const getReactionAnnotationTargetId = (reactionEvent: MatrixEvent): string | undefined => { - const eventId = reactionEvent.getRelation()?.event_id; - if (typeof eventId === 'string' && eventId.length > 0) return eventId; - - const contentRelatesTo = reactionEvent.getContent()['m.relates_to'] as - | { event_id?: string } - | undefined; - if (typeof contentRelatesTo?.event_id === 'string' && contentRelatesTo.event_id.length > 0) { - return contentRelatesTo.event_id; - } - - const originalRelatesTo = reactionEvent.getOriginalContent?.()?.['m.relates_to'] as - | { event_id?: string } - | undefined; - if (typeof originalRelatesTo?.event_id === 'string' && originalRelatesTo.event_id.length > 0) { - return originalRelatesTo.event_id; - } - - return undefined; -}; - -export const getRedactionReason = (mEvent: MatrixEvent): string | undefined => { - const reason = mEvent.getUnsigned()?.redacted_because?.content?.reason; - return typeof reason === 'string' && reason.length > 0 ? reason : undefined; -}; - -export const collectRelationReactionEvents = ( - linkedTimelines: EventTimeline[], - existingIds: ReadonlySet, - ignoredUsersSet: Set, - showReactions: boolean, - showReactionTombstones: boolean -): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => { - if (!showReactions && !showReactionTombstones) return []; - - const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = []; - const seen = new Set(existingIds); - - for (const timeline of linkedTimelines) { - const timelineSet = timeline.getTimelineSet(); - for (const parent of timeline.getEvents()) { - const parentId = parent.getId(); - if (!parentId) continue; - - const reactions = getEventReactions(timelineSet, parentId); - if (!reactions) continue; - - for (const reaction of reactions.getRelations()) { - const reactionId = reaction.getId(); - if (!reactionId || seen.has(reactionId)) continue; - seen.add(reactionId); - - const sender = reaction.getSender(); - if (sender && ignoredUsersSet.has(sender)) continue; - - const redacted = reaction.isRedacted(); - if (redacted && !showReactionTombstones) continue; - if (!redacted && !showReactions) continue; - - extras.push({ mEvent: reaction, timelineSet, parentId }); - } - } - } - - return extras; -}; - -export const collectRelationEditEvents = ( - linkedTimelines: EventTimeline[], - existingIds: ReadonlySet, - ignoredUsersSet: Set, - showEdits: boolean -): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => { - if (!showEdits) return []; - - const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = []; - const seen = new Set(existingIds); - - for (const timeline of linkedTimelines) { - const timelineSet = timeline.getTimelineSet(); - for (const parent of timeline.getEvents()) { - const parentId = parent.getId(); - if (!parentId || isEditEvent(parent)) continue; - - const edits = getEventEdits(timelineSet, parentId, parent.getType()); - if (!edits) continue; - - for (const editEvent of edits.getRelations()) { - const editId = editEvent.getId(); - if (!editId || seen.has(editId)) continue; - seen.add(editId); - - const sender = editEvent.getSender(); - if (sender && ignoredUsersSet.has(sender)) continue; - - extras.push({ mEvent: editEvent, timelineSet, parentId }); - } - } - } - - return extras; -}; - -export const isRedactableMessageType = (type: string): boolean => - type === (EventType.RoomMessage as string) || - type === (EventType.RoomMessageEncrypted as string) || - type === 'm.room.encrypted' || - type === (EventType.Sticker as string); - -export const getRedactionTargetId = (redactionEvent: MatrixEvent): string | undefined => { - const redacts = redactionEvent.event?.redacts; - if (typeof redacts === 'string') return redacts; - const associated = redactionEvent.getAssociatedId?.(); - return typeof associated === 'string' ? associated : undefined; -}; - -export const getRedactionTargetEvent = ( - timelineSet: EventTimelineSet, - redactionEvent: MatrixEvent -): MatrixEvent | undefined => { - const targetId = getRedactionTargetId(redactionEvent); - if (!targetId) return undefined; - return timelineSet.findEventById(targetId); -}; - -export const shouldShowRedactionTimelineEvent = ( - mEvent: MatrixEvent, - timelineSet: EventTimelineSet, - hiddenEventRedactionTimeline: boolean, - hiddenEventReactionRedactionTimeline: boolean -): boolean => { - if (!mEvent.isRedaction()) return false; - const target = getRedactionTargetEvent(timelineSet, mEvent); - if (target?.getType() === (EventType.Reaction as string)) { - return hiddenEventReactionRedactionTimeline; - } - return hiddenEventRedactionTimeline; -}; - -const readReplaceTargetId = ( - relatesTo: { rel_type?: string; event_id?: string } | undefined -): string | undefined => { - if (relatesTo?.rel_type !== (RelationType.Replace as string)) return undefined; - const eventId = relatesTo.event_id; - return typeof eventId === 'string' && eventId.length > 0 ? eventId : undefined; -}; - -export const getEditTargetId = (editEvent: MatrixEvent): string | undefined => { - const relationEventId = editEvent.getRelation()?.event_id; - if (typeof relationEventId === 'string' && relationEventId.length > 0) { - return relationEventId; - } - - const content = editEvent.getContent(); - const fromContent = readReplaceTargetId( - content['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined - ); - if (fromContent) return fromContent; - - const wireContent = editEvent.getWireContent?.() as Record | undefined; - const fromWire = readReplaceTargetId( - wireContent?.['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined - ); - if (fromWire) return fromWire; - - return readReplaceTargetId( - editEvent.getOriginalContent?.()?.['m.relates_to'] as - | { rel_type?: string; event_id?: string } - | undefined - ); -}; - -export const getEditChain = ( - timelineSet: EventTimelineSet, - eventId: string, - eventType: string, - room?: Room -): { original: MatrixEvent; edits: MatrixEvent[] } | undefined => { - let original = timelineSet.findEventById(eventId); - if (!original && room) { - original = room.findEventById(eventId) ?? undefined; - } - if (!original) return undefined; - - const editsRelation = getEventEdits(timelineSet, eventId, original.getType() ?? eventType); - const edits = editsRelation - ? [...editsRelation.getRelations()].toSorted((a, b) => a.getTs() - b.getTs()) - : []; - return { original, edits }; -}; - -const getEditChainEvents = ( - currentEditEvent: MatrixEvent, - chain: { original: MatrixEvent; edits: MatrixEvent[] } -): MatrixEvent[] => { - const currentId = currentEditEvent.getId(); - const edits = - currentId && !chain.edits.some((editEvent) => editEvent.getId() === currentId) - ? [...chain.edits, currentEditEvent].toSorted((a, b) => a.getTs() - b.getTs()) - : chain.edits; - return [chain.original, ...edits]; -}; - -export const getPreviousEditId = ( - currentEditEvent: MatrixEvent, - chain: { original: MatrixEvent; edits: MatrixEvent[] } -): string | undefined => { - const currentId = currentEditEvent.getId(); - if (!currentId) return undefined; - - const allEvents = getEditChainEvents(currentEditEvent, chain); - const idx = allEvents.findIndex((e) => e.getId() === currentId); - if (idx <= 0) return undefined; - return allEvents[idx - 1]?.getId(); -}; - -const getPreviousEditEvent = ( - currentEditEvent: MatrixEvent, - chain: { original: MatrixEvent; edits: MatrixEvent[] } -): MatrixEvent | undefined => { - const currentId = currentEditEvent.getId(); - if (!currentId) return undefined; - - const allEvents = getEditChainEvents(currentEditEvent, chain); - const idx = allEvents.findIndex((e) => e.getId() === currentId); - if (idx <= 0) return undefined; - return allEvents[idx - 1]; -}; - -const EDIT_DIFF_MSGTYPES = new Set([MsgType.Text, MsgType.Emote, MsgType.Notice]); - -const getMessageVersionBody = (mEvent: MatrixEvent): string | undefined => { - const content = mEvent.getContent(); - const wireContent = mEvent.getWireContent?.() as Record | undefined; - - let versionContent: Record | undefined; - if (isEditEvent(mEvent)) { - versionContent = - (content['m.new_content'] as Record | undefined) ?? - (wireContent?.['m.new_content'] as Record | undefined); - } else { - versionContent = - (mEvent.getOriginalContent?.() as Record | undefined) ?? - (content as Record); - } - - const fallbackContent = - (!versionContent || typeof versionContent.body !== 'string') && mEvent.getOriginalContent?.() - ? (mEvent.getOriginalContent?.() as Record) - : undefined; - const resolvedContent = - versionContent && typeof versionContent === 'object' ? versionContent : fallbackContent; - if (!resolvedContent || typeof resolvedContent !== 'object') return undefined; - - const msgtype = resolvedContent.msgtype; - if (typeof msgtype === 'string' && !EDIT_DIFF_MSGTYPES.has(msgtype)) { - return undefined; - } - - const body = resolvedContent.body; - return typeof body === 'string' ? trimReplyFromBody(body) : undefined; -}; - -export const getEditDiffBodies = ( - editEvent: MatrixEvent, - timelineSet: EventTimelineSet, - room?: Room -): { oldBody?: string; newBody?: string } => { - const newBody = getMessageVersionBody(editEvent); - const editTargetId = getEditTargetId(editEvent); - if (!editTargetId) { - return { newBody }; - } - - const chain = getEditChain(timelineSet, editTargetId, editEvent.getType(), room); - let previousEvent = chain ? getPreviousEditEvent(editEvent, chain) : undefined; - if (!previousEvent) { - previousEvent = - chain?.original ?? - timelineSet.findEventById(editTargetId) ?? - room?.findEventById(editTargetId); - } - - const oldBody = - previousEvent && previousEvent.getId() !== editEvent.getId() - ? getMessageVersionBody(previousEvent) - : undefined; - - return { oldBody, newBody }; -}; - -export const canEditEvent = (mx: MatrixClient, mEvent: MatrixEvent) => { - const content = mEvent.getContent(); - const relationType = content['m.relates_to']?.rel_type; - return ( - mEvent.getSender() === mx.getUserId() && - mEvent.getType() === (EventType.RoomMessage as string) && - (!relationType || relationType === (RelationType.Thread as string)) && - (content.msgtype === MsgType.Text || - content.msgtype === MsgType.Emote || - content.msgtype === MsgType.Notice || - content.msgtype === MsgType.Image || - content.msgtype === MsgType.Video || - content.msgtype === MsgType.Audio || - content.msgtype === MsgType.File) - ); -}; - -export const reactionOrEditEvent = (mEvent: MatrixEvent): boolean => { - const relType = mEvent.getRelation()?.rel_type; - if ( - relType === (RelationType.Annotation as string) || - relType === (RelationType.Replace as string) - ) - return true; - - // Sliding sync proxies may omit m.relates_to on the initial delivery of timeline - // events. Detect edit events by the presence of m.new_content in the event - // content even when the relation metadata is absent, so they are filtered from - // the rendered timeline rather than falling through as unsupported messages. - if (mEvent.getContent()['m.new_content'] !== undefined) return true; - - return false; -}; - -export const isThreadRelationEvent = (mEvent: MatrixEvent, threadRootId?: string): boolean => { - const relation = - mEvent.getRelation?.() ?? - ( - mEvent.getWireContent?.() as { - 'm.relates_to'?: { rel_type?: unknown; event_id?: unknown }; - } - )?.['m.relates_to'] ?? - ( - mEvent.getContent?.() as { - 'm.relates_to'?: { rel_type?: unknown; event_id?: unknown }; - } - )?.['m.relates_to']; - - return ( - relation?.rel_type === (RelationType.Thread as string) && - (threadRootId === undefined || relation.event_id === threadRootId) - ); -}; - -export const hasThreadRootAggregation = (mEvent: MatrixEvent): boolean => - (mEvent.getServerAggregatedRelation?.(RelationType.Thread as string) - ?.count ?? 0) > 0; - -/** - * Resolve the list of reply events to show for a thread. - * - * Prefers events from the SDK Thread object (authoritative, full history) but - * falls back to scanning the main room timeline when the Thread object was - * created without `initialEvents` (as happens with classic sync). In that - * case `thread.events` contains only the root event, so filtering it yields an - * empty array — we must fall back rather than showing nothing. - */ -export const getThreadReplyEvents = (room: Room, threadRootId: string): MatrixEvent[] => { - const isReply = (ev: MatrixEvent) => - ev.getId() !== threadRootId && - !reactionOrEditEvent(ev) && - isThreadRelationEvent(ev, threadRootId); - - const thread = room.getThread(threadRootId); - const fromThread = (thread?.events ?? []).filter(isReply); - if (fromThread.length > 0) return fromThread; - - return room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter(isReply); -}; - -/** - * Timeline rows skip reactions, edits, and other relation-only events. When jumping - * to a reply target, unwrap to the event that is actually rendered (root of an - * edit chain, message for a reaction annotation, etc.). - */ -export const unwrapRelationJumpTarget = (room: Room, eventId: string, maxHops = 24): string => { - let current = eventId; - for (let hop = 0; hop < maxHops; hop += 1) { - const ev = room.findEventById(current); - if (!ev) return current; - if (!reactionOrEditEvent(ev)) return current; - const related = ev.getRelation()?.event_id; - if (typeof related !== 'string' || related === current) return current; - current = related; - } - return current; -}; - -const findRelationChildEvent = ( - timelineSet: EventTimelineSet, - eventId: string -): MatrixEvent | undefined => { - for (const timeline of timelineSet.getTimelines()) { - for (const parent of timeline.getEvents()) { - const parentId = parent.getId(); - if (!parentId) continue; - - const reactionRelations = getEventReactions(timelineSet, parentId); - if (reactionRelations) { - const reaction = reactionRelations - .getRelations() - .find((candidate) => candidate.getId() === eventId); - if (reaction) return reaction; - } - - const editRelations = getEventEdits(timelineSet, parentId, parent.getType()); - if (editRelations) { - const edit = editRelations - .getRelations() - .find((candidate) => candidate.getId() === eventId); - if (edit) return edit; - } - } - } - return undefined; -}; - -export const findRoomEventById = ( - room: Room, - eventId: string, - timelineSet?: EventTimelineSet -): MatrixEvent | undefined => { - const set = timelineSet ?? room.getUnfilteredTimelineSet(); - return ( - set.findEventById(eventId) ?? - room.findEventById(eventId) ?? - findRelationChildEvent(set, eventId) - ); -}; - -export type ResolvedReplyDraftTarget = { - eventId: string; - replyEvt: MatrixEvent; -}; - -export const extractReplyDraftBody = ( - replyEvt: MatrixEvent, - timelineSet: EventTimelineSet -): { body: string; formattedBody: string } => { - const replyId = replyEvt.getId(); - const editedReply = - replyId !== undefined && !isEditEvent(replyEvt) - ? getEditedEvent(replyId, replyEvt, timelineSet) - : undefined; - const editedNewContent = editedReply?.getContent()['m.new_content']; - const content = (editedNewContent ?? replyEvt.getContent()) as Record; - const { body, formatted_body: formattedBody } = content; - const msc1767body = content['m.text']; - - const resolvedBody = - (typeof body === 'string' ? body : undefined) ?? - (typeof msc1767body === 'string' - ? msc1767body - : (msc1767body as { body?: string } | undefined)?.body) ?? - getMessageVersionBody(replyEvt) ?? - ''; - - return { - body: resolvedBody, - formattedBody: typeof formattedBody === 'string' ? formattedBody : '', - }; -}; - -export const resolveReplyDraftTarget = ( - room: Room, - clickedEventId: string, - timelineSet?: EventTimelineSet -): ResolvedReplyDraftTarget | undefined => { - const set = timelineSet ?? room.getUnfilteredTimelineSet(); - const replyEvt = findRoomEventById(room, clickedEventId, set); - if (!replyEvt) return undefined; - - const eventId = replyEvt.getId(); - if (!eventId) return undefined; - - return { eventId, replyEvt }; -}; - -export const getMentionContent = (userIds: string[], room: boolean): IMentions => { - const mMentions: IMentions = {}; - if (userIds.length > 0) { - mMentions.user_ids = userIds; - } - if (room) { - mMentions.room = true; - } - - return mMentions; -}; - -export const getCommonRooms = ( - mx: MatrixClient, - rooms: string[], - otherUserId: string -): string[] => { - const commonRooms: string[] = []; - - rooms.forEach((roomId) => { - const room = mx.getRoom(roomId); - if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return; - - const common = room.hasMembershipState(otherUserId, KnownMembership.Join); - if (common) { - commonRooms.push(roomId); - } - }); - - return commonRooms; -}; - -export const bannedInRooms = (mx: MatrixClient, rooms: string[], otherUserId: string): boolean => - rooms.some((roomId) => { - const room = mx.getRoom(roomId); - if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return false; - - return room.hasMembershipState(otherUserId, KnownMembership.Ban); - }); - -const getAllVersionsRoomCreator = (room: Room): Set => { - const creators = new Set(); - - const createEvent = getStateEvent(room, EventType.RoomCreate); - const createContent = createEvent?.getContent(); - const creator = createEvent?.getSender(); - if (typeof creator === 'string') creators.add(creator); - - if (createContent && Array.isArray(createContent.additional_creators)) { - createContent.additional_creators.forEach((c) => { - creators.add(c); - }); - } - - return creators; -}; - -export const guessPerfectParent = ( - mx: MatrixClient, - roomId: string, - parents: string[] -): string | undefined => { - if (parents.length === 1) { - return parents[0]; - } - - const getSpecialUsers = (rId: string): string[] => { - const specialUsers: Set = new Set(); - - const r = mx.getRoom(rId); - if (!r) return []; - - getAllVersionsRoomCreator(r).forEach((c) => specialUsers.add(c)); - - const powerLevels = getStateEvent( - r, - EventType.RoomPowerLevels - )?.getContent(); - - const { users_default: usersDefault, users } = powerLevels ?? {}; - const defaultPower = typeof usersDefault === 'number' ? usersDefault : 0; - - if (typeof users === 'object') - Object.keys(users).forEach((userId) => { - if (users[userId]! > defaultPower) { - specialUsers.add(userId); - } - }); - - return Array.from(specialUsers); - }; - - let perfectParent: string | undefined; - let score = 0; - - const roomSpecialUsers = getSpecialUsers(roomId); - parents.forEach((parentId) => { - const parentSpecialUsers = getSpecialUsers(parentId); - const matchedUsersCount = parentSpecialUsers.filter((userId) => - roomSpecialUsers.includes(userId) - ).length; - - if (matchedUsersCount > score) { - score = matchedUsersCount; - perfectParent = parentId; - } - }); - - return perfectParent; -}; diff --git a/src/app/utils/room.unread.test.ts b/src/app/utils/room.unread.test.ts index 2e087bfb9..fb2b70241 100644 --- a/src/app/utils/room.unread.test.ts +++ b/src/app/utils/room.unread.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest'; import { KnownMembership, NotificationCountType } from '$types/matrix-sdk'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { getUnreadInfosForRooms } from './room'; +import { getUnreadInfosForRooms } from './room/unread'; const SPACE = '!space:example.com'; const ROOM_UNREAD = '!unread:example.com'; diff --git a/src/app/utils/room/display.ts b/src/app/utils/room/display.ts new file mode 100644 index 000000000..5bbaffa64 --- /dev/null +++ b/src/app/utils/room/display.ts @@ -0,0 +1,109 @@ +import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; + +import { getMxIdLocalPart } from '$utils/matrix'; +import { mxcUrlToHttp } from '../mediaUrl'; + +/** + * The square-cropped avatar conversion every avatar call site repeats. Goes + * through `mxcUrlToHttp` so the Tauri media rewrite is never bypassed. + */ +export const getAvatarUrl = ( + mx: MatrixClient, + mxcUrl: string | null | undefined, + size: number, + useAuthentication = false +): string | undefined => + mxcUrl + ? (mxcUrlToHttp(mx, mxcUrl, useAuthentication, size, size, 'crop') ?? undefined) + : undefined; + +export const getRoomAvatarUrl = ( + mx: MatrixClient, + room: Room, + size: 32 | 96 = 32, + useAuthentication = false +): string | undefined => getAvatarUrl(mx, room.getMxcAvatarUrl(), size, useAuthentication); + +export const getDirectRoomAvatarUrl = ( + mx: MatrixClient, + room: Room, + size: 32 | 96 = 32, + useAuthentication = false +): string | undefined => { + const mxcUrl = room.getAvatarFallbackMember()?.getMxcAvatarUrl(); + + if (!mxcUrl) { + return getRoomAvatarUrl(mx, room, size, useAuthentication); + } + + return getAvatarUrl(mx, mxcUrl, size, useAuthentication); +}; + +export const trimReplyFromBody = (body: string): string => { + const match = body.match(/^> <.+?> .+\n(>.*\n)*?\n/m); + if (!match) return body; + return body.slice(match[0].length); +}; + +export const trimReplyFromFormattedBody = (formattedBody: string): string => { + const suffix = ''; + const i = formattedBody.lastIndexOf(suffix); + if (i < 0) { + return formattedBody; + } + return formattedBody.slice(i + suffix.length); +}; + +export const getMemberDisplayName = ( + room: Room, + userId: string, + nicknames?: Record +): string | undefined => { + if (nicknames?.[userId]) return nicknames[userId]; + const member = room.getMember(userId); + const name = member?.rawDisplayName; + if (name === userId) return undefined; + if ( + name?.replace( + // oxlint-disable-next-line no-misleading-character-class -- Stripping invisible formatting characters from display names + /[\p{Cc}\p{Cf}\u180B-\u180F\uFE00-\uFE0F\u200B-\u200D\t\n ]/gu, + '' + ).length === 0 + ) + return undefined; + return name; +}; + +export const getTimelineSenderDisplayName = ( + room: Room, + userId: string, + nicknames?: Record, + profileDisplayName?: string +): string => + getMemberDisplayName(room, userId, nicknames) ?? + profileDisplayName ?? + getMxIdLocalPart(userId) ?? + userId; + +export const getMemberSearchStr = ( + member: RoomMember, + query: string, + mxIdToName: (mxId: string) => string, + nicknames?: Record +): string[] => { + const nickname = nicknames?.[member.userId]; + const displayName = + member.rawDisplayName === member.userId ? mxIdToName(member.userId) : member.rawDisplayName; + const idStr = + query.startsWith('@') || query.indexOf(':') > -1 ? member.userId : mxIdToName(member.userId); + + const strings: string[] = []; + if (nickname) strings.push(nickname); + strings.push(displayName, idStr); + return strings; +}; + +export const getMemberAvatarMxc = (room: Room, userId: string): string | undefined => { + const member = room.getMember(userId); + return member?.getMxcAvatarUrl(); +}; diff --git a/src/app/utils/room/hierarchy.ts b/src/app/utils/room/hierarchy.ts new file mode 100644 index 000000000..5d2c1e07a --- /dev/null +++ b/src/app/utils/room/hierarchy.ts @@ -0,0 +1,255 @@ +import type { + AccountDataEvents, + IPowerLevelsContent, + MatrixClient, + MatrixEvent, + Room, + StateEvents, +} from '$types/matrix-sdk'; +import { EventTimeline, EventType, KnownMembership, RoomType } from '$types/matrix-sdk'; + +import type { IRoomCreateContent, RoomToParents } from '$types/matrix/room'; + +export const getStateEvent = ( + room: Room, + eventType: keyof StateEvents, + stateKey = '' +): MatrixEvent | undefined => + room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType, stateKey) ?? + undefined; + +export const getStateEvents = (room: Room, eventType: keyof StateEvents): MatrixEvent[] => + room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType) ?? []; + +export const getAccountData = ( + mx: MatrixClient, + eventType: keyof AccountDataEvents +): MatrixEvent | undefined => mx.getAccountData(eventType); + +export const isSpace = (room: Room | null): boolean => { + if (!room) return false; + const event = getStateEvent(room, EventType.RoomCreate); + if (!event) return false; + return event.getContent().type === RoomType.Space; +}; + +export const isRoom = (room: Room | null): boolean => { + if (!room) return false; + const event = getStateEvent(room, EventType.RoomCreate); + if (!event) return true; + return event.getContent().type !== RoomType.Space; +}; + +export const isUnsupportedRoom = (room: Room | null): boolean => { + if (!room) return false; + const event = getStateEvent(room, EventType.RoomCreate); + if (!event) return true; // Consider room unsupported if m.room.create event doesn't exist + return event.getContent().type !== undefined && event.getContent().type !== RoomType.Space; +}; + +export function isValidChild(mEvent: MatrixEvent): boolean { + return ( + mEvent.getType() === (EventType.SpaceChild as string) && + Array.isArray(mEvent.getContent<{ via: string[] }>().via) + ); +} + +export const getAllParents = (roomToParents: RoomToParents, roomId: string): Set => { + const allParents = new Set(); + + const addAllParentIds = (rId: string) => { + if (allParents.has(rId)) return; + allParents.add(rId); + + const parents = roomToParents.get(rId); + parents?.forEach((id) => addAllParentIds(id)); + }; + addAllParentIds(roomId); + allParents.delete(roomId); + return allParents; +}; + +export const getSpaceChildren = (room: Room) => + getStateEvents(room, EventType.SpaceChild).reduce((filtered, mEvent) => { + const stateKey = mEvent.getStateKey(); + if (isValidChild(mEvent) && stateKey) { + filtered.push(stateKey); + } + return filtered; + }, []); + +export const getJoinedSpaceChildrenLeaveOrder = ( + mx: MatrixClient, + rootSpaceId: string +): string[] => { + const leaveOrder: string[] = []; + const visited = new Set(); + + const isJoinedChild = (room: Room): boolean => + room.getMyMembership() === (KnownMembership.Join as string) && + !getStateEvent(room, EventType.RoomTombstone); + + const visitSpace = (spaceId: string) => { + if (visited.has(spaceId)) return; + visited.add(spaceId); + + const space = mx.getRoom(spaceId); + if (!space || !isJoinedChild(space)) return; + + getSpaceChildren(space).forEach((childId) => { + if (visited.has(childId)) return; + + const child = mx.getRoom(childId); + if (!child || !isJoinedChild(child)) return; + + if (child.isSpaceRoom()) { + visitSpace(childId); + return; + } + + visited.add(childId); + leaveOrder.push(childId); + }); + + if (spaceId !== rootSpaceId) { + leaveOrder.push(spaceId); + } + }; + + visitSpace(rootSpaceId); + + return leaveOrder.filter((id) => id !== rootSpaceId); +}; + +export type JoinedSpaceChildrenSummary = { + leaveOrder: string[]; + roomCount: number; + subspaceCount: number; +}; + +export const getJoinedSpaceChildrenSummary = ( + mx: MatrixClient, + rootSpaceId: string +): JoinedSpaceChildrenSummary => { + const leaveOrder = getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId); + let roomCount = 0; + let subspaceCount = 0; + + leaveOrder.forEach((id) => { + const room = mx.getRoom(id); + if (room?.isSpaceRoom()) { + subspaceCount += 1; + } else { + roomCount += 1; + } + }); + + return { leaveOrder, roomCount, subspaceCount }; +}; + +export const getRecursiveSpaceLeaveOrder = (mx: MatrixClient, rootSpaceId: string): string[] => [ + ...getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId), + rootSpaceId, +]; + +export const mapParentWithChildren = ( + roomToParents: RoomToParents, + roomId: string, + children: string[] +) => { + const allParents = getAllParents(roomToParents, roomId); + children.forEach((childId) => { + if (allParents.has(childId)) { + // Space cycle detected. + return; + } + const parents = roomToParents.get(childId) ?? new Set(); + parents.add(roomId); + roomToParents.set(childId, parents); + }); +}; + +export const getRoomToParents = (mx: MatrixClient): RoomToParents => { + const map: RoomToParents = new Map(); + mx.getRooms() + .filter((room) => isSpace(room) && room.getMyMembership() === (KnownMembership.Join as string)) + .forEach((room) => mapParentWithChildren(map, room.roomId, getSpaceChildren(room))); + + return map; +}; + +export const getOrphanParents = (roomToParents: RoomToParents, roomId: string): string[] => { + const parents = getAllParents(roomToParents, roomId); + return Array.from(parents).filter((parentRoomId) => !roomToParents.has(parentRoomId)); +}; + +const getAllVersionsRoomCreator = (room: Room): Set => { + const creators = new Set(); + + const createEvent = getStateEvent(room, EventType.RoomCreate); + const createContent = createEvent?.getContent(); + const creator = createEvent?.getSender(); + if (typeof creator === 'string') creators.add(creator); + + if (createContent && Array.isArray(createContent.additional_creators)) { + createContent.additional_creators.forEach((c) => { + creators.add(c); + }); + } + + return creators; +}; + +export const guessPerfectParent = ( + mx: MatrixClient, + roomId: string, + parents: string[] +): string | undefined => { + if (parents.length === 1) { + return parents[0]; + } + + const getSpecialUsers = (rId: string): string[] => { + const specialUsers: Set = new Set(); + + const r = mx.getRoom(rId); + if (!r) return []; + + getAllVersionsRoomCreator(r).forEach((c) => specialUsers.add(c)); + + const powerLevels = getStateEvent( + r, + EventType.RoomPowerLevels + )?.getContent(); + + const { users_default: usersDefault, users } = powerLevels ?? {}; + const defaultPower = typeof usersDefault === 'number' ? usersDefault : 0; + + if (typeof users === 'object') + Object.keys(users).forEach((userId) => { + if (users[userId]! > defaultPower) { + specialUsers.add(userId); + } + }); + + return Array.from(specialUsers); + }; + + let perfectParent: string | undefined; + let score = 0; + + const roomSpecialUsers = getSpecialUsers(roomId); + parents.forEach((parentId) => { + const parentSpecialUsers = getSpecialUsers(parentId); + const matchedUsersCount = parentSpecialUsers.filter((userId) => + roomSpecialUsers.includes(userId) + ).length; + + if (matchedUsersCount > score) { + score = matchedUsersCount; + perfectParent = parentId; + } + }); + + return perfectParent; +}; diff --git a/src/app/utils/room/relations.ts b/src/app/utils/room/relations.ts new file mode 100644 index 000000000..53de30903 --- /dev/null +++ b/src/app/utils/room/relations.ts @@ -0,0 +1,625 @@ +import type { + EventTimelineSet, + EventTimeline, + IMentions, + IThreadBundledRelationship, + MatrixClient, + MatrixEvent, + Room, +} from '$types/matrix-sdk'; +import { EventType, KnownMembership, MsgType, RelationType } from '$types/matrix-sdk'; + +// Local copy to avoid circular dependency with display.ts (which imports from $utils/matrix) +const trimReplyFromBodyLocal = (body: string): string => { + const match = body.match(/^> <.+?> .+\n(>.*\n)*?\n/m); + if (!match) return body; + return body.slice(match[0].length); +}; + +export const isMembershipChanged = (mEvent: MatrixEvent): boolean => + mEvent.getContent().membership !== mEvent.getPrevContent().membership || + mEvent.getContent().reason !== mEvent.getPrevContent().reason; + +export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string) => + timelineSet.relations.getChildEventsForEvent( + eventId, + RelationType.Annotation, + EventType.Reaction + ); + +export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, eventType: string) => + timelineSet.relations.getChildEventsForEvent(eventId, RelationType.Replace, eventType); + +const getLatestEdit = ( + targetEvent: MatrixEvent, + editEvents: MatrixEvent[] +): MatrixEvent | undefined => { + const eventByTargetSender = (rEvent: MatrixEvent) => + rEvent.getSender() === targetEvent.getSender(); + return editEvents.toSorted((m1, m2) => m2.getTs() - m1.getTs()).find(eventByTargetSender); +}; + +export const getEditedEvent = ( + mEventId: string, + mEvent: MatrixEvent, + timelineSet: EventTimelineSet +): MatrixEvent | undefined => { + const edits = getEventEdits(timelineSet, mEventId, mEvent.getType()); + return edits && getLatestEdit(mEvent, edits.getRelations()); +}; + +export const isEditEvent = (mEvent: MatrixEvent): boolean => { + const relType = mEvent.getRelation()?.rel_type; + if (relType === (RelationType.Replace as string)) return true; + if (mEvent.getContent()['m.new_content'] !== undefined) return true; + return false; +}; + +export const isReactionEvent = (mEvent: MatrixEvent): boolean => + mEvent.getType() === (EventType.Reaction as string); + +const FORWARDABLE_EVENT_TYPES = new Set([ + EventType.RoomMessage as string, + EventType.RoomMessageEncrypted as string, + EventType.Sticker as string, +]); + +export const canForwardEvent = (mEvent: MatrixEvent): boolean => { + if (mEvent.isRedacted()) return false; + if (isEditEvent(mEvent)) return false; + if (mEvent.getType() === (EventType.RoomRedaction as string)) return false; + if (isReactionEvent(mEvent)) return false; + if (typeof mEvent.getStateKey() === 'string') return false; + if (mEvent.isRedaction()) return false; + return FORWARDABLE_EVENT_TYPES.has(mEvent.getType()); +}; + +export const getReactionKey = (mEvent: MatrixEvent): string | undefined => { + const key = mEvent.getRelation()?.key; + if (typeof key === 'string' && key.length > 0) return key; + + const contentRelatesTo = mEvent.getContent()['m.relates_to'] as { key?: string } | undefined; + if (typeof contentRelatesTo?.key === 'string' && contentRelatesTo.key.length > 0) { + return contentRelatesTo.key; + } + + const originalRelatesTo = mEvent.getOriginalContent?.()?.['m.relates_to'] as + | { key?: string } + | undefined; + if (typeof originalRelatesTo?.key === 'string' && originalRelatesTo.key.length > 0) { + return originalRelatesTo.key; + } + + return undefined; +}; + +const readReactionShortcode = ( + content: Record | undefined +): string | undefined => { + if (!content) return undefined; + const shortcode = content.shortcode ?? content['com.beeper.reaction.shortcode']; + return typeof shortcode === 'string' && shortcode.length > 0 ? shortcode : undefined; +}; + +export const getReactionShortcode = (mEvent: MatrixEvent): string | undefined => + readReactionShortcode(mEvent.getContent()) ?? + readReactionShortcode(mEvent.getOriginalContent?.()); + +export const getReactionAnnotationTargetId = (reactionEvent: MatrixEvent): string | undefined => { + const eventId = reactionEvent.getRelation()?.event_id; + if (typeof eventId === 'string' && eventId.length > 0) return eventId; + + const contentRelatesTo = reactionEvent.getContent()['m.relates_to'] as + | { event_id?: string } + | undefined; + if (typeof contentRelatesTo?.event_id === 'string' && contentRelatesTo.event_id.length > 0) { + return contentRelatesTo.event_id; + } + + const originalRelatesTo = reactionEvent.getOriginalContent?.()?.['m.relates_to'] as + | { event_id?: string } + | undefined; + if (typeof originalRelatesTo?.event_id === 'string' && originalRelatesTo.event_id.length > 0) { + return originalRelatesTo.event_id; + } + + return undefined; +}; + +export const getRedactionReason = (mEvent: MatrixEvent): string | undefined => { + const reason = mEvent.getUnsigned()?.redacted_because?.content?.reason; + return typeof reason === 'string' && reason.length > 0 ? reason : undefined; +}; + +export const collectRelationReactionEvents = ( + linkedTimelines: EventTimeline[], + existingIds: ReadonlySet, + ignoredUsersSet: Set, + showReactions: boolean, + showReactionTombstones: boolean +): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => { + if (!showReactions && !showReactionTombstones) return []; + + const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = []; + const seen = new Set(existingIds); + + for (const timeline of linkedTimelines) { + const timelineSet = timeline.getTimelineSet(); + for (const parent of timeline.getEvents()) { + const parentId = parent.getId(); + if (!parentId) continue; + + const reactions = getEventReactions(timelineSet, parentId); + if (!reactions) continue; + + for (const reaction of reactions.getRelations()) { + const reactionId = reaction.getId(); + if (!reactionId || seen.has(reactionId)) continue; + seen.add(reactionId); + + const sender = reaction.getSender(); + if (sender && ignoredUsersSet.has(sender)) continue; + + const redacted = reaction.isRedacted(); + if (redacted && !showReactionTombstones) continue; + if (!redacted && !showReactions) continue; + + extras.push({ mEvent: reaction, timelineSet, parentId }); + } + } + } + + return extras; +}; + +export const collectRelationEditEvents = ( + linkedTimelines: EventTimeline[], + existingIds: ReadonlySet, + ignoredUsersSet: Set, + showEdits: boolean +): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => { + if (!showEdits) return []; + + const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = []; + const seen = new Set(existingIds); + + for (const timeline of linkedTimelines) { + const timelineSet = timeline.getTimelineSet(); + for (const parent of timeline.getEvents()) { + const parentId = parent.getId(); + if (!parentId || isEditEvent(parent)) continue; + + const edits = getEventEdits(timelineSet, parentId, parent.getType()); + if (!edits) continue; + + for (const editEvent of edits.getRelations()) { + const editId = editEvent.getId(); + if (!editId || seen.has(editId)) continue; + seen.add(editId); + + const sender = editEvent.getSender(); + if (sender && ignoredUsersSet.has(sender)) continue; + + extras.push({ mEvent: editEvent, timelineSet, parentId }); + } + } + } + + return extras; +}; + +export const isRedactableMessageType = (type: string): boolean => + type === (EventType.RoomMessage as string) || + type === (EventType.RoomMessageEncrypted as string) || + type === 'm.room.encrypted' || + type === (EventType.Sticker as string); + +export const getRedactionTargetId = (redactionEvent: MatrixEvent): string | undefined => { + const redacts = redactionEvent.event?.redacts; + if (typeof redacts === 'string') return redacts; + const associated = redactionEvent.getAssociatedId?.(); + return typeof associated === 'string' ? associated : undefined; +}; + +export const getRedactionTargetEvent = ( + timelineSet: EventTimelineSet, + redactionEvent: MatrixEvent +): MatrixEvent | undefined => { + const targetId = getRedactionTargetId(redactionEvent); + if (!targetId) return undefined; + return timelineSet.findEventById(targetId); +}; + +export const shouldShowRedactionTimelineEvent = ( + mEvent: MatrixEvent, + timelineSet: EventTimelineSet, + hiddenEventRedactionTimeline: boolean, + hiddenEventReactionRedactionTimeline: boolean +): boolean => { + if (!mEvent.isRedaction()) return false; + const target = getRedactionTargetEvent(timelineSet, mEvent); + if (target?.getType() === (EventType.Reaction as string)) { + return hiddenEventReactionRedactionTimeline; + } + return hiddenEventRedactionTimeline; +}; + +const readReplaceTargetId = ( + relatesTo: { rel_type?: string; event_id?: string } | undefined +): string | undefined => { + if (relatesTo?.rel_type !== (RelationType.Replace as string)) return undefined; + const eventId = relatesTo.event_id; + return typeof eventId === 'string' && eventId.length > 0 ? eventId : undefined; +}; + +export const getEditTargetId = (editEvent: MatrixEvent): string | undefined => { + const relationEventId = editEvent.getRelation()?.event_id; + if (typeof relationEventId === 'string' && relationEventId.length > 0) { + return relationEventId; + } + + const content = editEvent.getContent(); + const fromContent = readReplaceTargetId( + content['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined + ); + if (fromContent) return fromContent; + + const wireContent = editEvent.getWireContent?.() as Record | undefined; + const fromWire = readReplaceTargetId( + wireContent?.['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined + ); + if (fromWire) return fromWire; + + return readReplaceTargetId( + editEvent.getOriginalContent?.()?.['m.relates_to'] as + | { rel_type?: string; event_id?: string } + | undefined + ); +}; + +export const getEditChain = ( + timelineSet: EventTimelineSet, + eventId: string, + eventType: string, + room?: Room +): { original: MatrixEvent; edits: MatrixEvent[] } | undefined => { + let original = timelineSet.findEventById(eventId); + if (!original && room) { + original = room.findEventById(eventId) ?? undefined; + } + if (!original) return undefined; + + const editsRelation = getEventEdits(timelineSet, eventId, original.getType() ?? eventType); + const edits = editsRelation + ? [...editsRelation.getRelations()].toSorted((a, b) => a.getTs() - b.getTs()) + : []; + return { original, edits }; +}; + +const getEditChainEvents = ( + currentEditEvent: MatrixEvent, + chain: { original: MatrixEvent; edits: MatrixEvent[] } +): MatrixEvent[] => { + const currentId = currentEditEvent.getId(); + const edits = + currentId && !chain.edits.some((editEvent) => editEvent.getId() === currentId) + ? [...chain.edits, currentEditEvent].toSorted((a, b) => a.getTs() - b.getTs()) + : chain.edits; + return [chain.original, ...edits]; +}; + +export const getPreviousEditId = ( + currentEditEvent: MatrixEvent, + chain: { original: MatrixEvent; edits: MatrixEvent[] } +): string | undefined => { + const currentId = currentEditEvent.getId(); + if (!currentId) return undefined; + + const allEvents = getEditChainEvents(currentEditEvent, chain); + const idx = allEvents.findIndex((e) => e.getId() === currentId); + if (idx <= 0) return undefined; + return allEvents[idx - 1]?.getId(); +}; + +const getPreviousEditEvent = ( + currentEditEvent: MatrixEvent, + chain: { original: MatrixEvent; edits: MatrixEvent[] } +): MatrixEvent | undefined => { + const currentId = currentEditEvent.getId(); + if (!currentId) return undefined; + + const allEvents = getEditChainEvents(currentEditEvent, chain); + const idx = allEvents.findIndex((e) => e.getId() === currentId); + if (idx <= 0) return undefined; + return allEvents[idx - 1]; +}; + +const EDIT_DIFF_MSGTYPES = new Set([MsgType.Text, MsgType.Emote, MsgType.Notice]); + +const getMessageVersionBody = (mEvent: MatrixEvent): string | undefined => { + const content = mEvent.getContent(); + const wireContent = mEvent.getWireContent?.() as Record | undefined; + + let versionContent: Record | undefined; + if (isEditEvent(mEvent)) { + versionContent = + (content['m.new_content'] as Record | undefined) ?? + (wireContent?.['m.new_content'] as Record | undefined); + } else { + versionContent = + (mEvent.getOriginalContent?.() as Record | undefined) ?? + (content as Record); + } + + const fallbackContent = + (!versionContent || typeof versionContent.body !== 'string') && mEvent.getOriginalContent?.() + ? (mEvent.getOriginalContent?.() as Record) + : undefined; + const resolvedContent = + versionContent && typeof versionContent === 'object' ? versionContent : fallbackContent; + if (!resolvedContent || typeof resolvedContent !== 'object') return undefined; + + const msgtype = resolvedContent.msgtype; + if (typeof msgtype === 'string' && !EDIT_DIFF_MSGTYPES.has(msgtype)) { + return undefined; + } + + const body = resolvedContent.body; + return typeof body === 'string' ? trimReplyFromBodyLocal(body) : undefined; +}; + +export const getEditDiffBodies = ( + editEvent: MatrixEvent, + timelineSet: EventTimelineSet, + room?: Room +): { oldBody?: string; newBody?: string } => { + const newBody = getMessageVersionBody(editEvent); + const editTargetId = getEditTargetId(editEvent); + if (!editTargetId) { + return { newBody }; + } + + const chain = getEditChain(timelineSet, editTargetId, editEvent.getType(), room); + let previousEvent = chain ? getPreviousEditEvent(editEvent, chain) : undefined; + if (!previousEvent) { + previousEvent = + chain?.original ?? + timelineSet.findEventById(editTargetId) ?? + room?.findEventById(editTargetId); + } + + const oldBody = + previousEvent && previousEvent.getId() !== editEvent.getId() + ? getMessageVersionBody(previousEvent) + : undefined; + + return { oldBody, newBody }; +}; + +export const canEditEvent = (mx: MatrixClient, mEvent: MatrixEvent) => { + const content = mEvent.getContent(); + const relationType = content['m.relates_to']?.rel_type; + return ( + mEvent.getSender() === mx.getUserId() && + mEvent.getType() === (EventType.RoomMessage as string) && + (!relationType || relationType === (RelationType.Thread as string)) && + (content.msgtype === MsgType.Text || + content.msgtype === MsgType.Emote || + content.msgtype === MsgType.Notice || + content.msgtype === MsgType.Image || + content.msgtype === MsgType.Video || + content.msgtype === MsgType.Audio || + content.msgtype === MsgType.File) + ); +}; + +export const reactionOrEditEvent = (mEvent: MatrixEvent): boolean => { + const relType = mEvent.getRelation()?.rel_type; + if ( + relType === (RelationType.Annotation as string) || + relType === (RelationType.Replace as string) + ) + return true; + + // Sliding sync proxies may omit m.relates_to on the initial delivery of timeline + // events. Detect edit events by the presence of m.new_content in the event + // content even when the relation metadata is absent, so they are filtered from + // the rendered timeline rather than falling through as unsupported messages. + if (mEvent.getContent()['m.new_content'] !== undefined) return true; + + return false; +}; + +export const isThreadRelationEvent = (mEvent: MatrixEvent, threadRootId?: string): boolean => { + const relation = + mEvent.getRelation?.() ?? + ( + mEvent.getWireContent?.() as { + 'm.relates_to'?: { rel_type?: unknown; event_id?: unknown }; + } + )?.['m.relates_to'] ?? + ( + mEvent.getContent?.() as { + 'm.relates_to'?: { rel_type?: unknown; event_id?: unknown }; + } + )?.['m.relates_to']; + + return ( + relation?.rel_type === (RelationType.Thread as string) && + (threadRootId === undefined || relation.event_id === threadRootId) + ); +}; + +export const hasThreadRootAggregation = (mEvent: MatrixEvent): boolean => + (mEvent.getServerAggregatedRelation?.(RelationType.Thread as string) + ?.count ?? 0) > 0; + +/** + * Resolve the list of reply events to show for a thread. + * + * Prefers events from the SDK Thread object (authoritative, full history) but + * falls back to scanning the main room timeline when the Thread object was + * created without `initialEvents` (as happens with classic sync). In that + * case `thread.events` contains only the root event, so filtering it yields an + * empty array — we must fall back rather than showing nothing. + */ +export const getThreadReplyEvents = (room: Room, threadRootId: string): MatrixEvent[] => { + const isReply = (ev: MatrixEvent) => + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId); + + const thread = room.getThread(threadRootId); + const fromThread = (thread?.events ?? []).filter(isReply); + if (fromThread.length > 0) return fromThread; + + return room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter(isReply); +}; + +/** + * Timeline rows skip reactions, edits, and other relation-only events. When jumping + * to a reply target, unwrap to the event that is actually rendered (root of an + * edit chain, message for a reaction annotation, etc.). + */ +export const unwrapRelationJumpTarget = (room: Room, eventId: string, maxHops = 24): string => { + let current = eventId; + for (let hop = 0; hop < maxHops; hop += 1) { + const ev = room.findEventById(current); + if (!ev) return current; + if (!reactionOrEditEvent(ev)) return current; + const related = ev.getRelation()?.event_id; + if (typeof related !== 'string' || related === current) return current; + current = related; + } + return current; +}; + +const findRelationChildEvent = ( + timelineSet: EventTimelineSet, + eventId: string +): MatrixEvent | undefined => { + for (const timeline of timelineSet.getTimelines()) { + for (const parent of timeline.getEvents()) { + const parentId = parent.getId(); + if (!parentId) continue; + + const reactionRelations = getEventReactions(timelineSet, parentId); + if (reactionRelations) { + const reaction = reactionRelations + .getRelations() + .find((candidate) => candidate.getId() === eventId); + if (reaction) return reaction; + } + + const editRelations = getEventEdits(timelineSet, parentId, parent.getType()); + if (editRelations) { + const edit = editRelations + .getRelations() + .find((candidate) => candidate.getId() === eventId); + if (edit) return edit; + } + } + } + return undefined; +}; + +export const findRoomEventById = ( + room: Room, + eventId: string, + timelineSet?: EventTimelineSet +): MatrixEvent | undefined => { + const set = timelineSet ?? room.getUnfilteredTimelineSet(); + return ( + set.findEventById(eventId) ?? + room.findEventById(eventId) ?? + findRelationChildEvent(set, eventId) + ); +}; + +export type ResolvedReplyDraftTarget = { + eventId: string; + replyEvt: MatrixEvent; +}; + +export const extractReplyDraftBody = ( + replyEvt: MatrixEvent, + timelineSet: EventTimelineSet +): { body: string; formattedBody: string } => { + const replyId = replyEvt.getId(); + const editedReply = + replyId !== undefined && !isEditEvent(replyEvt) + ? getEditedEvent(replyId, replyEvt, timelineSet) + : undefined; + const editedNewContent = editedReply?.getContent()['m.new_content']; + const content = (editedNewContent ?? replyEvt.getContent()) as Record; + const { body, formatted_body: formattedBody } = content; + const msc1767body = content['m.text']; + + const resolvedBody = + (typeof body === 'string' ? body : undefined) ?? + (typeof msc1767body === 'string' + ? msc1767body + : (msc1767body as { body?: string } | undefined)?.body) ?? + getMessageVersionBody(replyEvt) ?? + ''; + + return { + body: resolvedBody, + formattedBody: typeof formattedBody === 'string' ? formattedBody : '', + }; +}; + +export const resolveReplyDraftTarget = ( + room: Room, + clickedEventId: string, + timelineSet?: EventTimelineSet +): ResolvedReplyDraftTarget | undefined => { + const set = timelineSet ?? room.getUnfilteredTimelineSet(); + const replyEvt = findRoomEventById(room, clickedEventId, set); + if (!replyEvt) return undefined; + + const eventId = replyEvt.getId(); + if (!eventId) return undefined; + + return { eventId, replyEvt }; +}; + +export const getMentionContent = (userIds: string[], room: boolean): IMentions => { + const mMentions: IMentions = {}; + if (userIds.length > 0) { + mMentions.user_ids = userIds; + } + if (room) { + mMentions.room = true; + } + + return mMentions; +}; + +export const getCommonRooms = ( + mx: MatrixClient, + rooms: string[], + otherUserId: string +): string[] => { + const commonRooms: string[] = []; + + rooms.forEach((roomId) => { + const room = mx.getRoom(roomId); + if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return; + + const common = room.hasMembershipState(otherUserId, KnownMembership.Join); + if (common) { + commonRooms.push(roomId); + } + }); + + return commonRooms; +}; + +export const bannedInRooms = (mx: MatrixClient, rooms: string[], otherUserId: string): boolean => + rooms.some((roomId) => { + const room = mx.getRoom(roomId); + if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return false; + + return room.hasMembershipState(otherUserId, KnownMembership.Ban); + }); diff --git a/src/app/utils/room/unread.ts b/src/app/utils/room/unread.ts new file mode 100644 index 000000000..6d04eddaa --- /dev/null +++ b/src/app/utils/room/unread.ts @@ -0,0 +1,363 @@ +import type { IPushRule, IPushRules, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { EventType, NotificationCountType, PushRuleActionName } from '$types/matrix-sdk'; + +import type { UnreadInfo } from '$types/matrix/room'; +import { NotificationType } from '$types/matrix/room'; + +export const getMDirects = (mDirectEvent: MatrixEvent): Set => { + const roomIds = new Set(); + const userIdToDirects = mDirectEvent?.getContent(); + + if (userIdToDirects === undefined) return roomIds; + + Object.keys(userIdToDirects).forEach((userId) => { + const directs = userIdToDirects[userId]; + if (Array.isArray(directs)) { + directs.forEach((id) => { + if (typeof id === 'string') roomIds.add(id); + }); + } + }); + + return roomIds; +}; + +export const isDirectInvite = (room: Room | null, myUserId: string | null): boolean => { + if (!room || !myUserId) return false; + const me = room.getMember(myUserId); + const memberEvent = me?.events?.member; + const content = memberEvent?.getContent(); + return content?.is_direct === true; +}; + +/** + * Detects if a room is a direct message room using multiple signals for robustness: + * 1. Primary: checks if room is in mDirects set (from m.direct account data) + * 2. Fallback: checks if room has exactly 2 joined members (classic DM heuristic) + * + * The fallback handles cases where m.direct account data is incomplete or outdated. + */ +export const isDMRoom = (room: Room, mDirects?: Set): boolean => { + // Primary signal: check m.direct account data + if (mDirects?.has(room.roomId)) { + return true; + } + + // Fallback: use member count heuristic for untagged DMs + // Only applies to non-space rooms with exactly 2 members (you + them) + if (!room.isSpaceRoom() && room.getJoinedMemberCount() === 2) { + return true; + } + + return false; +}; + +const hasNotifyPushAction = (actions: IPushRule['actions']): boolean => + actions.some((a) => typeof a === 'string' && a === PushRuleActionName.Notify); + +const findRoomMuteOverrideRule = ( + overrideRules: IPushRule[] | undefined, + roomId: string +): IPushRule | undefined => + overrideRules?.find( + (rule) => + rule.rule_id === roomId && rule.rule_id.startsWith('!') && !hasNotifyPushAction(rule.actions) + ); + +export const getNotificationType = (mx: MatrixClient, roomId: string): NotificationType => { + const overrideRules = mx.getAccountData(EventType.PushRules)?.getContent() + ?.global?.override; + if (findRoomMuteOverrideRule(overrideRules, roomId)) { + return NotificationType.Mute; + } + + let roomPushRule: IPushRule | undefined; + try { + roomPushRule = mx.getRoomPushRule('global', roomId); + } catch { + roomPushRule = undefined; + } + + if (!roomPushRule) { + return NotificationType.Default; + } + + if ((roomPushRule.actions[0] as string) === 'notify') return NotificationType.AllMessages; + return NotificationType.MentionsAndKeywords; +}; + +const NOTIFICATION_EVENT_TYPES = new Set([ + 'm.room.create', + 'm.room.message', + 'm.room.encrypted', + 'm.room.member', + 'm.sticker', + 'm.reaction', +]); +export const isNotificationEvent = (mEvent: MatrixEvent, room?: Room, userId?: string) => { + const eType = mEvent.getType(); + if (!NOTIFICATION_EVENT_TYPES.has(eType)) { + return false; + } + if (eType === 'm.room.member') return false; + + if (mEvent.isRedacted()) return false; + const relation = mEvent.getRelation(); + const relationType = relation?.rel_type; + + // Filter out edits - they shouldn't count as new notifications + if (relationType === 'm.replace') return false; + + // For reactions: only count them if they're reactions to the current user's messages + if (relationType === 'm.annotation') { + if (!room || !userId || !relation) { + // If we don't have room/userId/relation context, filter out all reactions (safe default) + return false; + } + // Get the event being reacted to + const reactedToEventId = relation.event_id; + if (!reactedToEventId) return false; + + const reactedToEvent = room.findEventById(reactedToEventId); + // Only count as notification if the reacted-to message was sent by current user + return reactedToEvent?.getSender() === userId; + } + + return true; +}; + +export const roomHaveNotification = (room: Room): boolean => { + const total = room.getUnreadNotificationCount(NotificationCountType.Total); + const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + + return total > 0 || highlight > 0; +}; + +export const roomHaveUnread = (mx: MatrixClient, room: Room) => { + if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return false; + const userId = mx.getUserId(); + if (!userId) return false; + const readUpToId = room.getEventReadUpTo(userId); + const liveEvents = room.getLiveTimeline().getEvents(); + + if (!readUpToId) { + return false; + } + + const latestEvent = liveEvents[liveEvents.length - 1]; + + if (latestEvent?.getSender() === userId) { + return false; + } + + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const event = liveEvents[i]; + if (!event) return false; + if (event.getId() === readUpToId) { + return false; + } + if (isNotificationEvent(event, room, userId)) { + return true; + } + } + return false; +}; + +type UnreadInfoOptions = { + applyFixup?: boolean; + mDirects?: Set; +}; + +const unreadInfoFixupInProgress = new WeakSet(); + +export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadInfo => { + if (getNotificationType(room.client, room.roomId) === NotificationType.Mute) { + return { roomId: room.roomId, highlight: 0, total: 0 }; + } + + const userId = room.client.getUserId(); + if (userId && options?.applyFixup && !unreadInfoFixupInProgress.has(room)) { + unreadInfoFixupInProgress.add(room); + try { + room.fixupNotifications(userId); + } finally { + unreadInfoFixupInProgress.delete(room); + } + } + + let total = room.getUnreadNotificationCount(NotificationCountType.Total); + const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + let hasTimelineUnread: boolean | undefined; + const roomHasTimelineUnread = () => { + hasTimelineUnread ??= roomHaveUnread(room.client, room); + return hasTimelineUnread; + }; + + // Check if this is a DM and what notification type it has (using multiple signals for robustness) + const isDM = isDMRoom(room, options?.mDirects); + const notificationType = isDM ? getNotificationType(room.client, room.roomId) : undefined; + const shouldForceDMHighlight = + isDM && + notificationType !== NotificationType.Mute && + notificationType !== NotificationType.MentionsAndKeywords; + + // If our latest main-timeline notification event is confirmed read, clamp its stale count. + // Only apply to the room (non-thread) portion so thread reply counts are preserved. + // Guard: only clamp when the room has NO receipt-confirmed unread events; if roomHaveUnread + // is true then there genuinely are unread messages and the SDK count is not fully stale. + if (userId && total > 0 && highlight === 0 && !roomHasTimelineUnread()) { + const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total); + if (roomTotal > 0) { + const liveEvents = room.getLiveTimeline().getEvents(); + // Exclude the user's own messages: own sent events are always "read" (hasUserReadEvent + // returns true for them), which would cause the clamp to fire incorrectly. + const latestNotification = [...liveEvents] + .toReversed() + .find( + (event) => + !event.isSending() && + event.getSender() !== userId && + isNotificationEvent(event, room, userId) + ); + const latestNotificationId = latestNotification?.getId(); + if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { + // Subtract only the stale main-timeline count; thread totals remain intact. + total -= roomTotal; + } + } + } + + // Fallback: SDK counters are stale/zero but there are receipt-confirmed unread + // messages. Walk the live timeline to compute real counts so the badge number + // and highlight colour reflect actual state rather than a hard-coded stub. + if (total === 0 && highlight === 0 && userId && roomHasTimelineUnread()) { + const readUpToId = room.getEventReadUpTo(userId); + const liveEvents = room.getLiveTimeline().getEvents(); + let fallbackTotal = 0; + let fallbackHighlight = 0; + const pushProcessor = room.client.pushProcessor; + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const event = liveEvents[i]; + if (!event) break; + if (event.getId() === readUpToId) break; + if (isNotificationEvent(event, room, userId) && event.getSender() !== userId) { + fallbackTotal += 1; + const pushActions = pushProcessor.actionsForEvent(event); + if (pushActions?.tweaks?.highlight) fallbackHighlight += 1; + } + } + if (fallbackTotal > 0) { + return { + roomId: room.roomId, + highlight: fallbackHighlight, + total: fallbackTotal, + }; + } + } + + // Sliding sync limitation: unvisited rooms don't have read receipt data, but may have + // timeline activity. Check for notification events from others in the timeline to show a + // badge even when SDK counts are 0 (or unreliable without receipts). + if (userId) { + const readUpToId = room.getEventReadUpTo(userId); + + // If we have no read receipt, SDK counts may be unreliable. Always check timeline. + if (!readUpToId) { + const liveEvents = room.getLiveTimeline().getEvents(); + const fullyReadEventId = room + .getAccountData(EventType.FullyRead) + ?.getContent<{ event_id?: string }>()?.event_id; + let hasActivity = false; + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const event = liveEvents[i]; + if (!event || event.getId() === fullyReadEventId) break; + if (event.getSender() !== userId && isNotificationEvent(event, room, userId)) { + hasActivity = true; + break; + } + } + + if (hasActivity) { + // If SDK already has counts, use those. Otherwise show dot badge (count=1). + if (total === 0 && highlight === 0) { + return { roomId: room.roomId, highlight: 0, total: 1 }; + } + // SDK has counts but no receipt - trust the counts and show them + return { roomId: room.roomId, highlight, total }; + } + } + } + + // For DMs with Default or AllMessages notification type: if there are unread messages, + // ensure we show a notification badge (treat as highlight for badge color purposes). + // This handles cases where push rules don't properly match (e.g., classic sync with + // member_count condition failures, or sliding sync with limited required_state). + if (shouldForceDMHighlight && total > 0 && highlight === 0) { + return { + roomId: room.roomId, + highlight: total, // Treat all unread messages as highlights for DMs + total, + }; + } + + return { + roomId: room.roomId, + highlight, + total: Math.max(total, highlight), + }; +}; + +export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): UnreadInfo[] => { + const unreadInfos = mx.getRooms().reduce((unread, room) => { + if (room.isSpaceRoom()) return unread; + if (room.getMyMembership() !== 'join') return unread; + if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread; + + // Always call getUnreadInfo - it has fallback logic for sliding sync rooms without receipts + const unreadInfo = getUnreadInfo(room, options); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + unread.push(unreadInfo); + } + + return unread; + }, []); + + return unreadInfos; +}; + +export const getUnreadInfosForRooms = ( + mx: MatrixClient, + roomIds: Iterable, + options?: UnreadInfoOptions +): { unread: UnreadInfo[]; deleted: string[] } => { + const unread: UnreadInfo[] = []; + const deleted: string[] = []; + + for (const roomId of roomIds) { + const room = mx.getRoom(roomId); + if (!room) { + deleted.push(roomId); + continue; + } + // Space unread is derived from children in the atom reducer; skip like + // getUnreadInfos rather than deleting. + if (room.isSpaceRoom()) continue; + if (room.getMyMembership() !== 'join') { + deleted.push(roomId); + continue; + } + if (getNotificationType(mx, room.roomId) === NotificationType.Mute) { + deleted.push(roomId); + continue; + } + + const unreadInfo = getUnreadInfo(room, options); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + unread.push(unreadInfo); + } else { + deleted.push(roomId); + } + } + + return { unread, deleted }; +}; diff --git a/src/app/utils/roomVisibility.ts b/src/app/utils/roomVisibility.ts index 2f88f092a..837b5d6b5 100644 --- a/src/app/utils/roomVisibility.ts +++ b/src/app/utils/roomVisibility.ts @@ -1,6 +1,6 @@ import { EventType, JoinRule } from 'matrix-js-sdk'; import type { MatrixClient, Room } from 'matrix-js-sdk'; -import { getStateEvents } from './room'; +import { getStateEvents } from './room/hierarchy'; /** * simple check to see if a room can be considered private diff --git a/src/app/utils/settingsSync.ts b/src/app/utils/settingsSync.ts index cae2db294..6c37c52c0 100644 --- a/src/app/utils/settingsSync.ts +++ b/src/app/utils/settingsSync.ts @@ -1,6 +1,7 @@ import { sanitizeThemeRemoteTweakFavorites, type Settings } from '$state/settings'; import { isLocalImportTweakUrl } from '../theme/localImportUrls'; import { sanitizeShortcutOverrides } from '../keyboard/shortcuts'; +import { downloadJsonFile } from './common'; /** * Keys excluded from cross-device sync. @@ -152,14 +153,10 @@ export const deserializeFromSync = (data: unknown, currentSettings: Settings): S /** Trigger a browser download of the current settings as a JSON file. */ export const exportSettingsAsJson = (settings: Settings): void => { - const payload = JSON.stringify({ v: SETTINGS_SYNC_VERSION, settings }, null, 2); - const blob = new Blob([payload], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `sable-settings-${Date.now()}.json`; - a.click(); - URL.revokeObjectURL(url); + downloadJsonFile( + JSON.stringify({ v: SETTINGS_SYNC_VERSION, settings }, null, 2), + 'sable-settings' + ); }; /** diff --git a/src/app/utils/timeline.ts b/src/app/utils/timeline.ts index cfc9acce9..89bdd6ff0 100644 --- a/src/app/utils/timeline.ts +++ b/src/app/utils/timeline.ts @@ -1,6 +1,6 @@ import type { EventTimeline, MatrixEvent, Room } from '$types/matrix-sdk'; import { Direction } from '$types/matrix-sdk'; -import { roomHaveNotification, roomHaveUnread } from '$utils/room'; +import { roomHaveNotification, roomHaveUnread } from '$utils/room/unread'; export const PAGINATION_LIMIT = 60; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index ff3f1223d..0912015a1 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -31,8 +31,6 @@ const debugLog = createDebugLogger('slidingSync'); const LIST_JOINED = 'joined'; const LIST_INVITES = 'invites'; const LIST_UPDATES = 'updates'; -const LIST_ROOM_SEARCH = 'room_search'; -const LIST_SPACE = 'space'; const LIST_TIMELINE_LIMIT = 1; const LIST_PAGE_SIZE = 30; const STEADY_STATE_DETAILED_ROOMS = 3; @@ -962,29 +960,6 @@ export class SlidingSyncManager { return this.slidingSync.getListParams(listKey) ?? list; } - public setRoomNameSearch(query: string | null): void { - if (this.disposed) return; - const trimmed = query?.trim() ?? ''; - const filters: MSC3575List['filters'] = trimmed ? { room_name_like: trimmed } : {}; - this.ensureListRegistered(LIST_ROOM_SEARCH, { - filters, - ranges: [[0, 19]], - sort: LIST_SORT_ORDER, - }); - } - - public setSpaceScope(spaceId: string | null): void { - if (this.disposed) return; - const filters: MSC3575List['filters'] = spaceId - ? { is_invite: false, spaces: [spaceId] } - : { is_invite: false }; - this.ensureListRegistered(LIST_SPACE, { - filters, - ranges: spaceId ? [[0, LIST_PAGE_SIZE - 1]] : [[0, 0]], - sort: LIST_SORT_ORDER, - }); - } - public isRoomActive(roomId: string): boolean { return this.activeRoomSubscriptions.has(roomId); } diff --git a/src/types/matrix/accountData.ts b/src/types/matrix/accountData.ts index 415249757..5c855123e 100644 --- a/src/types/matrix/accountData.ts +++ b/src/types/matrix/accountData.ts @@ -19,8 +19,6 @@ export const CustomAccountDataEvent = { export type CustomAccountDataEvent = (typeof CustomAccountDataEvent)[keyof typeof CustomAccountDataEvent]; -export type MDirectContent = Record; - export type AddedServersContent = { servers: string[]; }; diff --git a/src/types/matrix/common.ts b/src/types/matrix/common.ts index 36f531258..acef5ed08 100644 --- a/src/types/matrix/common.ts +++ b/src/types/matrix/common.ts @@ -136,13 +136,6 @@ export type IFileContent = { file?: IEncryptedFile; }; -export type ILocationContent = { - msgtype: MsgType.Location; - body?: string; - geo_uri?: string; - info?: IThumbnailContent; -}; - export type IGalleryImageItem = Omit & { itemtype: MsgType.Image }; export type IGalleryVideoItem = Omit & { itemtype: MsgType.Video }; export type IGalleryAudioItem = Omit & { itemtype: MsgType.Audio }; diff --git a/src/types/matrix/room.ts b/src/types/matrix/room.ts index 79ab4cb26..dca3462a3 100644 --- a/src/types/matrix/room.ts +++ b/src/types/matrix/room.ts @@ -62,11 +62,6 @@ export type UnreadInfo = { highlight: number; }; -export type MuteChanges = { - added: string[]; - removed: string[]; -}; - export type MemberPowerTagIcon = { key?: string; info?: IImageInfo; diff --git a/tests/e2e/touch.spec.ts b/tests/e2e/touch.spec.ts new file mode 100644 index 000000000..1e03f7032 --- /dev/null +++ b/tests/e2e/touch.spec.ts @@ -0,0 +1,182 @@ +import { test, expect } from './fixtures/test'; + +test.describe('touch interactions', () => { + test('long-press opens a bottom-sheet context menu', async ({ app, page }) => { + // Open a room so there are messages to long-press + await app.room('General').click(); + await expect(page.getByText('Welcome to the test room.')).toBeVisible(); + + // Get a message element to long-press on + const message = page.getByText('Welcome to the test room.').first(); + const box = await message.boundingBox(); + if (!box) throw new Error('Message element not visible'); + + // Simulate a long-press: touch start, hold >500ms (the useMenuAnchor threshold) + const cx = box.x + box.width / 2; + const cy = box.y + box.height / 2; + + await page.touchscreen.tap(cx, cy); + // tap() is a brief tap, not a long-press. Use raw touch events for hold. + // Clear any state from the tap first. + await page.evaluate(() => { + document.elementFromPoint(0, 0); // no-op to settle + }); + + // Dispatch a real long-press via touch events + await page.evaluate( + ({ x, y }) => { + const target = document.elementFromPoint(x, y); + if (!target) return; + const touchStart = new TouchEvent('touchstart', { + bubbles: true, + cancelable: true, + touches: [new Touch({ identifier: 0, target, clientX: x, clientY: y })], + }); + target.dispatchEvent(touchStart); + }, + { x: cx, y: cy } + ); + + // Wait 600ms for the long-press timer (>500ms threshold) + await page.waitForTimeout(600); + + // Dispatch touchend to complete the long-press + await page.evaluate( + ({ x, y }) => { + const target = document.elementFromPoint(x, y); + if (!target) return; + const touchEnd = new TouchEvent('touchend', { + bubbles: true, + cancelable: true, + changedTouches: [new Touch({ identifier: 0, target, clientX: x, clientY: y })], + }); + target.dispatchEvent(touchEnd); + }, + { x: cx, y: cy } + ); + + // The context menu should now be open — on mobile this is a bottom sheet + // rendered inside the MessageMobileOptionsContainer (z-index 1005, fixed at bottom) + const sheet = page.locator('[data-gestures="ignore"]').first(); + await expect(sheet).toBeVisible({ timeout: 5_000 }); + }); + + // Never passed. The sheet does not dismiss from a downward swipe under real + // CDP touch input either, so this looks like a gap in MobileSwipeDownModal + // rather than a harness problem. Investigate before re-enabling. + test.fixme('swipe-down dismisses a bottom sheet', async ({ app, page }) => { + // Open a room to get messages with context menus + await app.room('General').click(); + await expect(page.getByText('Welcome to the test room.')).toBeVisible(); + + // Long-press a message to open the context menu bottom sheet + const message = page.getByText('Welcome to the test room.').first(); + const box = await message.boundingBox(); + if (!box) throw new Error('Message element not visible'); + + const cx = box.x + box.width / 2; + const cy = box.y + box.height / 2; + + await page.evaluate( + ({ x, y }) => { + const target = document.elementFromPoint(x, y); + if (!target) return; + const touchStart = new TouchEvent('touchstart', { + bubbles: true, + cancelable: true, + touches: [new Touch({ identifier: 0, target, clientX: x, clientY: y })], + }); + target.dispatchEvent(touchStart); + }, + { x: cx, y: cy } + ); + await page.waitForTimeout(600); + await page.evaluate( + ({ x, y }) => { + const target = document.elementFromPoint(x, y); + if (!target) return; + const touchEnd = new TouchEvent('touchend', { + bubbles: true, + cancelable: true, + changedTouches: [new Touch({ identifier: 0, target, clientX: x, clientY: y })], + }); + target.dispatchEvent(touchEnd); + }, + { x: cx, y: cy } + ); + + // Verify the sheet is open + const sheetContainer = page.locator('[data-gestures="ignore"]').first(); + await expect(sheetContainer).toBeVisible({ timeout: 5_000 }); + + // Derive the touch point from the sheet's real box: it is fixed to the bottom, + // so a hardcoded y lands on the backdrop instead. + const sheetBox = await page.locator('[data-gestures="ignore"] > *').first().boundingBox(); + if (!sheetBox) throw new Error('Sheet has no box'); + const dragHandleY = Math.round(sheetBox.y + sheetBox.height / 3); + const dragHandleX = Math.round(sheetBox.x + sheetBox.width / 2); + + // Real touch input via CDP: synthetic TouchEvents are retargeted by + // elementFromPoint as the finger travels, so they miss the sheet's handlers. + const cdp = await page.context().newCDPSession(page); + const point = [{ x: dragHandleX, y: dragHandleY }]; + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: point }); + for (let i = 1; i <= 5; i += 1) { + // eslint-disable-next-line no-await-in-loop + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchMove', + touchPoints: [{ x: dragHandleX, y: dragHandleY + (150 * i) / 5 }], + }); + } + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + + // The sheet should close — the container disappears + await expect(sheetContainer).toBeHidden({ timeout: 3_000 }); + }); + + // Never passed: the Save click times out on a touch viewport, so the long + // status is never persisted and the overflow assertion never runs. + test.fixme('settings page has no horizontal overflow', async ({ app, page }) => { + // Confirm the client is loaded (app.open() has already waited for room list) + await expect(app.room('General')).toBeVisible(); + + // Navigate to the settings account page where the StatusEditor is + await page.goto('/settings/account'); + + // The status input is the readiness signal; on a touch viewport the word + // "Settings" only appears in the collapsed nav. + + // The StatusEditor is present in the Account section with input name="statusInput" + const statusInput = page.locator('input[name="statusInput"]').first(); + await expect(statusInput).toBeVisible({ timeout: 10_000 }); + + // Fill a very long status to test horizontal overflow (issue #1349) + const longStatus = + 'This is a very long status message designed to test horizontal overflow behavior on mobile viewports. '.repeat( + 10 + ); + await statusInput.fill(longStatus); + + // Save the status + const saveButton = page.getByRole('button', { name: 'Save' }).first(); + await saveButton.click(); + + // Wait for save to complete (the button should no longer show a spinner) + await page.waitForTimeout(2_000); + + // Assert no horizontal overflow anywhere on the page + const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth); + const clientWidth = await page.evaluate(() => document.documentElement.clientWidth); + expect(scrollWidth).toBeLessThanOrEqual(clientWidth); + + // Also check on the main settings index page + await page.goto('/settings/general'); + // The section renders its own heading; on a touch viewport the word + // "Settings" only appears in the collapsed nav. + await expect(page.getByText('General').first()).toBeVisible({ timeout: 10_000 }); + + const scrollWidth2 = await page.evaluate(() => document.documentElement.scrollWidth); + const clientWidth2 = await page.evaluate(() => document.documentElement.clientWidth); + expect(scrollWidth2).toBeLessThanOrEqual(clientWidth2); + }); +}); From 228494c1f96c86a5a278f458409053c6d3fb12f8 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 26 Jul 2026 10:17:05 +0200 Subject: [PATCH 2/2] refactor: own the Button component with a built-in loading state --- src/app/components/AccountDataEditor.tsx | 7 +- src/app/components/AsyncButton.tsx | 41 ----- src/app/components/DeviceVerification.tsx | 12 +- .../components/DeviceVerificationSetup.tsx | 8 +- src/app/components/LogoutDialog.tsx | 8 +- src/app/components/SecretStorage.tsx | 10 +- src/app/components/button/Button.css.ts | 149 ++++++++++++++++++ src/app/components/button/Button.tsx | 63 ++++++++ src/app/components/button/index.ts | 1 + .../DirectInvitePrompt.tsx | 8 +- .../invite-user-prompt/InviteUserPrompt.tsx | 6 +- .../knock-room-prompt/KnockRoomPrompt.tsx | 6 +- .../leave-space-prompt/LeaveSpacePrompt.tsx | 10 +- .../user-profile/UserModeration.tsx | 12 +- .../developer-tools/SendRoomEvent.tsx | 6 +- .../developer-tools/StateEventEditor.tsx | 7 +- .../emojis-stickers/RoomPacks.tsx | 11 +- .../general/RoomEncryption.tsx | 6 +- .../common-settings/general/RoomProfile.tsx | 8 +- .../common-settings/general/RoomUpgrade.tsx | 8 +- .../permissions/PermissionGroups.tsx | 8 +- src/app/features/create-chat/CreateChat.tsx | 6 +- src/app/features/create-room/CreateRoom.tsx | 6 +- src/app/features/create-space/CreateSpace.tsx | 6 +- src/app/features/room/RoomTombstone.tsx | 8 +- .../features/settings/devices/LocalBackup.tsx | 12 +- .../DeregisterPushNotifications.tsx | 8 +- src/app/pages/auth/login/OidcLogin.tsx | 8 +- src/app/pages/client/SpecVersions.tsx | 8 +- src/app/pages/client/inbox/Invites.tsx | 24 +-- src/app/pages/client/space/Space.tsx | 7 +- 31 files changed, 328 insertions(+), 160 deletions(-) delete mode 100644 src/app/components/AsyncButton.tsx create mode 100644 src/app/components/button/Button.css.ts create mode 100644 src/app/components/button/Button.tsx create mode 100644 src/app/components/button/index.ts diff --git a/src/app/components/AccountDataEditor.tsx b/src/app/components/AccountDataEditor.tsx index 02c322632..fb2bf6fad 100644 --- a/src/app/components/AccountDataEditor.tsx +++ b/src/app/components/AccountDataEditor.tsx @@ -5,7 +5,6 @@ import { Text, IconButton, Input, - Button, TextArea as TextAreaComponent, color, Chip, @@ -17,13 +16,13 @@ import type { MatrixError } from '$types/matrix-sdk'; import { Cursor } from '$plugins/text-area'; import { syntaxErrorPosition } from '$utils/dom'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { useAlive } from '$hooks/useAlive'; import { useTextAreaCodeEditor } from '$hooks/useTextAreaCodeEditor'; import { Page, PageHeader } from './page'; import { SequenceCard } from './sequence-card'; import { TextViewerContent } from './text-viewer'; +import { Button } from '$components/button'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -135,7 +134,7 @@ function AccountDataEdit({ required /> - Save - + - ); -} diff --git a/src/app/components/DeviceVerification.tsx b/src/app/components/DeviceVerification.tsx index 852e1397f..c14da9c3b 100644 --- a/src/app/components/DeviceVerification.tsx +++ b/src/app/components/DeviceVerification.tsx @@ -2,8 +2,7 @@ import type { ShowSasCallbacks, VerificationRequest, Verifier } from '$types/mat import { VerificationPhase, VerificationMethod } from '$types/matrix-sdk'; import type { CSSProperties } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; -import { Box, Button, config, Dialog, Header, IconButton, Spinner, Text } from 'folds'; -import { AsyncButton } from '$components/AsyncButton'; +import { Box, config, Dialog, Header, IconButton, Spinner, Text } from 'folds'; import { composerIcon, X } from '$components/icons/phosphor'; import * as Sentry from '@sentry/react'; import { @@ -15,6 +14,7 @@ import { import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { ContainerColor } from '$styles/ContainerColor.css'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; +import { Button } from '$components/button'; const DialogHeaderStyles: CSSProperties = { padding: `0 ${config.space.S200} 0 ${config.space.S400}`, @@ -64,7 +64,7 @@ function VerificationAccept({ onAccept }: VerificationAcceptProps) { return ( Click accept to start the verification process. - Accept - + ); } @@ -138,7 +138,7 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) { ))} - They Match - + {nextAuthData !== null && uiaAction && ( void; @@ -82,7 +82,7 @@ export const LogoutDialog = forwardRef( You’re about to log out. Are you sure? - ( spinnerSize="200" > Logout - + diff --git a/src/app/components/SecretStorage.tsx b/src/app/components/SecretStorage.tsx index 2b44d6a98..d40893723 100644 --- a/src/app/components/SecretStorage.tsx +++ b/src/app/components/SecretStorage.tsx @@ -9,9 +9,9 @@ import type { import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; import { useAlive } from '$hooks/useAlive'; import { PasswordInput } from './password-input'; +import { Button } from '$components/button'; type SecretStorageRecoveryPassphraseProps = { processing?: boolean; @@ -93,7 +93,7 @@ export function SecretStorageRecoveryPassphrase({ /> - Verify - + @@ -180,7 +180,7 @@ export function SecretStorageRecoveryKey({ /> - Verify - + diff --git a/src/app/components/button/Button.css.ts b/src/app/components/button/Button.css.ts new file mode 100644 index 000000000..b0fa86e50 --- /dev/null +++ b/src/app/components/button/Button.css.ts @@ -0,0 +1,149 @@ +import type { ComplexStyleRule } from '@vanilla-extract/css'; +import { createVar } from '@vanilla-extract/css'; +import type { RecipeVariants } from '@vanilla-extract/recipes'; +import { recipe } from '@vanilla-extract/recipes'; +import { color, config, toRem, DefaultReset, Disabled, FocusOutline, RadiiVariant } from 'folds'; + +type MainColor = 'Primary' | 'Secondary' | 'Success' | 'Warning' | 'Critical'; + +const Main = createVar(); +const MainHover = createVar(); +const MainActive = createVar(); +const MainLine = createVar(); +const OnMain = createVar(); +const Container = createVar(); +const ContainerHover = createVar(); +const ContainerActive = createVar(); +const ContainerLine = createVar(); +const OnContainer = createVar(); + +const Hover = createVar(); +const Active = createVar(); +const UIBeforeAfterSpace = createVar(); + +const getVariant = (variant: MainColor): ComplexStyleRule => ({ + vars: { + [Main]: color[variant].Main, + [MainHover]: color[variant].MainHover, + [MainActive]: color[variant].MainActive, + [MainLine]: color[variant].MainLine, + [OnMain]: color[variant].OnMain, + [Container]: color[variant].Container, + [ContainerHover]: color[variant].ContainerHover, + [ContainerActive]: color[variant].ContainerActive, + [ContainerLine]: color[variant].ContainerLine, + [OnContainer]: color[variant].OnContainer, + }, +}); + +export const Button = recipe({ + base: [ + DefaultReset, + { + minWidth: 0, + maxWidth: '100%', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + cursor: 'pointer', + + selectors: { + '&[aria-pressed=true]': { + backgroundColor: Active, + }, + '&:hover, &:focus-visible': { + backgroundColor: Hover, + }, + '&:active': { + backgroundColor: Active, + }, + '&[data-ui-before=true]': { + paddingLeft: [UIBeforeAfterSpace], + }, + '&[data-ui-after=true]': { + paddingRight: [UIBeforeAfterSpace], + }, + }, + }, + FocusOutline, + Disabled, + ], + variants: { + size: { + '300': { + vars: { + [UIBeforeAfterSpace]: config.space.S200, + }, + height: toRem(32), + gap: config.space.S100, + padding: `0 ${config.space.S300}`, + }, + '400': { + vars: { + [UIBeforeAfterSpace]: config.space.S300, + }, + height: toRem(40), + gap: config.space.S200, + padding: `0 ${config.space.S400}`, + }, + '500': { + vars: { + [UIBeforeAfterSpace]: config.space.S400, + }, + height: toRem(48), + gap: config.space.S300, + padding: `0 ${config.space.S500}`, + }, + }, + variant: { + Primary: getVariant('Primary'), + Secondary: getVariant('Secondary'), + Success: getVariant('Success'), + Warning: getVariant('Warning'), + Critical: getVariant('Critical'), + }, + fill: { + Solid: { + vars: { + [Hover]: MainHover, + [Active]: MainActive, + }, + backgroundColor: Main, + color: OnMain, + borderColor: MainLine, + }, + Soft: { + vars: { + [Hover]: ContainerHover, + [Active]: ContainerActive, + }, + backgroundColor: Container, + color: OnContainer, + borderColor: ContainerLine, + }, + None: { + vars: { + [Hover]: ContainerHover, + [Active]: ContainerActive, + }, + backgroundColor: 'inherit', + color: Main, + borderColor: Main, + }, + }, + outlined: { + true: { + borderWidth: config.borderWidth.B400, + }, + }, + radii: RadiiVariant, + }, + defaultVariants: { + size: '400', + variant: 'Primary', + fill: 'Solid', + radii: '400', + }, +}); + +export type ButtonVariants = RecipeVariants; diff --git a/src/app/components/button/Button.tsx b/src/app/components/button/Button.tsx new file mode 100644 index 000000000..481af5b23 --- /dev/null +++ b/src/app/components/button/Button.tsx @@ -0,0 +1,63 @@ +import type { ReactNode } from 'react'; +import classNames from 'classnames'; +import { as, Spinner } from 'folds'; +import * as css from './Button.css'; + +type SpinnerProps = { + /** Swaps `before` for a spinner and disables the button. */ + loading?: boolean; + spinnerVariant?: 'Primary' | 'Secondary' | 'Success' | 'Warning' | 'Critical'; + spinnerFill?: 'Solid' | 'Soft'; + spinnerSize?: '50' | '100' | '200' | '300' | '400' | '500' | '600' | 'Inherit'; +}; + +type ButtonProps = SpinnerProps & { + before?: ReactNode; + after?: ReactNode; +}; + +export const Button = as<'button', css.ButtonVariants & ButtonProps>( + ( + { + as: AsButton = 'button', + className, + size, + variant, + fill, + outlined, + radii, + before, + after, + loading, + spinnerVariant = 'Primary', + spinnerFill = 'Solid', + spinnerSize = '200', + disabled, + children, + ...props + }, + ref + ) => { + const leading = loading ? ( + + ) : ( + before + ); + + return ( + + {leading} + {children} + {after} + + ); + } +); diff --git a/src/app/components/button/index.ts b/src/app/components/button/index.ts new file mode 100644 index 000000000..8b166a86e --- /dev/null +++ b/src/app/components/button/index.ts @@ -0,0 +1 @@ +export * from './Button'; diff --git a/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx b/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx index e35b13242..f9df106a6 100644 --- a/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx +++ b/src/app/components/direct-invite-prompt/DirectInvitePrompt.tsx @@ -1,6 +1,6 @@ -import { Box, Button, Text, color, config } from 'folds'; +import { Box, Text, color, config } from 'folds'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; type DirectInvitePromptProps = { onCancel: () => void; @@ -32,7 +32,7 @@ export function DirectInvitePrompt({ )} - {converting ? 'Converting...' : 'Convert to Group Chat and Invite'} - + diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index 851eaa581..60a248f74 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -27,13 +27,13 @@ import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { highlightText, makeHighlightRegex } from '$plugins/react-custom-html-parser'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { composerIcon, X } from '$components/icons/phosphor'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useAlive } from '$hooks/useAlive'; import { getMxIdServer } from '$utils/mxIdHelper'; import { KnownMembership } from '$types/matrix-sdk'; +import { Button } from '$components/button'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, @@ -274,7 +274,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { /> - Invite - + diff --git a/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx b/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx index 5ff3896c3..f9dc31fd8 100644 --- a/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx +++ b/src/app/components/knock-room-prompt/KnockRoomPrompt.tsx @@ -8,7 +8,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { createDebugLogger } from '$utils/debugLogger'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; const debugLog = createDebugLogger('KnockRoomPrompt'); @@ -70,7 +70,7 @@ export function KnockRoomPrompt({ roomId, via, onDone, onCancel }: KnockRoomProp - {knockState.status === AsyncStatus.Loading ? 'Knocking...' : 'Knock'} - + ); diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx index e2fa5cc38..e37e1083a 100644 --- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx +++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx @@ -7,7 +7,7 @@ import { getJoinedSpaceChildrenSummary, getRecursiveSpaceLeaveOrder } from '$uti import { rateLimitedActions } from '$utils/matrix'; import { PromptDialog } from '$components/modal-overlay/PromptDialog'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; type LeaveSpacePromptProps = { roomId: string; @@ -95,7 +95,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP /> - leaveSpace()} @@ -105,9 +105,9 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP aria-disabled={isBusy || leaveState.status === AsyncStatus.Success} > {leaving ? 'Leaving...' : 'Leave Space Only'} - + {joinedChildrenCount > 0 && ( - leaveAll()} @@ -119,7 +119,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP {formatRecursiveLeaveLabel(leavingAll, roomCount, subspaceCount)} - + )} diff --git a/src/app/components/user-profile/UserModeration.tsx b/src/app/components/user-profile/UserModeration.tsx index 0c0b88c39..5374a3b39 100644 --- a/src/app/components/user-profile/UserModeration.tsx +++ b/src/app/components/user-profile/UserModeration.tsx @@ -1,9 +1,8 @@ -import { Box, Button, config, Spinner, Text, Input } from 'folds'; +import { Box, config, Spinner, Text, Input } from 'folds'; import { ArrowLeft, ArrowRight, profileIcon, Prohibit } from '$components/icons/phosphor'; import { useCallback, useRef } from 'react'; import { useRoom } from '$hooks/useRoom'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useSetting } from '$state/hooks/settings'; @@ -11,6 +10,7 @@ import { settingsAtom } from '$state/settings'; import { timeDayMonYear, timeHourMinute } from '$utils/time'; import { SettingTile } from '$components/setting-tile'; import { CutoutCard } from '$components/cutout-card'; +import { Button } from '$components/button'; type UserKickAlertProps = { reason?: string; @@ -111,7 +111,7 @@ export function UserBanAlert({ userId, reason, canUnban, bannedBy, ts }: UserBan {canUnban && ( - Unban - + )} @@ -183,7 +183,7 @@ export function UserInviteAlert({ userId, reason, canKick, invitedBy, ts }: User {canKick && ( - Cancel Invite - + )} diff --git a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx index fa4bfd28b..4c649bb09 100644 --- a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx +++ b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx @@ -18,10 +18,10 @@ import { useRoom } from '$hooks/useRoom'; import { useAlive } from '$hooks/useAlive'; import { useTextAreaCodeEditor } from '$hooks/useTextAreaCodeEditor'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { syntaxErrorPosition } from '$utils/dom'; import { Cursor } from '$plugins/text-area'; +import { Button } from '$components/button'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -152,7 +152,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro required /> - Send - + diff --git a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx index a270fa441..7302a192c 100644 --- a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx +++ b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx @@ -9,7 +9,6 @@ import { config, TextArea as TextAreaComponent, color, - Button, } from 'folds'; import { ArrowLeft, composerIcon, menuIcon, X } from '$components/icons/phosphor'; import type { MatrixError, StateEvents } from '$types/matrix-sdk'; @@ -23,7 +22,6 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useAlive } from '$hooks/useAlive'; import { Cursor } from '$plugins/text-area'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { syntaxErrorPosition } from '$utils/dom'; import { SettingTile } from '$components/setting-tile'; @@ -31,6 +29,7 @@ import { usePowerLevels } from '$hooks/usePowerLevels'; import { useTextAreaCodeEditor } from '$hooks/useTextAreaCodeEditor'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; +import { Button } from '$components/button'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -130,7 +129,7 @@ function StateEventEdit({ type, stateKey, content, requestClose }: StateEventEdi description={stateKey} after={ - Save - + @@ -335,7 +334,7 @@ export function RoomPacks({ onViewPack }: Readonly) { > Cancel - ) { onClick={handleApplyChanges} > Delete - +
diff --git a/src/app/features/common-settings/general/RoomEncryption.tsx b/src/app/features/common-settings/general/RoomEncryption.tsx index 51f823ca6..c11312f3b 100644 --- a/src/app/features/common-settings/general/RoomEncryption.tsx +++ b/src/app/features/common-settings/general/RoomEncryption.tsx @@ -12,7 +12,7 @@ import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; import { EventType } from '$types/matrix-sdk'; import { confirm } from '$components/confirm/confirm'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; const ROOM_ENC_ALGO = 'm.megolm.v1.aes-sha2'; @@ -71,7 +71,7 @@ export function RoomEncryption({ permissions }: RoomEncryptionProps) { Enabled ) : ( - Enable - + ) } > diff --git a/src/app/features/common-settings/general/RoomProfile.tsx b/src/app/features/common-settings/general/RoomProfile.tsx index 0cfe3859a..48d8c3d25 100644 --- a/src/app/features/common-settings/general/RoomProfile.tsx +++ b/src/app/features/common-settings/general/RoomProfile.tsx @@ -1,4 +1,4 @@ -import { Avatar, Box, Button, Chip, config, Input, Text, TextArea } from 'folds'; +import { Avatar, Box, Chip, config, Input, Text, TextArea } from 'folds'; import { ArrowsClockwise, chipIcon, menuIcon, PencilSimple } from '$components/icons/phosphor'; import type { FormEventHandler } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; @@ -35,7 +35,7 @@ import { SettingTile } from '$components/setting-tile'; import { confirm } from '$components/confirm/confirm'; import { reportMediaLoadFailure } from '$utils/mediaLoadDiagnostics'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; type RoomProfileEditProps = { canEditAvatar: boolean; @@ -263,7 +263,7 @@ function RoomProfileEdit({ - Save - + diff --git a/src/app/features/common-settings/permissions/PermissionGroups.tsx b/src/app/features/common-settings/permissions/PermissionGroups.tsx index 350626762..dba89acab 100644 --- a/src/app/features/common-settings/permissions/PermissionGroups.tsx +++ b/src/app/features/common-settings/permissions/PermissionGroups.tsx @@ -1,6 +1,5 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; -import { Badge, Box, Button, Chip, config, Menu, Text } from 'folds'; -import { AsyncButton } from '$components/AsyncButton'; +import { Badge, Box, Chip, config, Menu, Text } from 'folds'; import { CaretDown, CaretUp, chipIcon } from '$components/icons/phosphor'; import { produce } from 'immer'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; @@ -17,6 +16,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useAlive } from '$hooks/useAlive'; import type { PermissionGroup } from './types'; import { EventType } from '$types/matrix-sdk'; +import { Button } from '$components/button'; const USER_DEFAULT_LOCATION: PermissionLocation = { user: true, @@ -266,7 +266,7 @@ export function PermissionGroups({ > Reset - Apply Changes - +
diff --git a/src/app/features/create-chat/CreateChat.tsx b/src/app/features/create-chat/CreateChat.tsx index 28a896560..bc2791d1e 100644 --- a/src/app/features/create-chat/CreateChat.tsx +++ b/src/app/features/create-chat/CreateChat.tsx @@ -1,5 +1,4 @@ import { Box, color, config, Input, Switch, Text } from 'folds'; -import { AsyncButton } from '$components/AsyncButton'; import { sizedIcon, Warning } from '$components/icons/phosphor'; import type { FormEventHandler } from 'react'; import { useCallback, useState } from 'react'; @@ -16,6 +15,7 @@ import { createRoomEncryptionState } from '$components/create-room'; import { useAlive } from '$hooks/useAlive'; import { getDirectRoomPath } from '$pages/pathUtils'; import { ErrorCode } from '../../cs-errorcode'; +import { Button } from '$components/button'; type CreateChatProps = { defaultUserId?: string; @@ -141,7 +141,7 @@ export function CreateChat({ defaultUserId }: CreateChatProps) { )} - Create Chat - + ); diff --git a/src/app/features/create-room/CreateRoom.tsx b/src/app/features/create-room/CreateRoom.tsx index 6f9cdec41..3551db965 100644 --- a/src/app/features/create-room/CreateRoom.tsx +++ b/src/app/features/create-room/CreateRoom.tsx @@ -3,7 +3,6 @@ import { useCallback, useEffect, useState } from 'react'; import type { Room } from '$types/matrix-sdk'; import { MatrixError, JoinRule, RoomType } from '$types/matrix-sdk'; import { Box, Chip, color, config, Input, Switch, Text, TextArea } from 'folds'; -import { AsyncButton } from '$components/AsyncButton'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -42,6 +41,7 @@ import { knockRestrictedSupported, } from '$utils/roomSupport'; import { ErrorCode } from '../../cs-errorcode'; +import { Button } from '$components/button'; const debugLog = createDebugLogger('CreateRoom'); @@ -347,7 +347,7 @@ export function CreateRoomForm({ )} - Create Room - + ); diff --git a/src/app/features/create-space/CreateSpace.tsx b/src/app/features/create-space/CreateSpace.tsx index c1ec08829..212f95827 100644 --- a/src/app/features/create-space/CreateSpace.tsx +++ b/src/app/features/create-space/CreateSpace.tsx @@ -3,7 +3,6 @@ import { useCallback, useEffect, useState } from 'react'; import type { Room } from '$types/matrix-sdk'; import { MatrixError, RoomType } from '$types/matrix-sdk'; import { Box, Chip, color, config, Input, Switch, Text, TextArea } from 'folds'; -import { AsyncButton } from '$components/AsyncButton'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -38,6 +37,7 @@ import { } from '$components/icons/phosphor'; import { ErrorCode } from '../../cs-errorcode'; +import { Button } from '$components/button'; const getCreateSpaceAccessToIcon = ( access: CreateRoomAccess, @@ -267,7 +267,7 @@ export function CreateSpaceForm({ defaultAccess, space, onCreate }: CreateSpaceF )} - Create Space - + ); diff --git a/src/app/features/room/RoomTombstone.tsx b/src/app/features/room/RoomTombstone.tsx index 45f662514..25e902daa 100644 --- a/src/app/features/room/RoomTombstone.tsx +++ b/src/app/features/room/RoomTombstone.tsx @@ -1,9 +1,8 @@ import { useCallback } from 'react'; -import { Box, Button, Text } from 'folds'; +import { Box, Text } from 'folds'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; @@ -11,6 +10,7 @@ import { getViaServers } from '$plugins/via-servers'; import { RoomInputPlaceholder } from './RoomInputPlaceholder'; import * as css from './RoomTombstone.css'; import { KnownMembership } from '$types/matrix-sdk'; +import { Button } from '$components/button'; type RoomTombstoneProps = { roomId: string; body?: string; replacementRoomId: string }; export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstoneProps) { @@ -46,7 +46,7 @@ export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstone Open New Room ) : ( - Join New Room - + )} diff --git a/src/app/features/settings/devices/LocalBackup.tsx b/src/app/features/settings/devices/LocalBackup.tsx index f9cb9e981..14e3fcc83 100644 --- a/src/app/features/settings/devices/LocalBackup.tsx +++ b/src/app/features/settings/devices/LocalBackup.tsx @@ -1,6 +1,6 @@ import type { FormEventHandler } from 'react'; import { useCallback, useEffect, useState } from 'react'; -import { Box, Button, color, Text, toRem } from 'folds'; +import { Box, color, Text, toRem } from 'folds'; import { ArrowRight, CaretDown, CaretUp, File, menuIcon, X } from '$components/icons/phosphor'; import { saveFileToDevice } from '$utils/download'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; @@ -9,7 +9,6 @@ import { PasswordInput } from '$components/password-input'; import { ConfirmPasswordMatch } from '$components/ConfirmPasswordMatch'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { decryptMegolmKeyFile, encryptMegolmKeyFile, @@ -17,6 +16,7 @@ import { } from '$utils/MegolmExportEncryption'; import { useAlive } from '$hooks/useAlive'; import { useFilePicker } from '$hooks/useFilePicker'; +import { Button } from '$components/button'; type LocalBackupError = Error | FriendlyError; @@ -112,7 +112,7 @@ function ExportKeys() { )} - Export - + {exportState.status === AsyncStatus.Error && ( @@ -237,7 +237,7 @@ function ImportKeys({ file, onDone }: ImportKeysProps) { readOnly={decrypting} /> - Decrypt - + {decryptState.status === AsyncStatus.Error && ( diff --git a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx index 665037fe6..876ca27f4 100644 --- a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx +++ b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx @@ -1,5 +1,5 @@ import { useCallback, useState } from 'react'; -import { Box, Button, color, config, Dialog, Header, IconButton, Text } from 'folds'; +import { Box, color, config, Dialog, Header, IconButton, Text } from 'folds'; import { menuIcon, X } from '$components/icons/phosphor'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { useAtom } from 'jotai'; @@ -14,7 +14,7 @@ import { disableNativePush } from './NotificationTransport'; import { disableUnifiedPush } from './UnifiedPushNotifications'; import { SettingTile } from '../../../components/setting-tile'; import { isTauri } from '@tauri-apps/api/core'; -import { AsyncButton } from '../../../components/AsyncButton'; +import { Button } from '$components/button'; type ConfirmDeregisterDialogProps = { onClose: () => void; @@ -40,7 +40,7 @@ function ConfirmDeregisterDialog({ onClose, onConfirm, isLoading }: ConfirmDereg cannot be undone. Are you sure you want to continue? - Reset All - + diff --git a/src/app/pages/auth/login/OidcLogin.tsx b/src/app/pages/auth/login/OidcLogin.tsx index 6606bccef..d270b68c9 100644 --- a/src/app/pages/auth/login/OidcLogin.tsx +++ b/src/app/pages/auth/login/OidcLogin.tsx @@ -1,9 +1,8 @@ -import { Box, Button, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds'; +import { Box, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds'; import { useCallback, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import type { ValidatedAuthMetadata } from '$types/matrix-sdk'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { useAuthServer } from '$hooks/useAuthServer'; import { InfoCard } from '$components/info-card'; import { getLoginPath } from '$pages/pathUtils'; @@ -15,6 +14,7 @@ import { completeOidcLogin, startOidcLogin, } from './oidcLoginUtil'; +import { Button } from '$components/button'; const ERROR_TITLE = 'Single sign-on'; @@ -67,7 +67,7 @@ export function OidcLoginButton({ {errorMessage && ( )} - {label} - + ); } diff --git a/src/app/pages/client/SpecVersions.tsx b/src/app/pages/client/SpecVersions.tsx index 6bd96b4a1..1b0a19cfa 100644 --- a/src/app/pages/client/SpecVersions.tsx +++ b/src/app/pages/client/SpecVersions.tsx @@ -1,6 +1,6 @@ import type { ReactNode } from 'react'; import { useCallback, useState } from 'react'; -import { Box, Button, Dialog, config, Text } from 'folds'; +import { Box, Dialog, config, Text } from 'folds'; import { useAtomValue, useSetAtom } from 'jotai'; import { SpecVersionsLoader } from '$components/SpecVersionsLoader'; import { SpecVersionsProvider } from '$hooks/useSpecVersions'; @@ -12,7 +12,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useClientConfig } from '$hooks/useClientConfig'; import type { SpecVersions } from '../../cs-api'; import { AsyncError } from '$components/AsyncError'; -import { AsyncButton } from '$components/AsyncButton'; +import { Button } from '$components/button'; const EMPTY_VERSIONS: SpecVersions = { versions: [] }; @@ -102,7 +102,7 @@ function HomeserverOfflineError({ baseUrl, onRetry }: HomeserverOfflineErrorProp )} )} - Logout - + diff --git a/src/app/pages/client/inbox/Invites.tsx b/src/app/pages/client/inbox/Invites.tsx index a1d753e01..3438a1506 100644 --- a/src/app/pages/client/inbox/Invites.tsx +++ b/src/app/pages/client/inbox/Invites.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useRef, useState } from 'react'; -import { Avatar, Badge, Box, Button, Chip, IconButton, Scroll, Spinner, Text, config } from 'folds'; +import { Avatar, Badge, Box, Chip, IconButton, Scroll, Spinner, Text, config } from 'folds'; import { useAtom, useAtomValue } from 'jotai'; import { ArrowLeft, @@ -54,7 +54,6 @@ import { useElementSizeObserver } from '$hooks/useElementSizeObserver'; import { onEnterOrSpace } from '$utils/keyboard'; import { RoomTopicViewer } from '$components/room-topic-viewer'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; @@ -72,6 +71,7 @@ import { CustomAccountDataEvent } from '$types/matrix/accountData'; import { updateInviteList } from '$state/updateInvites'; import { useDismissedInviteList } from '$hooks/useDismissedInvites'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; +import { Button } from '$components/button'; const COMPACT_CARD_WIDTH = 548; @@ -318,7 +318,7 @@ function InviteCard({ > {isDismissed ? 'Undismiss' : 'Dismiss'} - Decline - - + @@ -645,7 +645,7 @@ function SpamInvites({ subTitle="Some of the following invites may contain harmful content or have been sent by banned users." > - Decline All - + {reportRoomSupported && reportAllStatus.status !== AsyncStatus.Success && ( - Report All - + )} {unignoredUsers.length > 0 && ( - Block All - + )} diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index dc597ab05..0d7c167a1 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -4,7 +4,6 @@ import { useAtom, useAtomValue } from 'jotai'; import { Avatar, Box, - Button, IconButton, Line, Menu, @@ -83,7 +82,6 @@ import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { ContainerColor } from '$styles/ContainerColor.css'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import { AsyncButton } from '$components/AsyncButton'; import { AsyncError } from '$components/AsyncError'; import { InviteUserPrompt } from '$components/invite-user-prompt'; import { useCallEmbed } from '$hooks/useCallEmbed'; @@ -105,6 +103,7 @@ import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; import { useOpenRoomSettings } from '$state/hooks/roomSettings'; import { ResponsiveMenu } from '$components/ResponsiveMenu'; import { useMenuAnchor } from '$hooks/useMenuAnchor'; +import { Button } from '$components/button'; const debugLog = createDebugLogger('Space'); @@ -463,7 +462,7 @@ function SpaceTombstone({ roomId, replacementRoomId }: SpaceTombstoneProps) { Open New Space ) : ( - Join New Space - + )}