From a6ad8651b3c241aee65682d300e50c70c5c8eee3 Mon Sep 17 00:00:00 2001 From: litruv Date: Sun, 1 Nov 2026 04:23:53 +1100 Subject: [PATCH] Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts. --- .gitignore | 3 + CODE_OF_CONDUCT.md | 22 +- config.json | 6 +- docs/API-QUICKSTART.md | 47 +- docs/API.md | 183 ++-- docs/PLUGINS.md | 7 +- docs/PLUGIN_API.md | 441 ++++----- docs/PLUGIN_BUTTON_API.md | 129 ++- docs/PLUGIN_SYSTEM_IMPLEMENTATION.md | 51 +- docs/handoff/TEMPLATE.md | 8 +- docs/handoff/features/android/HANDOFF.md | 16 +- .../features/authentication/HANDOFF.md | 40 +- .../features/avatar-metadata/HANDOFF.md | 26 +- .../background-notifications/HANDOFF.md | 26 +- .../handoff/features/client-chrome/HANDOFF.md | 30 +- .../features/common-settings/HANDOFF.md | 18 +- docs/handoff/features/create-flows/HANDOFF.md | 24 +- .../features/custom-emoji-packs/HANDOFF.md | 28 +- .../features/developer-tools/HANDOFF.md | 14 +- .../features/direct-messages/HANDOFF.md | 20 +- .../features/e2e-and-devices/HANDOFF.md | 34 +- .../features/editor-and-composer/HANDOFF.md | 32 +- .../features/electron-shell/HANDOFF.md | 28 +- .../handoff/features/embed-filters/HANDOFF.md | 26 +- .../features/emoji-stickers/HANDOFF.md | 32 +- docs/handoff/features/explore/HANDOFF.md | 12 +- docs/handoff/features/forum/HANDOFF.md | 44 +- .../handoff/features/global-search/HANDOFF.md | 16 +- .../features/home-and-sidebar/HANDOFF.md | 44 +- .../features/inbox-and-invites/HANDOFF.md | 24 +- .../features/join-before-navigate/HANDOFF.md | 12 +- docs/handoff/features/lobby-forums/HANDOFF.md | 40 +- docs/handoff/features/local-api/HANDOFF.md | 48 +- .../handoff/features/matrix-client/HANDOFF.md | 28 +- .../features/media-and-url-preview/HANDOFF.md | 24 +- .../features/message-rendering/HANDOFF.md | 24 +- .../features/message-search/HANDOFF.md | 14 +- docs/handoff/features/plugins/HANDOFF.md | 24 +- docs/handoff/features/room-app-ui/HANDOFF.md | 24 +- docs/handoff/features/room-nav/HANDOFF.md | 12 +- .../handoff/features/room-settings/HANDOFF.md | 18 +- .../handoff/features/room-timeline/HANDOFF.md | 46 +- .../routing-and-navigation/HANDOFF.md | 34 +- .../features/space-settings/HANDOFF.md | 12 +- .../features/state-management/HANDOFF.md | 48 +- docs/handoff/features/streamdeck/HANDOFF.md | 18 +- docs/handoff/features/sub-rooms/HANDOFF.md | 24 +- .../features/themes-and-appearance/HANDOFF.md | 24 +- .../handoff/features/user-settings/HANDOFF.md | 28 +- docs/handoff/features/voice-calls/HANDOFF.md | 34 +- eslint.config.js | 44 +- index.html | 14 +- playground.html | 2 +- public/gif.worker.js | 858 +++++++++++++++++- public/update/4.11.185.md | 1 - scripts/generate-update-manifest.mjs | 4 +- src/app/components/AccountDataEditor.tsx | 20 +- src/app/components/AngleSelector.tsx | 10 +- src/app/components/AnimatedOutlet.tsx | 2 +- src/app/components/AuthFlowsLoader.tsx | 2 +- src/app/components/BackupRestore.tsx | 20 +- src/app/components/ConfirmPasswordMatch.tsx | 4 +- src/app/components/DeviceVerification.tsx | 16 +- .../components/DeviceVerificationSetup.tsx | 20 +- src/app/components/JoinRulesSwitcher.tsx | 10 +- src/app/components/LogoutDialog.tsx | 6 +- src/app/components/ManualVerification.tsx | 8 +- src/app/components/Pdf-viewer/PdfViewer.tsx | 25 +- src/app/components/RenderMessageContent.tsx | 68 +- .../components/RoomNotificationSwitcher.tsx | 8 +- src/app/components/RouteTransition.tsx | 11 +- src/app/components/SecretStorage.tsx | 10 +- src/app/components/ServerConfigsLoader.tsx | 2 +- .../components/SpaceChildDirectsProvider.tsx | 2 +- .../components/SpaceChildRoomsProvider.tsx | 2 +- src/app/components/SpecVersionsLoader.tsx | 4 +- src/app/components/UIAFlowOverlay.tsx | 14 +- .../account-switcher/AccountSwitcher.tsx | 65 +- .../AuthenticatedAvatarImage.tsx | 2 +- .../AuthenticatedMedia.tsx | 7 +- .../create-room/AdditionalCreatorInput.tsx | 24 +- .../create-room/CreateRoomAliasInput.tsx | 6 +- .../create-room/RoomVersionSelector.tsx | 2 +- src/app/components/create-room/utils.ts | 8 +- .../custom-status/CustomStatusDialog.tsx | 45 +- src/app/components/cutout-card/CutoutCard.tsx | 2 +- src/app/components/direct-list/DirectList.tsx | 26 +- src/app/components/editor/Editor.tsx | 105 +-- src/app/components/editor/Toolbar.tsx | 18 +- .../autocomplete/EmoticonAutocomplete.tsx | 4 +- .../autocomplete/RoomMentionAutocomplete.tsx | 77 +- .../autocomplete/UserMentionAutocomplete.tsx | 6 +- .../editor/autocomplete/autocompleteQuery.ts | 6 +- src/app/components/editor/input.ts | 16 +- src/app/components/editor/output.ts | 6 +- src/app/components/editor/utils.ts | 6 +- src/app/components/emoji-board/EmojiBoard.tsx | 21 +- .../emoji-board/components/NoStickerPacks.tsx | 1 + .../emoji-board/components/Sidebar.tsx | 2 +- .../emoji-board/useEmojiGroupIcons.ts | 5 +- .../emoji-board/useEmojiGroupLabels.ts | 2 +- .../components/event-readers/EventReaders.tsx | 8 +- src/app/components/icons/Icon.tsx | 9 +- .../components/image-editor/ImageEditor.tsx | 2 +- .../image-pack-view/ImagePackContent.tsx | 24 +- .../components/image-pack-view/PackMeta.tsx | 6 +- .../image-pack-view/RoomImagePack.tsx | 6 +- .../image-pack-view/UsageSwitcher.tsx | 4 +- .../image-pack-view/UserImagePack.tsx | 2 +- .../components/image-viewer/ImageViewer.tsx | 24 +- .../invite-user-prompt/InviteUserPrompt.tsx | 31 +- .../join-address-prompt/JoinAddressPrompt.tsx | 15 +- .../join-space-prompt/JoinSpacePrompt.tsx | 41 +- .../leave-room-prompt/LeaveRoomPrompt.tsx | 19 +- .../leave-space-prompt/LeaveSpacePrompt.tsx | 23 +- .../manage-rooms-prompt/ManageRoomsPrompt.tsx | 43 +- src/app/components/media/Image.tsx | 2 +- src/app/components/media/MediaControls.tsx | 2 +- src/app/components/media/Video.tsx | 47 +- src/app/components/member-tile/MemberTile.tsx | 4 +- src/app/components/message/FileHeader.tsx | 10 +- .../components/message/MsgTypeRenderers.tsx | 69 +- src/app/components/message/Reaction.tsx | 4 +- src/app/components/message/Reply.tsx | 17 +- .../components/message/StationeryMedia.tsx | 17 +- src/app/components/message/Time.tsx | 2 +- .../message/attachment/Attachment.tsx | 2 +- .../message/content/AudioContent.tsx | 14 +- .../message/content/EventContent.tsx | 2 +- .../message/content/FallbackContent.tsx | 4 +- .../message/content/FileContent.tsx | 44 +- .../message/content/ImageContent.tsx | 52 +- .../message/content/ThumbnailContent.tsx | 34 +- .../message/content/VideoContent.tsx | 43 +- .../message/content/VideoFrameThumbnail.tsx | 45 +- src/app/components/message/layout/Base.tsx | 71 +- src/app/components/message/layout/Bubble.tsx | 2 +- src/app/components/message/layout/Compact.tsx | 2 +- .../components/message/layout/layout.css.ts | 2 +- .../placeholder/CompactPlaceholder.tsx | 2 +- .../placeholder/DefaultPlaceholder.tsx | 2 +- .../message/placeholder/LinePlaceholder.tsx | 2 +- src/app/components/nav/NavCategoryHeader.tsx | 2 +- src/app/components/nav/NavItem.tsx | 4 +- src/app/components/nav/NavItemContent.tsx | 2 +- src/app/components/nav/NavItemOptions.tsx | 2 +- src/app/components/page/Page.tsx | 6 +- .../password-input/PasswordInput.tsx | 2 +- src/app/components/power/PowerColorBadge.tsx | 2 +- src/app/components/power/PowerSelector.tsx | 2 +- src/app/components/presence/Presence.tsx | 7 +- .../RemoveInaccessiblePrompt.tsx | 16 +- src/app/components/room-avatar/RoomAvatar.tsx | 20 +- src/app/components/room-card/RoomCard.tsx | 38 +- src/app/components/room-intro/RoomIntro.tsx | 2 +- .../room-topic-viewer/RoomTopicViewer.tsx | 2 +- .../ScrollTopContainer.tsx | 4 +- .../components/sequence-card/SequenceCard.tsx | 6 +- src/app/components/sidebar/Sidebar.tsx | 7 +- src/app/components/sidebar/SidebarContent.tsx | 7 +- src/app/components/sidebar/SidebarItem.tsx | 10 +- src/app/components/sidebar/SidebarStack.tsx | 2 +- .../speech-bubble/SpeechBubble.css.ts | 1 - .../components/speech-bubble/SpeechBubble.tsx | 9 +- src/app/components/text-viewer/TextViewer.tsx | 7 +- src/app/components/time-date/DatePicker.tsx | 2 +- src/app/components/time-date/TimePicker.tsx | 2 +- src/app/components/title-bar/TitleBar.tsx | 394 ++++---- .../title-bar/WindowControls.css.ts | 27 +- .../components/title-bar/WindowControls.tsx | 40 +- .../typing-indicator/TypingIndicator.tsx | 2 +- src/app/components/uia-stages/EmailStage.tsx | 4 +- .../components/uia-stages/PasswordStage.tsx | 2 +- .../uia-stages/RegistrationTokenStage.tsx | 2 +- src/app/components/uia-stages/SSOStage.tsx | 4 +- src/app/components/uia-stages/TermsStage.tsx | 2 +- .../components/unread-badge/UnreadBadge.tsx | 2 +- .../UpdateNotification.tsx | 11 +- .../updates-dialog/UpdatesDialog.css.ts | 9 +- .../updates-dialog/UpdatesDialog.tsx | 9 +- .../updates-dialog/UpdatesDialogHost.tsx | 2 +- .../components/upload-board/UploadBoard.tsx | 6 +- src/app/components/upload-card/UploadCard.tsx | 4 +- src/app/components/url-preview/GiphyEmbed.tsx | 9 +- .../components/url-preview/TikTokEmbed.tsx | 2 +- .../components/url-preview/UrlPreviewCard.tsx | 19 +- .../components/url-preview/YouTubeEmbed.tsx | 18 +- src/app/components/user-avatar/UserAvatar.tsx | 9 +- .../components/user-profile/CreatorChip.tsx | 26 +- src/app/components/user-profile/PowerChip.tsx | 54 +- src/app/components/user-profile/UserChips.tsx | 119 ++- src/app/components/user-profile/UserHero.tsx | 6 +- .../user-profile/UserModeration.tsx | 12 +- .../user-profile/UserRoomProfile.tsx | 84 +- .../components/video-viewer/VideoViewer.tsx | 10 +- .../components/virtualizer/VirtualTile.tsx | 2 +- src/app/cs-api.ts | 6 +- src/app/data/updateNotes.ts | 9 +- src/app/features/ShareRoomPicker.tsx | 353 +++---- src/app/features/add-existing/AddExisting.tsx | 31 +- src/app/features/call/CallOverlay.tsx | 842 +++++++++-------- src/app/features/call/CallService.ts | 333 ++++--- src/app/features/call/CallSounds.ts | 8 +- src/app/features/call/DockedCallContent.tsx | 118 ++- src/app/features/call/DockedCallPanel.tsx | 4 +- .../call/IncomingCallNotification.tsx | 108 ++- src/app/features/call/RemoteCursorOverlay.tsx | 9 +- .../features/call/SidebarDockedCallPanel.tsx | 88 +- src/app/features/call/useCall.ts | 80 +- src/app/features/call/useDockedCall.ts | 11 +- src/app/features/call/useRemoteCursor.ts | 6 +- src/app/features/call/useRoomCallMembers.ts | 6 +- src/app/features/call/useRtcConfig.ts | 81 +- .../developer-tools/DevelopTools.tsx | 27 +- .../developer-tools/SendRoomEvent.tsx | 19 +- .../developer-tools/StateEventEditor.tsx | 23 +- .../emojis-stickers/RoomPacks.tsx | 23 +- .../common-settings/general/EmbedFilters.tsx | 21 +- .../common-settings/general/RoomAddress.tsx | 24 +- .../general/RoomEncryption.tsx | 20 +- .../general/RoomHistoryVisibility.tsx | 10 +- .../common-settings/general/RoomJoinRules.tsx | 4 +- .../common-settings/general/RoomProfile.tsx | 12 +- .../common-settings/general/RoomPublish.tsx | 2 +- .../common-settings/general/RoomUpgrade.tsx | 25 +- .../common-settings/members/Members.tsx | 28 +- .../permissions/PermissionGroups.tsx | 12 +- .../permissions/PowersEditor.tsx | 26 +- src/app/features/create-chat/CreateChat.tsx | 8 +- src/app/features/create-room/CreateRoom.tsx | 6 +- .../features/create-room/CreateRoomModal.tsx | 44 +- src/app/features/create-space/CreateSpace.tsx | 42 +- .../create-space/CreateSpaceModal.tsx | 15 +- .../features/forum/ForumAuthorIdentity.tsx | 12 +- src/app/features/forum/ForumBoardDetail.tsx | 11 +- src/app/features/forum/ForumBoardView.tsx | 21 +- src/app/features/forum/ForumChatComposer.tsx | 28 +- src/app/features/forum/ForumEventContent.tsx | 6 +- src/app/features/forum/ForumFeedSidebar.tsx | 7 +- src/app/features/forum/ForumFilterBar.tsx | 4 +- .../features/forum/ForumMessageActions.tsx | 182 ++-- .../forum/ForumMessageContextMenu.tsx | 12 +- src/app/features/forum/ForumNewPostModal.tsx | 47 +- src/app/features/forum/ForumPostList.tsx | 10 +- .../features/forum/ForumPostUploadField.tsx | 12 +- .../features/forum/ForumRichReplyComposer.tsx | 24 +- src/app/features/forum/ForumSpaceShell.tsx | 24 +- src/app/features/forum/ForumThreadDetail.tsx | 227 ++--- .../features/forum/ForumTopicSearchInput.tsx | 35 +- src/app/features/forum/forumFeed.ts | 65 +- src/app/features/forum/forumLucideIcons.tsx | 43 +- src/app/features/forum/forumRichText.ts | 2 +- src/app/features/forum/forumTheme.css.ts | 55 +- src/app/features/forum/forumTopicHelpers.ts | 14 +- src/app/features/forum/topicSearch.ts | 53 +- src/app/features/forum/useForumBoard.ts | 118 ++- .../forum/useForumMessageReactions.ts | 12 +- .../forum/useForumMessageRenderOptions.ts | 13 +- .../features/forum/useForumRoomLiveUpdates.ts | 13 +- .../JoinBeforeNavigate.tsx | 2 +- src/app/features/lobby/DnD.tsx | 6 +- src/app/features/lobby/HierarchyItemMenu.tsx | 20 +- src/app/features/lobby/Lobby.tsx | 54 +- src/app/features/lobby/LobbyHeader.tsx | 215 ++--- src/app/features/lobby/LobbyHero.tsx | 4 +- src/app/features/lobby/RoomItem.tsx | 30 +- src/app/features/lobby/SpaceHierarchy.tsx | 14 +- src/app/features/lobby/SpaceItem.tsx | 34 +- .../features/message-search/MessageSearch.tsx | 8 +- .../features/message-search/SearchFilters.tsx | 24 +- .../features/message-search/SearchInput.tsx | 1 + .../message-search/SearchResultGroup.tsx | 37 +- .../message-search/useMessageSearch.ts | 7 +- src/app/features/room-app/RoomAppSchema.tsx | 6 +- src/app/features/room-app/RoomAppView.tsx | 8 +- .../features/room-app/sanitizeRoomAppCss.ts | 4 +- .../room-nav/CallParticipantsIndicator.tsx | 39 +- .../room-nav/RoomNavCategoryButton.tsx | 4 +- src/app/features/room-nav/RoomNavItem.tsx | 216 +++-- .../features/room-nav/UnjoinedSubRoomItem.tsx | 32 +- .../features/room-settings/RoomSettings.tsx | 10 +- .../room-settings/sub-rooms/SubRooms.tsx | 42 +- src/app/features/room/CommandAutocomplete.tsx | 10 +- src/app/features/room/ForumRoomView.tsx | 2 +- src/app/features/room/MembersDrawer.tsx | 35 +- src/app/features/room/Room.tsx | 9 +- src/app/features/room/RoomInput.tsx | 110 ++- .../features/room/RoomInputPlaceholder.tsx | 2 +- src/app/features/room/RoomTimeline.tsx | 340 ++++--- src/app/features/room/RoomTombstone.tsx | 2 +- src/app/features/room/RoomView.tsx | 4 +- src/app/features/room/RoomViewFollowing.tsx | 7 +- src/app/features/room/RoomViewHeader.tsx | 75 +- src/app/features/room/RoomViewTyping.tsx | 8 +- src/app/features/room/ThreadView.tsx | 165 ++-- .../EmojiConfettiBurstCanvas.tsx | 30 +- .../emoji-confetti/EmojiConfettiOverlay.tsx | 6 +- .../room/emoji-confetti/burstOrigin.ts | 4 +- .../room/emoji-confetti/emojiBurstEngine.ts | 18 +- .../emoji-confetti/fireworkParticleEngine.ts | 26 +- .../emoji-confetti/jumboEmojiInteraction.ts | 5 +- .../emoji-confetti/resolveClickedEmoji.ts | 10 +- .../room/emoji-confetti/sendEmojiConfetti.ts | 2 +- .../room/emoji-confetti/useEmojiConfetti.ts | 48 +- .../emoji-confetti/useJumboEmojiConfetti.ts | 8 +- .../features/room/jump-to-time/JumpToTime.tsx | 24 +- src/app/features/room/message/Message.tsx | 595 ++++++------ .../features/room/message/MessageEditor.tsx | 16 +- src/app/features/room/message/Reactions.tsx | 4 +- src/app/features/room/msgContent.ts | 12 +- .../room/reaction-viewer/ReactionViewer.tsx | 10 +- .../room/room-media-menu/RoomMediaMenu.tsx | 463 +++++----- .../room/room-pin-menu/RoomPinMenu.tsx | 35 +- src/app/features/search/Search.tsx | 29 +- src/app/features/settings/Settings.tsx | 19 +- src/app/features/settings/about/About.tsx | 79 +- .../account/CollectiblesSection.css.ts | 3 +- .../settings/account/CollectiblesSection.tsx | 184 ++-- .../features/settings/account/ContactInfo.tsx | 2 +- .../settings/account/IgnoredUserList.tsx | 8 +- src/app/features/settings/account/Profile.tsx | 841 ++++++++--------- .../account/ProfileEffectHeroPreview.tsx | 7 +- src/app/features/settings/audio/Audio.tsx | 140 ++- .../settings/developer-tools/AccountData.tsx | 4 +- .../settings/developer-tools/DevelopTools.tsx | 56 +- .../developer-tools/ProfileFields.tsx | 62 +- .../features/settings/devices/DeviceTile.tsx | 23 +- src/app/features/settings/devices/Devices.tsx | 6 +- .../features/settings/devices/LocalBackup.tsx | 10 +- .../settings/devices/OtherDevices.tsx | 16 +- .../settings/devices/Verification.tsx | 24 +- .../emojis-stickers/EmojisStickers.tsx | 5 +- .../settings/emojis-stickers/GlobalPacks.tsx | 41 +- .../emojis-stickers/TelegramImport.tsx | 25 +- src/app/features/settings/general/General.tsx | 118 ++- .../settings/notifications/AllMessages.tsx | 6 +- .../notifications/KeywordMessages.tsx | 16 +- .../NotificationModeSwitcher.tsx | 4 +- .../settings/notifications/Notifications.tsx | 4 +- .../notifications/SpecialMessages.tsx | 14 +- .../notifications/SystemNotification.tsx | 26 +- .../settings/plugins/PLUGIN_DEVELOPMENT.md | 223 +++-- .../features/settings/plugins/PluginAPI.ts | 25 +- .../settings/plugins/PluginButtonSlot.tsx | 14 +- .../settings/plugins/PluginLoader.tsx | 13 +- .../settings/plugins/PluginSidebarSlot.tsx | 6 +- src/app/features/settings/plugins/Plugins.tsx | 250 ++--- .../settings/settingsSearchCatalog.ts | 192 +++- .../features/space-settings/SpaceSettings.tsx | 6 +- .../permissions/Permissions.tsx | 138 ++- src/app/features/space/SpaceOptionsMenu.tsx | 348 ++++--- src/app/hooks/media/useMediaLoading.ts | 2 +- src/app/hooks/media/useMediaPlay.ts | 4 +- .../hooks/media/useMediaPlayTimeCallback.ts | 2 +- src/app/hooks/media/useMediaPlaybackRate.ts | 4 +- src/app/hooks/media/useMediaSeek.ts | 4 +- src/app/hooks/media/useMediaVolume.ts | 6 +- src/app/hooks/types.ts | 2 +- src/app/hooks/useAccountData.ts | 4 +- src/app/hooks/useAccountDataCallback.ts | 2 +- src/app/hooks/useAccountManagement.ts | 2 +- src/app/hooks/useAsyncCallback.ts | 8 +- src/app/hooks/useAsyncSearch.ts | 14 +- src/app/hooks/useAuthenticatedMediaUrl.ts | 4 +- src/app/hooks/useAutoJoinSpaceRooms.ts | 27 +- src/app/hooks/useBackRoute.ts | 13 +- src/app/hooks/useCategoryHandler.ts | 2 +- src/app/hooks/useCommands.ts | 22 +- src/app/hooks/useComposingCheck.ts | 4 +- src/app/hooks/useDateFormat.ts | 2 +- src/app/hooks/useDebounce.ts | 4 +- src/app/hooks/useDeviceList.ts | 12 +- src/app/hooks/useDeviceVerificationStatus.ts | 14 +- src/app/hooks/useElementSizeObserver.ts | 6 +- src/app/hooks/useEmailNotifications.ts | 6 +- src/app/hooks/useEmojiUsage.ts | 4 +- src/app/hooks/useFileDrop.ts | 4 +- src/app/hooks/useFilePasteHandler.ts | 2 +- src/app/hooks/useFilePicker.ts | 4 +- src/app/hooks/useForceUpdate.js | 10 +- src/app/hooks/useGetRoom.ts | 2 +- src/app/hooks/useImagePackRooms.ts | 2 +- src/app/hooks/useImagePacks.ts | 28 +- src/app/hooks/useInertialHorizontalScroll.ts | 269 +++--- src/app/hooks/useIntersectionObserver.ts | 4 +- src/app/hooks/useInterval.ts | 2 +- src/app/hooks/useJoinedRoomId.ts | 4 +- src/app/hooks/useKeyBackup.ts | 18 +- src/app/hooks/useMarkAsRead.ts | 4 +- src/app/hooks/useMatrixEventRenderer.ts | 2 +- src/app/hooks/useMemberEventParser.tsx | 2 +- src/app/hooks/useMemberFilter.ts | 4 +- src/app/hooks/useMemberPowerCompare.ts | 2 +- src/app/hooks/useMemberPowerTag.ts | 12 +- src/app/hooks/useMemberSort.ts | 6 +- src/app/hooks/useMembership.ts | 4 +- src/app/hooks/useMentionClickHandler.ts | 2 +- src/app/hooks/useMessageLayout.ts | 2 +- src/app/hooks/useMessageSpacing.ts | 2 +- src/app/hooks/useMutualRooms.ts | 4 +- src/app/hooks/useNotificationMode.ts | 10 +- src/app/hooks/useObjectURL.ts | 2 +- src/app/hooks/usePan.ts | 2 +- src/app/hooks/useParsedLoginFlows.ts | 5 +- src/app/hooks/usePasswordEmail.ts | 4 +- src/app/hooks/usePowerLevelTags.ts | 2 +- src/app/hooks/usePowerLevels.ts | 12 +- src/app/hooks/usePushRule.ts | 6 +- src/app/hooks/useRegisterEmail.ts | 4 +- src/app/hooks/useRelations.ts | 2 +- src/app/hooks/useResizeObserver.ts | 4 +- .../hooks/useRestoreBackupOnVerification.ts | 2 +- src/app/hooks/useRoomAliases.ts | 24 +- src/app/hooks/useRoomCreators.ts | 2 +- src/app/hooks/useRoomDirectoryVisibility.ts | 6 +- src/app/hooks/useRoomEmbedFilters.ts | 12 +- src/app/hooks/useRoomEvent.ts | 2 +- src/app/hooks/useRoomEventReaders.ts | 2 +- src/app/hooks/useRoomListReorder.ts | 18 +- src/app/hooks/useRoomMediaEvents.ts | 17 +- src/app/hooks/useRoomNavigate.ts | 6 +- src/app/hooks/useRoomPermissions.ts | 6 +- src/app/hooks/useRoomSubRooms.ts | 6 +- src/app/hooks/useRoomTypingMembers.ts | 2 +- src/app/hooks/useRoomUploadFiles.ts | 13 +- .../hooks/useRoomsNotificationPreferences.ts | 14 +- src/app/hooks/useScreenSize.ts | 2 +- src/app/hooks/useSidebarItems.ts | 45 +- src/app/hooks/useSpaceHierarchy.ts | 54 +- src/app/hooks/useStateEvent.ts | 6 +- src/app/hooks/useStateEventCallback.ts | 2 +- src/app/hooks/useStateEvents.ts | 6 +- src/app/hooks/useSyncState.ts | 2 +- src/app/hooks/useTextAreaCodeEditor.ts | 2 +- src/app/hooks/useTextAreaIntent.ts | 4 +- src/app/hooks/useTheme.ts | 83 +- src/app/hooks/useThrottle.ts | 4 +- src/app/hooks/useTimeoutToggle.ts | 2 +- src/app/hooks/useUIAFlows.ts | 6 +- src/app/hooks/useUserBanner.ts | 4 +- src/app/hooks/useUserCollectibles.ts | 11 +- src/app/hooks/useUserColor.ts | 18 +- src/app/hooks/useUserPresence.ts | 2 +- src/app/hooks/useUserProfile.ts | 6 +- src/app/hooks/useUserTrustStatusChange.ts | 2 +- src/app/hooks/useUserTypingVerb.ts | 4 +- src/app/hooks/useVerificationRequest.ts | 12 +- src/app/hooks/useViewTransitions.ts | 14 +- src/app/hooks/useVirtualPaginator.ts | 32 +- src/app/paarrot-api.ts | 228 +++-- src/app/pages/Router.tsx | 21 +- src/app/pages/auth/AuthFooter.tsx | 8 +- src/app/pages/auth/AuthLayout.tsx | 8 +- src/app/pages/auth/FiledError.tsx | 1 + src/app/pages/auth/SSOLogin.tsx | 4 +- src/app/pages/auth/ServerPicker.tsx | 2 +- src/app/pages/auth/login/Login.tsx | 4 +- .../pages/auth/login/PasswordLoginForm.tsx | 19 +- src/app/pages/auth/login/TokenLogin.tsx | 2 +- src/app/pages/auth/login/loginUtil.ts | 25 +- .../auth/register/PasswordRegisterForm.tsx | 2 +- src/app/pages/auth/register/Register.tsx | 2 +- src/app/pages/auth/register/registerUtil.ts | 4 +- .../auth/reset-password/PasswordResetForm.tsx | 4 +- .../auth/reset-password/ResetPassword.tsx | 4 +- .../auth/reset-password/resetPasswordUtil.ts | 4 +- src/app/pages/client/ClientNonUIFeatures.tsx | 70 +- src/app/pages/client/ClientRoot.tsx | 197 ++-- src/app/pages/client/SyncStatus.tsx | 2 +- src/app/pages/client/WelcomePage.tsx | 8 +- src/app/pages/client/direct/Direct.tsx | 114 ++- src/app/pages/client/direct/RoomProvider.tsx | 5 +- src/app/pages/client/explore/Explore.tsx | 18 +- src/app/pages/client/explore/Featured.tsx | 2 +- src/app/pages/client/explore/Server.tsx | 26 +- src/app/pages/client/home/Home.tsx | 232 ++--- .../pages/client/home/HomeThreadsCategory.tsx | 48 +- src/app/pages/client/inbox/Inbox.tsx | 10 +- src/app/pages/client/inbox/Invites.tsx | 39 +- src/app/pages/client/inbox/Notifications.tsx | 62 +- src/app/pages/client/sidebar/CreateTab.tsx | 4 +- src/app/pages/client/sidebar/DirectTab.tsx | 22 +- src/app/pages/client/sidebar/ExploreTab.tsx | 2 +- src/app/pages/client/sidebar/HomeTab.tsx | 15 +- src/app/pages/client/sidebar/InboxTab.tsx | 4 +- src/app/pages/client/sidebar/SearchTab.tsx | 2 +- src/app/pages/client/sidebar/SettingsTab.tsx | 28 +- src/app/pages/client/sidebar/SpaceTabs.tsx | 89 +- .../pages/client/sidebar/UnverifiedTab.tsx | 4 +- src/app/pages/client/space/RoomProvider.tsx | 11 +- src/app/pages/client/space/Search.tsx | 4 +- src/app/pages/client/space/Space.tsx | 57 +- src/app/pages/pathSearchParam.ts | 2 +- src/app/pages/pathUtils.ts | 6 +- src/app/plugins/bad-words.ts | 4 +- .../plugins/custom-emoji/PackMetaReader.ts | 2 +- src/app/plugins/custom-emoji/utils.ts | 3 +- src/app/plugins/markdown/block/runner.ts | 2 +- src/app/plugins/markdown/block/type.ts | 2 +- src/app/plugins/markdown/inline/rules.ts | 12 +- src/app/plugins/markdown/inline/runner.ts | 4 +- src/app/plugins/markdown/internal/utils.ts | 2 +- src/app/plugins/markdown/utils.ts | 6 +- src/app/plugins/matrix-to.ts | 2 +- src/app/plugins/pdfjs-dist.ts | 8 +- src/app/plugins/react-custom-html-parser.tsx | 80 +- src/app/plugins/text-area/mods/Intent.ts | 4 +- src/app/plugins/via-servers.ts | 2 +- src/app/state/activeThread.ts | 2 +- src/app/state/backupRestore.ts | 2 +- src/app/state/closedLobbyCategories.ts | 8 +- src/app/state/closedNavCategories.ts | 8 +- src/app/state/hooks/createRoomModal.ts | 4 +- src/app/state/hooks/createSpaceModal.ts | 2 +- src/app/state/hooks/inviteList.ts | 16 +- src/app/state/hooks/roomList.ts | 48 +- src/app/state/hooks/roomSettings.ts | 2 +- src/app/state/hooks/settings.ts | 7 +- src/app/state/hooks/spaceSettings.ts | 2 +- src/app/state/hooks/unread.ts | 6 +- src/app/state/hooks/userRoomProfile.ts | 4 +- src/app/state/joiningProgress.ts | 2 +- src/app/state/list.ts | 17 +- src/app/state/mDirectList.ts | 2 +- src/app/state/mediaDimensionCache.ts | 26 +- src/app/state/navToActivePath.ts | 8 +- src/app/state/openedSidebarFolder.ts | 8 +- src/app/state/releaseNotes.ts | 2 +- src/app/state/room-list/inviteList.ts | 6 +- src/app/state/room-list/roomList.ts | 4 +- src/app/state/room-list/utils.ts | 2 +- src/app/state/room/roomInputDrafts.ts | 8 +- src/app/state/room/roomToParents.ts | 8 +- src/app/state/room/roomToUnread.ts | 32 +- src/app/state/sessions.ts | 24 +- src/app/state/settings.ts | 12 +- src/app/state/spaceRooms.ts | 8 +- src/app/state/typingMembers.ts | 22 +- src/app/state/upload.ts | 10 +- src/app/state/utils/atomWithLocalStorage.ts | 4 +- src/app/utils/ASCIILexicalTable.ts | 10 +- src/app/utils/AsyncSearch.ts | 8 +- src/app/utils/androidShare.ts | 11 +- src/app/utils/animatedStickerConverter.ts | 17 +- src/app/utils/auth.ts | 16 +- src/app/utils/authenticatedMediaCache.ts | 5 +- src/app/utils/backgroundSync.ts | 52 +- src/app/utils/blurHash.ts | 2 +- src/app/utils/collectibleAssets.ts | 23 +- src/app/utils/common.ts | 28 +- src/app/utils/copyHandler.ts | 38 +- src/app/utils/discordCollectibles.ts | 21 +- src/app/utils/disposable.ts | 6 +- src/app/utils/dom.ts | 16 +- src/app/utils/emoticonConverter.ts | 62 +- src/app/utils/findAndReplace.ts | 4 +- src/app/utils/fuzzy.ts | 7 +- src/app/utils/gifMetadata.ts | 115 +-- src/app/utils/imageMetadata.ts | 90 +- src/app/utils/jpegMetadata.ts | 110 +-- src/app/utils/matrix-crypto.ts | 2 +- src/app/utils/matrix-uia.ts | 2 +- src/app/utils/matrix.ts | 42 +- src/app/utils/notifications.ts | 2 +- src/app/utils/pngMetadata.ts | 171 ++-- src/app/utils/profileAssetCache.ts | 2 +- src/app/utils/profileFields.ts | 52 +- src/app/utils/regex.ts | 2 +- src/app/utils/registerDesktopMediaSaver.ts | 10 +- src/app/utils/room.ts | 49 +- src/app/utils/saveMedia.ts | 2 +- src/app/utils/tauri.ts | 79 +- src/app/utils/telegramStickerImport.ts | 86 +- src/app/utils/viewTransitions.ts | 6 +- src/app/utils/webpMetadata.ts | 85 +- src/client/initMatrix.ts | 170 ++-- src/colors.css.ts | 1 - src/ext.d.ts | 25 +- src/index.css | 222 ++--- src/index.tsx | 6 +- src/playground/App.tsx | 16 +- src/playground/LivePreview.tsx | 5 +- src/playground/ResizableStage.tsx | 18 +- src/playground/catalog.ts | 7 +- src/playground/defaultLive.tsx | 2 +- src/playground/liveClient.ts | 6 +- src/playground/main.tsx | 2 +- src/playground/mocks/PlaygroundProviders.tsx | 5 +- src/playground/mocks/index.ts | 8 +- src/playground/mocks/matrix.ts | 30 +- src/playground/styles.css | 13 +- src/playground/usePlaygroundMatrix.ts | 7 +- src/sw.ts | 2 +- src/types/gif.js.d.ts | 10 +- src/types/matrix/common.ts | 3 +- src/types/matrix/room.ts | 9 +- src/util/colorMXID.js | 67 +- src/util/cryptE2ERoomKeys.js | 79 +- vanillaExtractIdentifiers.js | 2 +- vite.config.js | 34 +- ....timestamp-1771641468415-046b313db8c4b.mjs | 165 ---- ....timestamp-1771641863062-566dfacb5223d.mjs | 165 ---- ....timestamp-1771642098574-00e5d9a55dc42.mjs | 165 ---- ....timestamp-1771642338922-3a8734296d3bf.mjs | 165 ---- ....timestamp-1771642553007-3bf56500344a6.mjs | 165 ---- 605 files changed, 11480 insertions(+), 9125 deletions(-) delete mode 100644 vite.config.js.timestamp-1771641468415-046b313db8c4b.mjs delete mode 100644 vite.config.js.timestamp-1771641863062-566dfacb5223d.mjs delete mode 100644 vite.config.js.timestamp-1771642098574-00e5d9a55dc42.mjs delete mode 100644 vite.config.js.timestamp-1771642338922-3a8734296d3bf.mjs delete mode 100644 vite.config.js.timestamp-1771642553007-3bf56500344a6.mjs diff --git a/.gitignore b/.gitignore index 3ab2eff5..1dd0e67a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ devAssets .DS_Store .idea .cache + +# Vite build artifacts +vite.config.js.timestamp-* diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index f1ef5d46..37a7e9c8 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -17,23 +17,23 @@ diverse, inclusive, and healthy community. Examples of behavior that contributes to a positive environment for our community include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or +- The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities @@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an +standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within diff --git a/config.json b/config.json index 2272551b..319140a8 100644 --- a/config.json +++ b/config.json @@ -11,10 +11,8 @@ "allowCustomHomeservers": true, "featuredCommunities": { "openAsDefault": false, - "spaces": [ - ], - "rooms": [ - ], + "spaces": [], + "rooms": [], "servers": [] }, diff --git a/docs/API-QUICKSTART.md b/docs/API-QUICKSTART.md index b92fa26c..b6f94e6a 100644 --- a/docs/API-QUICKSTART.md +++ b/docs/API-QUICKSTART.md @@ -11,6 +11,7 @@ The API server starts automatically when you run Paarrot. It listens on `http:// **Option 1: Using Postman** Import the Postman collection for easy testing: + 1. Open Postman 2. Click **Import** → **File** 3. Select `paarrot-api.postman_collection.json` @@ -19,16 +20,19 @@ Import the Postman collection for easy testing: The collection is automatically updated on git push. **Option 2: Using the test script** + ```bash node test-api.js ``` **Option 3: Using curl** + ```bash ./test-api.sh ``` **Option 4: Manual curl commands** + ```bash # Health check curl http://127.0.0.1:33384/health @@ -46,22 +50,22 @@ curl -X POST http://127.0.0.1:33384/message/current \ ### Common Endpoints -| Endpoint | Method | Description | -|----------|--------|-------------| -| `/health` | GET | Check if API is running | -| `/status` | GET | Get app status (mute, deafen, etc.) | -| `/mute/toggle` | POST | Toggle microphone mute | -| `/deafen/toggle` | POST | Toggle deafen | -| `/channels` | GET | Get list of rooms | -| `/channel` | POST | Switch to a room | -| `/message/current` | POST | Send message to current room | -| `/room/current` | GET | Get current room info | -| `/messages/groups` | GET | Last N messages across groups (`?limit=10`) | -| `/messages/dms` | GET | Last N messages across DMs (`?limit=10`) | -| `/messages/combined` | GET | Last N messages across groups + DMs (`?limit=10`) | -| `/unreads/groups` | GET | Unread group conversations | -| `/unreads/dms` | GET | Unread DM conversations | -| `/unreads/combined` | GET | Unread groups + DMs | +| Endpoint | Method | Description | +| -------------------- | ------ | ------------------------------------------------- | +| `/health` | GET | Check if API is running | +| `/status` | GET | Get app status (mute, deafen, etc.) | +| `/mute/toggle` | POST | Toggle microphone mute | +| `/deafen/toggle` | POST | Toggle deafen | +| `/channels` | GET | Get list of rooms | +| `/channel` | POST | Switch to a room | +| `/message/current` | POST | Send message to current room | +| `/room/current` | GET | Get current room info | +| `/messages/groups` | GET | Last N messages across groups (`?limit=10`) | +| `/messages/dms` | GET | Last N messages across DMs (`?limit=10`) | +| `/messages/combined` | GET | Last N messages across groups + DMs (`?limit=10`) | +| `/unreads/groups` | GET | Unread group conversations | +| `/unreads/dms` | GET | Unread DM conversations | +| `/unreads/combined` | GET | Unread groups + DMs | ## 🎮 Stream Deck Integration @@ -69,10 +73,12 @@ curl -X POST http://127.0.0.1:33384/message/current \ 2. Create buttons with these settings: **Mute Toggle Button:** + - URL: `http://127.0.0.1:33384/mute/toggle` - Method: POST **Quick Message Button:** + - URL: `http://127.0.0.1:33384/message/current` - Method: POST - Body: `{"message": "BRB!"}` @@ -82,6 +88,7 @@ curl -X POST http://127.0.0.1:33384/message/current \ To enable full functionality, you need to implement the action handlers in the Cinny frontend: 1. Import the API handler in your app initialization: + ```typescript import { initPaarrotAPI } from './app/paarrot-api'; @@ -98,6 +105,7 @@ initPaarrotAPI(matrixClient); ## 📖 Full Documentation See [API.md](API.md) for complete API documentation including: + - All available endpoints - Request/response formats - Error handling @@ -107,6 +115,7 @@ See [API.md](API.md) for complete API documentation including: ## 🛠️ Configuration Edit `electron/api-server.js` to customize: + - Port number (default: 33384) - Timeout duration (default: 10s) - CORS settings @@ -114,11 +123,13 @@ Edit `electron/api-server.js` to customize: ## 🐛 Troubleshooting **API not responding:** + 1. Check if Paarrot is running 2. Look for "Paarrot API server listening" in console logs 3. Verify port 33384 is not in use: `lsof -i :33384` **Actions not working:** + 1. Check browser console for errors 2. Ensure `initPaarrotAPI()` is called in your app 3. Implement the TODO items in `paarrot-api.ts` @@ -144,6 +155,7 @@ Edit `electron/api-server.js` and change the port number in the constructor. ## 💡 Examples **Python Script:** + ```python import requests @@ -155,12 +167,13 @@ toggle_mute() ``` **JavaScript:** + ```javascript async function sendQuickMessage(msg) { const res = await fetch('http://127.0.0.1:33384/message/current', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message: msg }) + body: JSON.stringify({ message: msg }), }); return res.json(); } diff --git a/docs/API.md b/docs/API.md index 98ebae56..82d10a50 100644 --- a/docs/API.md +++ b/docs/API.md @@ -22,6 +22,7 @@ Check if the API server is running. **Endpoint**: `GET /health` **Response**: + ```json { "status": "ok", @@ -39,6 +40,7 @@ Get the current status of the app (mute, deafen, current room, etc.). **Endpoint**: `GET /status` **Response**: + ```json { "success": true, @@ -60,6 +62,7 @@ Set the mute status. **Endpoint**: `POST /mute` **Request Body**: + ```json { "muted": true @@ -67,6 +70,7 @@ Set the mute status. ``` **Response**: + ```json { "success": true, @@ -85,6 +89,7 @@ Toggle the current mute status. **Endpoint**: `POST /mute/toggle` **Response**: + ```json { "success": true, @@ -103,6 +108,7 @@ Set the deafen status (deafening also mutes). **Endpoint**: `POST /deafen` **Request Body**: + ```json { "deafened": true @@ -110,6 +116,7 @@ Set the deafen status (deafening also mutes). ``` **Response**: + ```json { "success": true, @@ -128,6 +135,7 @@ Toggle the current deafen status. **Endpoint**: `POST /deafen/toggle` **Response**: + ```json { "success": true, @@ -146,6 +154,7 @@ Switch to a different Matrix room. **Endpoint**: `POST /channel` **Request Body**: + ```json { "roomId": "!abc123:matrix.org" @@ -153,6 +162,7 @@ Switch to a different Matrix room. ``` **Response**: + ```json { "success": true, @@ -172,6 +182,7 @@ Get a list of available rooms/channels. **Endpoint**: `GET /channels` **Response**: + ```json { "success": true, @@ -212,6 +223,7 @@ Send a message to a specific room. **Endpoint**: `POST /message` **Request Body**: + ```json { "roomId": "!abc123:matrix.org", @@ -220,6 +232,7 @@ Send a message to a specific room. ``` **Response**: + ```json { "success": true, @@ -239,6 +252,7 @@ Send a message to the currently active room. **Endpoint**: `POST /message/current` **Request Body**: + ```json { "message": "Hello from the API!" @@ -246,6 +260,7 @@ Send a message to the currently active room. ``` **Response**: + ```json { "success": true, @@ -265,6 +280,7 @@ Get information about the currently active room. **Endpoint**: `GET /room/current` **Response**: + ```json { "success": true, @@ -287,9 +303,11 @@ Get the most recent messages across joined group channels (non-DMs). **Endpoint**: `GET /messages/groups` **Query Parameters**: + - `limit` (optional) — number of messages to return (1–100, default `10`) **Response**: + ```json { "success": true, @@ -323,6 +341,7 @@ Get the most recent messages across joined direct messages. **Endpoint**: `GET /messages/dms` **Query Parameters**: + - `limit` (optional) — number of messages to return (1–100, default `10`) **Response**: same shape as groups, with `"scope": "dms"`. @@ -336,6 +355,7 @@ Get the most recent messages across groups and DMs together. **Endpoint**: `GET /messages/combined` **Query Parameters**: + - `limit` (optional) — number of messages to return (1–100, default `10`) **Response**: same shape as groups, with `"scope": "combined"`. @@ -349,6 +369,7 @@ List joined group channels that currently have unread activity. **Endpoint**: `GET /unreads/groups` **Response**: + ```json { "success": true, @@ -409,6 +430,7 @@ All endpoints return error responses in the following format: ``` Common HTTP status codes: + - `200 OK` - Request successful - `400 Bad Request` - Missing or invalid parameters - `404 Not Found` - Endpoint not found @@ -443,7 +465,7 @@ const fetch = require('node-fetch'); // Toggle mute async function toggleMute() { const response = await fetch('http://127.0.0.1:33384/mute/toggle', { - method: 'POST' + method: 'POST', }); const data = await response.json(); console.log('Muted:', data.data.muted); @@ -454,9 +476,9 @@ async function sendMessage(roomId, message) { const response = await fetch('http://127.0.0.1:33384/message', { method: 'POST', headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }, - body: JSON.stringify({ roomId, message }) + body: JSON.stringify({ roomId, message }), }); const data = await response.json(); console.log('Message sent:', data.data.eventId); @@ -499,14 +521,17 @@ To integrate with Stream Deck: Example configurations: **Mute Toggle Button**: + - URL: `http://127.0.0.1:33384/mute/toggle` - Method: POST **Deafen Toggle Button**: + - URL: `http://127.0.0.1:33384/deafen/toggle` - Method: POST **Send Quick Message**: + - URL: `http://127.0.0.1:33384/message/current` - Method: POST - Body: `{"message": "BRB!"}` @@ -524,82 +549,80 @@ Add this to your app initialization: ```typescript // Listen for API actions from the Electron API server if (window.electron?.api?.onAction) { - window.electron.api.onAction(async (action: { - action: string; - params: any; - responseChannel: string; - }) => { - try { - let result; - - switch (action.action) { - case 'toggle-mute': - // Toggle microphone mute - result = await toggleMicrophone(); - break; - - case 'set-mute': - // Set microphone mute state - result = await setMicrophone(action.params.muted); - break; - - case 'toggle-deafen': - // Toggle deafen (mute speakers) - result = await toggleDeafen(); - break; - - case 'set-deafen': - // Set deafen state - result = await setDeafen(action.params.deafened); - break; - - case 'change-channel': - // Navigate to a different room - result = await changeRoom(action.params.roomId); - break; - - case 'get-channels': - // Get list of rooms - result = await getRoomList(); - break; - - case 'send-message': - // Send message to specific room - result = await sendMessage(action.params.roomId, action.params.message); - break; - - case 'send-message-current': - // Send message to current room - result = await sendMessageToCurrent(action.params.message); - break; - - case 'get-current-room': - // Get current room info - result = await getCurrentRoomInfo(); - break; - - case 'get-status': - // Get current app status - result = await getAppStatus(); - break; - - default: - throw new Error(`Unknown action: ${action.action}`); + window.electron.api.onAction( + async (action: { action: string; params: any; responseChannel: string }) => { + try { + let result; + + switch (action.action) { + case 'toggle-mute': + // Toggle microphone mute + result = await toggleMicrophone(); + break; + + case 'set-mute': + // Set microphone mute state + result = await setMicrophone(action.params.muted); + break; + + case 'toggle-deafen': + // Toggle deafen (mute speakers) + result = await toggleDeafen(); + break; + + case 'set-deafen': + // Set deafen state + result = await setDeafen(action.params.deafened); + break; + + case 'change-channel': + // Navigate to a different room + result = await changeRoom(action.params.roomId); + break; + + case 'get-channels': + // Get list of rooms + result = await getRoomList(); + break; + + case 'send-message': + // Send message to specific room + result = await sendMessage(action.params.roomId, action.params.message); + break; + + case 'send-message-current': + // Send message to current room + result = await sendMessageToCurrent(action.params.message); + break; + + case 'get-current-room': + // Get current room info + result = await getCurrentRoomInfo(); + break; + + case 'get-status': + // Get current app status + result = await getAppStatus(); + break; + + default: + throw new Error(`Unknown action: ${action.action}`); + } + + // Send success response back + window.electron.api.sendResponse(action.responseChannel, { + success: true, + data: result, + }); + } catch (error) { + // Send error response back + window.electron.api.sendResponse(action.responseChannel, { + success: false, + error: error.message, + }); } - - // Send success response back - window.electron.api.sendResponse(action.responseChannel, { - success: true, - data: result - }); - } catch (error) { - // Send error response back - window.electron.api.sendResponse(action.responseChannel, { - success: false, - error: error.message - }); - } - }); + }, + ); } ``` @@ -627,16 +650,19 @@ The API server can be configured by modifying `electron/api-server.js`: ## Troubleshooting **API server not starting**: + - Check if port 33384 is already in use - Check console logs for errors - Verify Express is installed: `npm install express cors body-parser` **Actions not working**: + - Ensure the client-side handler is implemented - Check browser console for errors - Verify the action names match between API server and client **Timeout errors**: + - Actions must respond within 10 seconds - Check if the Matrix client is initialized - Verify the action handler is registered @@ -646,6 +672,7 @@ The API server can be configured by modifying `electron/api-server.js`: ## Future Enhancements Potential features to add: + - WebSocket support for real-time events - Authentication with API keys - Voice channel controls (join/leave) diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 7a218448..de098216 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -5,6 +5,7 @@ The Paarrot desktop client includes a powerful plugin system that allows you to ## What are Plugins? Plugins are small JavaScript modules that run inside Paarrot and can: + - Add custom commands - Modify the UI - React to Matrix events @@ -53,6 +54,7 @@ Use the search bar to filter plugins by name, description, author, or tags. ⚠️ **Important Security Information** Plugins run with access to your Matrix client and can: + - Read your messages - Send messages on your behalf - Access your room list @@ -79,6 +81,7 @@ Want to create your own plugin? Check out the [Plugin API Reference](docs/PLUGIN - `plugin-metadata.json` - Plugin information 2. Implement the plugin interface: + ```javascript module.exports = { onLoad: async (context) => { @@ -87,7 +90,7 @@ module.exports = { }, onUnload: async () => { // Cleanup when disabled - } + }, }; ``` @@ -98,6 +101,7 @@ module.exports = { ## Plugin API Plugins have access to: + - **Matrix Client**: Full matrix-js-sdk client instance - **React**: For building UI components - **Commands**: Register custom slash commands @@ -134,6 +138,7 @@ Check out the `example-plugin/` directory for a simple example, or the `plugins/ ### Performance Issues If Paarrot becomes slow: + 1. Disable plugins one by one to identify the culprit 2. Check for memory leaks in the console 3. Contact the plugin author with details diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md index 7c8764bf..124dbe9b 100644 --- a/docs/PLUGIN_API.md +++ b/docs/PLUGIN_API.md @@ -27,6 +27,7 @@ Complete reference for developing plugins for Paarrot/Cinny Desktop. ### Plugin Location Plugins are installed in: + - **Windows**: `%APPDATA%\paarrot\plugins\\` - **Linux**: `~/.config/Paarrot/plugins//` - **macOS**: `~/Library/Application Support/Paarrot/plugins//` @@ -59,38 +60,38 @@ Plugins are installed in: ```javascript module.exports = { - name: "My Plugin", - version: "1.0.0", + name: 'My Plugin', + version: '1.0.0', dependencies: { // "other-plugin": "^1.0.0" }, - + /** * Called when plugin loads * @param {PluginContext} ctx - Plugin context */ onLoad: async (ctx) => { ctx.log('Plugin loaded!'); - + // Initialize your plugin here ctx.commands.register({ - name: "hello", - description: "Say hello", - run: () => "Hello, world!" + name: 'hello', + description: 'Say hello', + run: () => 'Hello, world!', }); }, - + /** * Called when plugin unloads */ onUnload: async () => { console.log('Plugin unloaded'); }, - + /** * API for other plugins */ - exports: null + exports: null, }; ``` @@ -106,7 +107,7 @@ interface PluginContext { matrixClient: MatrixClient; React: typeof import('react'); lucide: typeof import('lucide-react'); - + commands: CommandsAPI; messages: MessagesAPI; ui: UIAPI; @@ -129,54 +130,57 @@ Register slash commands that users can type in chat. ```javascript ctx.commands.register({ - name: "mycommand", - description: "Does something cool", - args: ["arg1", "arg2"], // Optional + name: 'mycommand', + description: 'Does something cool', + args: ['arg1', 'arg2'], // Optional run: (args) => { // Return string to send as message return `Got args: ${args.arg1}, ${args.arg2}`; - } + }, }); ``` #### Examples **Simple command:** + ```javascript ctx.commands.register({ - name: "shrug", - description: "Send a shrug emoji", - run: () => "¯\\_(ツ)_/¯" + name: 'shrug', + description: 'Send a shrug emoji', + run: () => '¯\\_(ツ)_/¯', }); // Usage: /shrug ``` **Command with arguments:** + ```javascript ctx.commands.register({ - name: "greet", - description: "Greet someone", - args: ["name"], - run: ({ name }) => `Hello, ${name || 'stranger'}!` + name: 'greet', + description: 'Greet someone', + args: ['name'], + run: ({ name }) => `Hello, ${name || 'stranger'}!`, }); // Usage: /greet Alice ``` **Advanced command:** + ```javascript ctx.commands.register({ - name: "calc", - description: "Simple calculator", - args: ["expression"], + name: 'calc', + description: 'Simple calculator', + args: ['expression'], run: ({ expression }) => { try { const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, ''); const result = Function(`'use strict'; return (${sanitized})`)(); return `${expression} = ${result}`; } catch (err) { - return "Invalid expression"; + return 'Invalid expression'; } - } + }, }); // Usage: /calc 2 + 2 * 3 ``` @@ -214,7 +218,7 @@ ctx.messages.onBeforeSend((msg) => { if (msg.content.includes('secret')) { msg.content = msg.content.replace(/secret/g, '█████'); } - + // Add prefix msg.content = `[Bot] ${msg.content}`; }); @@ -231,7 +235,7 @@ ctx.messages.onReceive((msg) => { ctx.notify({ title: 'Important Message', body: msg.content, - type: 'info' + type: 'info', }); } }); @@ -240,15 +244,16 @@ ctx.messages.onReceive((msg) => { #### Real-World Examples **Auto-expand abbreviations:** + ```javascript ctx.messages.onBeforeSend((msg) => { const expansions = { - 'brb': 'be right back', - 'omw': 'on my way', - 'gtg': 'got to go', - 'afk': 'away from keyboard' + brb: 'be right back', + omw: 'on my way', + gtg: 'got to go', + afk: 'away from keyboard', }; - + Object.entries(expansions).forEach(([abbr, full]) => { const regex = new RegExp(`\\b${abbr}\\b`, 'gi'); msg.content = msg.content.replace(regex, full); @@ -257,6 +262,7 @@ ctx.messages.onBeforeSend((msg) => { ``` **Add auto-shrug to questions:** + ```javascript ctx.messages.onBeforeSend((msg) => { if (msg.content.trim().endsWith('?')) { @@ -266,6 +272,7 @@ ctx.messages.onBeforeSend((msg) => { ``` **Track mentions:** + ```javascript ctx.messages.onReceive((msg) => { const userId = ctx.matrixClient.getUserId(); @@ -300,21 +307,25 @@ Register custom UI renderers for messages, images, and other content types. ```javascript // Custom message renderer -ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { +ctx.ui.registerRenderer('message', (msg, defaultRenderer) => { // Custom logic if (msg.sender?.includes('bot')) { // Return custom React component - return ctx.React.createElement('div', { - style: { background: 'yellow' } - }, msg.content); + return ctx.React.createElement( + 'div', + { + style: { background: 'yellow' }, + }, + msg.content, + ); } - + // Fall back to default return defaultRenderer?.(); }); // Custom image renderer -ctx.ui.registerRenderer("image", (data, defaultRenderer) => { +ctx.ui.registerRenderer('image', (data, defaultRenderer) => { // Add custom effects, borders, etc. return defaultRenderer?.(); }); @@ -328,14 +339,11 @@ interface UIAPI { unregisterButton(id: string): void; registerRenderer( type: string, - renderer: (data: any, defaultRenderer?: () => ReactNode) => ReactNode + renderer: (data: any, defaultRenderer?: () => ReactNode) => ReactNode, ): void; } -type CustomRenderer = ( - data: any, - defaultRenderer?: () => ReactNode -) => ReactNode; +type CustomRenderer = (data: any, defaultRenderer?: () => ReactNode) => ReactNode; ``` --- @@ -354,30 +362,30 @@ ctx.ui.registerButton({ location: 'text-composer-toolbar', label: 'My Tool', icon: '🔧', - onClick: () => ctx.log('clicked!') + onClick: () => ctx.log('clicked!'), }); ``` #### UI Locations — Nav List Rows -| Location | Where it appears | -|---|---| -| `channel-list` | Space channel list, below Lobby and Message Search | -| `home-section` | Home panel, inside the Rooms category above the room list | +| Location | Where it appears | +| ----------------- | ----------------------------------------------------------- | +| `channel-list` | Space channel list, below Lobby and Message Search | +| `home-section` | Home panel, inside the Rooms category above the room list | | `direct-messages` | DMs panel, below "Create Chat" and above the CHATS dropdown | #### UI Locations — Icon Buttons -| Location | Where it appears | -|---|---| -| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | -| `composer-actions` | Left side of the composer, beside the `+` attach button | -| `room-header` | Top room header bar, before the ⋮ menu | -| `room-menu` | Room ⋮ dropdown menu | -| `message-actions` | Message hover action bar | -| `user-menu` | Right-click popup on the user avatar | -| `search-notification-section` | Notifications page header (right side) | -| `sidebar-actions` | Left sidebar — above Explore Servers icon, and above Search icon in the sticky bottom section | +| Location | Where it appears | +| ----------------------------- | --------------------------------------------------------------------------------------------- | +| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | +| `composer-actions` | Left side of the composer, beside the `+` attach button | +| `room-header` | Top room header bar, before the ⋮ menu | +| `room-menu` | Room ⋮ dropdown menu | +| `message-actions` | Message hover action bar | +| `user-menu` | Right-click popup on the user avatar | +| `search-notification-section` | Notifications page header (right side) | +| `sidebar-actions` | Left sidebar — above Explore Servers icon, and above Search icon in the sticky bottom section | #### Positioning @@ -390,9 +398,9 @@ ctx.ui.registerButton({ position: { after: 'emoji-picker-button', group: 'my-tools', - order: 1 + order: 1, }, - onClick: () => ctx.log('clicked!') + onClick: () => ctx.log('clicked!'), }); ``` @@ -407,10 +415,17 @@ ctx.ui.unregisterButton('my-button'); ```typescript type UILocation = - | 'channel-list' | 'direct-messages' | 'home-section' - | 'text-composer-toolbar' | 'composer-actions' - | 'room-header' | 'room-menu' | 'message-actions' - | 'user-menu' | 'search-notification-section' | 'sidebar-actions'; + | 'channel-list' + | 'direct-messages' + | 'home-section' + | 'text-composer-toolbar' + | 'composer-actions' + | 'room-header' + | 'room-menu' + | 'message-actions' + | 'user-menu' + | 'search-notification-section' + | 'sidebar-actions'; interface UIButtonDefinition { id: string; @@ -443,47 +458,47 @@ Define settings that users can configure in the UI. ctx.settings.define({ // Boolean toggle enableFeature: { - type: "boolean", - label: "Enable Feature", - description: "Toggle this feature on/off", - default: true + type: 'boolean', + label: 'Enable Feature', + description: 'Toggle this feature on/off', + default: true, }, - + // String input apiKey: { - type: "string", - label: "API Key", - description: "Your API key", - default: "" + type: 'string', + label: 'API Key', + description: 'Your API key', + default: '', }, - + // Number input maxRetries: { - type: "number", - label: "Max Retries", - description: "Maximum retry attempts", - default: 3 + type: 'number', + label: 'Max Retries', + description: 'Maximum retry attempts', + default: 3, }, - + // Select dropdown theme: { - type: "select", - label: "Theme", - description: "Choose a theme", + type: 'select', + label: 'Theme', + description: 'Choose a theme', options: [ - { value: "dark", label: "Dark Mode" }, - { value: "light", label: "Light Mode" } + { value: 'dark', label: 'Dark Mode' }, + { value: 'light', label: 'Light Mode' }, ], - default: "dark" + default: 'dark', }, - + // Color picker accentColor: { - type: "color", - label: "Accent Color", - description: "Choose your accent color", - default: "#6366f1" - } + type: 'color', + label: 'Accent Color', + description: 'Choose your accent color', + default: '#6366f1', + }, }); ``` @@ -528,9 +543,9 @@ Register custom themes that appear in the theme selector dropdown. Themes use CS ```javascript ctx.themes.register({ - id: "my-theme", - name: "My Custom Theme", - kind: "dark", // "light" or "dark" + id: 'my-theme', + name: 'My Custom Theme', + kind: 'dark', // "light" or "dark" css: ` body.plugin-my-plugin-my-theme { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); @@ -543,7 +558,7 @@ ctx.themes.register({ .plugin-my-plugin-my-theme { --tc-link: hsl(213, 100%, 80%); } - ` + `, }); ``` @@ -563,6 +578,7 @@ Example: plugin ID `my-plugin` + theme ID `dark-blue` = `.plugin-my-plugin-dark- #### CSS Custom Properties Available CSS variables you can override: + - `--tc-link` - Link color - `--mx-uc-1` through `--mx-uc-8` - Matrix user ID colors (for different users) - `--font-emoji` - Emoji font family @@ -571,6 +587,7 @@ Available CSS variables you can override: #### Styling Elements Common selectors to style: + - `body.plugin-{pluginId}-{themeId}` - Body background - `.plugin-{pluginId}-{themeId} #root` - Main app container - `.plugin-{pluginId}-{themeId} [role="navigation"]` - Navigation sidebar @@ -582,11 +599,12 @@ Common selectors to style: #### Examples **Dark Theme with Gradients:** + ```javascript ctx.themes.register({ - id: "midnight", - name: "Midnight Blue 🌙", - kind: "dark", + id: 'midnight', + name: 'Midnight Blue 🌙', + kind: 'dark', css: ` body.plugin-my-plugin-midnight { background: linear-gradient(135deg, #0a192f 0%, #112240 50%, #1a365d 100%); @@ -613,16 +631,17 @@ ctx.themes.register({ .plugin-my-plugin-midnight { --tc-link: hsl(213, 100%, 80%); } - ` + `, }); ``` **Light Theme:** + ```javascript ctx.themes.register({ - id: "sunrise", - name: "Sunrise ☀️", - kind: "light", + id: 'sunrise', + name: 'Sunrise ☀️', + kind: 'light', css: ` body.plugin-my-plugin-sunrise { background: linear-gradient(135deg, #fff4e6 0%, #ffe0b2 50%, #ffcc80 100%); @@ -645,16 +664,17 @@ ctx.themes.register({ .plugin-my-plugin-sunrise { --tc-link: hsl(30, 100%, 40%); } - ` + `, }); ``` **Minimal Theme:** + ```javascript ctx.themes.register({ - id: "forest", - name: "Forest Green 🌲", - kind: "dark", + id: 'forest', + name: 'Forest Green 🌲', + kind: 'dark', css: ` body.plugin-my-plugin-forest { background: #1a2f23; @@ -671,14 +691,14 @@ ctx.themes.register({ --mx-uc-7: hsl(135, 60%, 70%); --mx-uc-8: hsl(155, 60%, 70%); } - ` + `, }); ``` #### Unregister Theme ```javascript -ctx.themes.unregister("my-theme"); +ctx.themes.unregister('my-theme'); ``` #### API Reference @@ -699,6 +719,7 @@ interface PluginTheme { ``` **Notes:** + - CSS is injected once when the plugin loads (not per theme change) - Theme IDs are automatically prefixed with `plugin-{pluginId}-` to avoid conflicts - Theme class names follow the pattern: `.plugin-{pluginId}-{themeId}` @@ -717,19 +738,19 @@ Hook into raw Matrix events for advanced functionality. ```javascript // Room messages -ctx.matrix.on("m.room.message", (event) => { +ctx.matrix.on('m.room.message', (event) => { const content = event.getContent(); ctx.log('Message:', content.body); }); // Membership changes -ctx.matrix.on("m.room.member", (event) => { +ctx.matrix.on('m.room.member', (event) => { const content = event.getContent(); ctx.log('Membership:', content.membership); }); // Timeline events -ctx.matrix.on("Room.timeline", (event) => { +ctx.matrix.on('Room.timeline', (event) => { if (event.getType() === 'm.room.message') { const sender = event.getSender(); ctx.log('Timeline event from:', sender); @@ -737,7 +758,7 @@ ctx.matrix.on("Room.timeline", (event) => { }); // Sync state -ctx.matrix.on("sync", (state, prevState) => { +ctx.matrix.on('sync', (state, prevState) => { ctx.log('Sync state:', state); }); ``` @@ -749,10 +770,10 @@ const handler = (event) => { ctx.log('Event received'); }; -ctx.matrix.on("m.room.message", handler); +ctx.matrix.on('m.room.message', handler); // Later... -ctx.matrix.off("m.room.message", handler); +ctx.matrix.off('m.room.message', handler); ``` #### API Reference @@ -765,6 +786,7 @@ interface MatrixEventsAPI { ``` **Common Event Types:** + - `m.room.message` - Room messages - `m.room.member` - Membership changes - `m.room.name` - Room name changes @@ -784,11 +806,11 @@ Run periodic tasks or delayed actions. // Run every 30 seconds const intervalId = ctx.timers.setInterval(() => { ctx.log('Periodic task running'); - + // Do something periodically const stats = { timestamp: Date.now(), - setting: ctx.settings.get('theme') + setting: ctx.settings.get('theme'), }; ctx.log('Stats:', stats); }, 30000); @@ -805,9 +827,9 @@ const timeoutId = ctx.timers.setTimeout(() => { ctx.notify({ title: 'Reminder', body: 'This is a delayed notification', - type: 'info' + type: 'info', }); -}, 10000); // 10 seconds +}, 10000); // 10 seconds // Clear timeout ctx.timers.clearTimeout(timeoutId); @@ -844,8 +866,8 @@ ctx.notify('Hello, world!'); ctx.notify({ title: 'Plugin Alert', body: 'Something important happened!', - type: 'info', // 'info' | 'success' | 'error' | 'warning' - duration: 5000 // milliseconds (optional) + type: 'info', // 'info' | 'success' | 'error' | 'warning' + duration: 5000, // milliseconds (optional) }); ``` @@ -856,30 +878,28 @@ ctx.notify({ ctx.notify({ title: 'Success', body: 'Operation completed successfully!', - type: 'success' + type: 'success', }); // Error notification ctx.notify({ title: 'Error', body: 'Something went wrong', - type: 'error' + type: 'error', }); // Warning ctx.notify({ title: 'Warning', body: 'This action cannot be undone', - type: 'warning' + type: 'warning', }); ``` #### API Reference ```typescript -type NotificationFunction = ( - options: NotificationOptions | string -) => void; +type NotificationFunction = (options: NotificationOptions | string) => void; interface NotificationOptions { title: string; @@ -916,13 +936,14 @@ ctx.error('Error details:', errorObject); type LogFunction = (...args: any[]) => void; interface PluginContext { - log: LogFunction; // Info level - warn: LogFunction; // Warning level - error: LogFunction; // Error level + log: LogFunction; // Info level + warn: LogFunction; // Warning level + error: LogFunction; // Error level } ``` **Note:** All logs are visible in: + - Browser console (F12) - Plugin logs panel (Settings → Plugins → Logs) - coming soon @@ -937,21 +958,21 @@ Export functions and data for other plugins to use. ```javascript module.exports = { // ... onLoad, onUnload ... - + exports: { - version: "1.0.0", - + version: '1.0.0', + utils: { greet: (name) => `Hello, ${name}!`, - + processText: (text) => text.toUpperCase(), - + getStats: () => ({ - version: "1.0.0", - features: ['commands', 'settings'] - }) - } - } + version: '1.0.0', + features: ['commands', 'settings'], + }), + }, + }, }; ``` @@ -963,11 +984,11 @@ const otherPlugin = ctx.require('other-plugin-id'); if (otherPlugin) { const greeting = otherPlugin.utils.greet('World'); - ctx.log(greeting); // "Hello, World!" - + ctx.log(greeting); // "Hello, World!" + const processed = otherPlugin.utils.processText('hello'); - ctx.log(processed); // "HELLO" - + ctx.log(processed); // "HELLO" + const stats = otherPlugin.utils.getStats(); ctx.log('Stats:', stats); } @@ -1018,7 +1039,7 @@ ctx.log('Sync state:', syncState); // Send custom event await ctx.matrixClient.sendEvent(roomId, 'm.room.message', { msgtype: 'm.text', - body: 'Hello from plugin!' + body: 'Hello from plugin!', }); ``` @@ -1026,7 +1047,7 @@ await ctx.matrixClient.sendEvent(roomId, 'm.room.message', { ```typescript interface PluginContext { - matrixClient: MatrixClient; // Full Matrix.js SDK client + matrixClient: MatrixClient; // Full Matrix.js SDK client } ``` @@ -1043,122 +1064,122 @@ Here's a complete plugin that demonstrates all features: * Example Plugin - All Features */ module.exports = { - name: "Example Plugin", - version: "1.0.0", + name: 'Example Plugin', + version: '1.0.0', dependencies: {}, - + onLoad: async (ctx) => { ctx.log('🚀 Plugin loading...'); - + // === COMMANDS === ctx.commands.register({ - name: "hello", - description: "Say hello", - run: () => "Hello, world!" + name: 'hello', + description: 'Say hello', + run: () => 'Hello, world!', }); - + ctx.commands.register({ - name: "greet", - description: "Greet someone", - args: ["name"], - run: ({ name }) => `Hello, ${name}!` + name: 'greet', + description: 'Greet someone', + args: ['name'], + run: ({ name }) => `Hello, ${name}!`, }); - + // === INTERCEPTORS === ctx.messages.onBeforeSend((msg) => { // Auto-expand abbreviations msg.content = msg.content.replace(/\bbrb\b/gi, 'be right back'); - + // Add emoji if enabled if (ctx.settings.get('addEmoji')) { msg.content += ' ✨'; } }); - + ctx.messages.onReceive((msg) => { // Track keywords const keywords = ctx.settings.get('keywords') || ''; - keywords.split(',').forEach(keyword => { + keywords.split(',').forEach((keyword) => { if (msg.content.includes(keyword.trim())) { ctx.notify(`Keyword detected: ${keyword}`); } }); }); - + // === SETTINGS === ctx.settings.define({ addEmoji: { - type: "boolean", - label: "Add Emoji", - description: "Add sparkles to messages", - default: false + type: 'boolean', + label: 'Add Emoji', + description: 'Add sparkles to messages', + default: false, }, keywords: { - type: "string", - label: "Track Keywords", - description: "Comma-separated keywords to track", - default: "important,urgent" + type: 'string', + label: 'Track Keywords', + description: 'Comma-separated keywords to track', + default: 'important,urgent', }, theme: { - type: "select", - label: "Theme", + type: 'select', + label: 'Theme', options: [ - { value: "light", label: "Light" }, - { value: "dark", label: "Dark" } + { value: 'light', label: 'Light' }, + { value: 'dark', label: 'Dark' }, ], - default: "dark" - } + default: 'dark', + }, }); - + // === THEMES === ctx.themes.register({ - id: "example-theme", - name: "Example Theme", - kind: "dark", + id: 'example-theme', + name: 'Example Theme', + kind: 'dark', colors: { - background: "#1a1a2e", - surface: "#16213e", - primary: "#0f3460", - secondary: "#533483", - onBackground: "#ffffff", - onSurface: "#e0e0e0" - } + background: '#1a1a2e', + surface: '#16213e', + primary: '#0f3460', + secondary: '#533483', + onBackground: '#ffffff', + onSurface: '#e0e0e0', + }, }); - + // === MATRIX EVENTS === - ctx.matrix.on("m.room.message", (event) => { + ctx.matrix.on('m.room.message', (event) => { const content = event.getContent(); if (content.body?.includes('example')) { ctx.log('Keyword found in message'); } }); - + // === BACKGROUND TASKS === ctx.timers.setInterval(() => { ctx.log('Periodic check'); - }, 60000); // Every minute - + }, 60000); // Every minute + // === NOTIFICATIONS === ctx.notify({ title: 'Example Plugin', body: 'Plugin loaded successfully!', - type: 'success' + type: 'success', }); - + // === EXPORTS === this.exports = { - version: "1.0.0", - greet: (name) => `Hello, ${name}!` + version: '1.0.0', + greet: (name) => `Hello, ${name}!`, }; - + ctx.log('✅ Plugin loaded'); }, - + onUnload: async () => { console.log('Plugin unloaded'); }, - - exports: null + + exports: null, }; ``` @@ -1179,10 +1200,10 @@ onLoad: async (ctx) => { ctx.notify({ title: 'Plugin Error', body: error.message, - type: 'error' + type: 'error', }); } -} +}; ``` ### Cleanup @@ -1194,9 +1215,9 @@ onUnload: async () => { // Timers are auto-cleared // Event handlers are auto-removed // Settings are persisted automatically - + console.log('Plugin unloaded'); -} +}; ``` ### Settings Validation @@ -1205,7 +1226,7 @@ Validate settings before use: ```javascript const maxRetries = ctx.settings.get('maxRetries') || 3; -const keywords = (ctx.settings.get('keywords') || '').split(',').filter(k => k.trim()); +const keywords = (ctx.settings.get('keywords') || '').split(',').filter((k) => k.trim()); ``` ### Logging @@ -1213,9 +1234,9 @@ const keywords = (ctx.settings.get('keywords') || '').split(',').filter(k => k.t Use appropriate log levels: ```javascript -ctx.log('Info message'); // Normal operation -ctx.warn('Warning message'); // Potential issues -ctx.error('Error message'); // Actual errors +ctx.log('Info message'); // Normal operation +ctx.warn('Warning message'); // Potential issues +ctx.error('Error message'); // Actual errors ``` ### Performance diff --git a/docs/PLUGIN_BUTTON_API.md b/docs/PLUGIN_BUTTON_API.md index 8f53914c..5da0fa4d 100644 --- a/docs/PLUGIN_BUTTON_API.md +++ b/docs/PLUGIN_BUTTON_API.md @@ -15,26 +15,26 @@ Buttons render in two visual styles depending on location — **nav list rows** These render as full-width list entries matching the style of built-in items like "Create Room" and "Message Search": -| Location | Where it appears | -|---|---| -| `channel-list` | Space channel list, below Lobby and Message Search | -| `home-section` | Home panel, inside the Rooms category above the room list | +| Location | Where it appears | +| ----------------- | ----------------------------------------------------------------------- | +| `channel-list` | Space channel list, below Lobby and Message Search | +| `home-section` | Home panel, inside the Rooms category above the room list | | `direct-messages` | Direct Messages panel, below "Create Chat" and above the CHATS dropdown | ### Icon Buttons These render as compact icon buttons inline with other toolbar/header controls: -| Location | Where it appears | -|---|---| -| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | -| `composer-actions` | Left side of the composer, beside the `+` attach button | -| `room-header` | Top room header bar, before the ⋮ menu button | -| `room-menu` | Room ⋮ dropdown menu | -| `message-actions` | Message hover action bar | -| `user-menu` | Right-click popup on the user avatar | -| `search-notification-section` | Notifications page header (right side) | -| `sidebar-actions` | Left sidebar — appears in **two** places: above the Explore Servers icon, and above the Search icon in the sticky bottom section | +| Location | Where it appears | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | +| `composer-actions` | Left side of the composer, beside the `+` attach button | +| `room-header` | Top room header bar, before the ⋮ menu button | +| `room-menu` | Room ⋮ dropdown menu | +| `message-actions` | Message hover action bar | +| `user-menu` | Right-click popup on the user avatar | +| `search-notification-section` | Notifications page header (right side) | +| `sidebar-actions` | Left sidebar — appears in **two** places: above the Explore Servers icon, and above the Search icon in the sticky bottom section | > 💡 **Tip:** Install the [example-showcase-plugin](example-showcase-plugin/) to see exactly where each location appears in the UI! @@ -46,7 +46,7 @@ These render as compact icon buttons inline with other toolbar/header controls: module.exports = { name: 'my-plugin', version: '1.0.0', - + onLoad: (context) => { context.ui.registerButton({ id: 'my-button', @@ -55,13 +55,13 @@ module.exports = { icon: '🎨', onClick: () => { context.log('Button clicked!'); - } + }, }); }, - + onUnload: () => { // Buttons are automatically cleaned up on plugin unload - } + }, }; ``` @@ -80,8 +80,8 @@ context.ui.registerButton({ position: { before: 'emoji-picker-button', // Place before emoji picker // OR - after: 'sticker-button' // Place after sticker button - } + after: 'sticker-button', // Place after sticker button + }, }); ``` @@ -97,8 +97,8 @@ context.ui.registerButton({ icon: '1️⃣', position: { group: 'my-plugin-tools', - order: 1 // Lower numbers appear first - } + order: 1, // Lower numbers appear first + }, }); context.ui.registerButton({ @@ -108,8 +108,8 @@ context.ui.registerButton({ icon: '2️⃣', position: { group: 'my-plugin-tools', - order: 2 - } + order: 2, + }, }); ``` @@ -126,8 +126,8 @@ context.ui.registerButton({ position: { group: 'my-tools', after: 'emoji-picker-button', - order: 1 - } + order: 1, + }, }); context.ui.registerButton({ @@ -137,8 +137,8 @@ context.ui.registerButton({ icon: '🔨', position: { group: 'my-tools', - order: 2 - } + order: 2, + }, }); ``` @@ -148,7 +148,7 @@ context.ui.registerButton({ module.exports = { name: 'custom-tools', version: '1.0.0', - + onLoad: (context) => { // Nav list row — appears below "Create Chat" in the DMs panel context.ui.registerButton({ @@ -156,7 +156,7 @@ module.exports = { location: 'direct-messages', label: 'Favourites', icon: '⭐', - onClick: () => context.log('Favourites clicked!') + onClick: () => context.log('Favourites clicked!'), }); // Nav list row — appears in the space channel list @@ -165,7 +165,7 @@ module.exports = { location: 'channel-list', label: 'Quick Access', icon: '⚡', - onClick: () => context.log('Quick access clicked!') + onClick: () => context.log('Quick access clicked!'), }); // Icon button — appears in the message composer toolbar @@ -176,9 +176,9 @@ module.exports = { icon: '𝐁', position: { group: 'custom-formatting', - order: 1 + order: 1, }, - onClick: () => context.log('Bold clicked!') + onClick: () => context.log('Bold clicked!'), }); // Icon button — appears in the room header @@ -188,7 +188,7 @@ module.exports = { label: 'Special Search', icon: '🔍', position: { after: 'search-button' }, - onClick: () => context.log('Special search clicked!') + onClick: () => context.log('Special search clicked!'), }); // Sidebar icon — appears above Explore and above Search @@ -197,13 +197,13 @@ module.exports = { location: 'sidebar-actions', label: 'Plugin Panel', icon: '🧩', - onClick: () => context.log('Plugin panel clicked!') + onClick: () => context.log('Plugin panel clicked!'), }); }, - + onUnload: () => { // All registered buttons are automatically cleaned up - } + }, }; ``` @@ -228,13 +228,12 @@ const button: UIButtonDefinition = { position: { group: 'my-tools', after: 'emoji-picker', - order: 1 + order: 1, }, - onClick: () => console.log('Clicked!') + onClick: () => console.log('Clicked!'), }; ``` - ## Basic Usage ### Simple Button @@ -243,7 +242,7 @@ const button: UIButtonDefinition = { module.exports = { name: 'my-plugin', version: '1.0.0', - + onLoad: (context) => { context.ui.registerButton({ id: 'my-button', @@ -252,13 +251,13 @@ module.exports = { icon: '🎨', onClick: () => { context.log('Button clicked!'); - } + }, }); }, - + onUnload: () => { // Buttons are automatically cleaned up on plugin unload - } + }, }; ``` @@ -277,8 +276,8 @@ context.ui.registerButton({ position: { before: 'emoji-picker-button', // Place before emoji picker // OR - after: 'sticker-button' // Place after sticker button - } + after: 'sticker-button', // Place after sticker button + }, }); ``` @@ -294,8 +293,8 @@ context.ui.registerButton({ icon: '1️⃣', position: { group: 'my-plugin-tools', - order: 1 // Lower numbers appear first - } + order: 1, // Lower numbers appear first + }, }); context.ui.registerButton({ @@ -305,8 +304,8 @@ context.ui.registerButton({ icon: '2️⃣', position: { group: 'my-plugin-tools', - order: 2 - } + order: 2, + }, }); ``` @@ -323,8 +322,8 @@ context.ui.registerButton({ position: { group: 'my-tools', after: 'emoji-picker-button', - order: 1 - } + order: 1, + }, }); context.ui.registerButton({ @@ -334,8 +333,8 @@ context.ui.registerButton({ icon: '🔨', position: { group: 'my-tools', - order: 2 - } + order: 2, + }, }); ``` @@ -345,7 +344,7 @@ context.ui.registerButton({ module.exports = { name: 'custom-tools', version: '1.0.0', - + onLoad: (context) => { // Nav list row — appears below "Create Chat" in the DMs panel context.ui.registerButton({ @@ -353,7 +352,7 @@ module.exports = { location: 'direct-messages', label: 'Favourites', icon: '⭐', - onClick: () => context.log('Favourites clicked!') + onClick: () => context.log('Favourites clicked!'), }); // Nav list row — appears in the space channel list @@ -362,7 +361,7 @@ module.exports = { location: 'channel-list', label: 'Quick Access', icon: '⚡', - onClick: () => context.log('Quick access clicked!') + onClick: () => context.log('Quick access clicked!'), }); // Icon button — appears in the message composer toolbar @@ -373,9 +372,9 @@ module.exports = { icon: '𝐁', position: { group: 'custom-formatting', - order: 1 + order: 1, }, - onClick: () => context.log('Bold clicked!') + onClick: () => context.log('Bold clicked!'), }); // Icon button — appears in the room header @@ -385,7 +384,7 @@ module.exports = { label: 'Special Search', icon: '🔍', position: { after: 'search-button' }, - onClick: () => context.log('Special search clicked!') + onClick: () => context.log('Special search clicked!'), }); // Sidebar icon — appears above Explore and above Search @@ -394,13 +393,13 @@ module.exports = { location: 'sidebar-actions', label: 'Plugin Panel', icon: '🧩', - onClick: () => context.log('Plugin panel clicked!') + onClick: () => context.log('Plugin panel clicked!'), }); }, - + onUnload: () => { // All registered buttons are automatically cleaned up - } + }, }; ``` @@ -425,8 +424,8 @@ const button: UIButtonDefinition = { position: { group: 'my-tools', after: 'emoji-picker', - order: 1 + order: 1, }, - onClick: () => console.log('Clicked!') + onClick: () => console.log('Clicked!'), }; ``` diff --git a/docs/PLUGIN_SYSTEM_IMPLEMENTATION.md b/docs/PLUGIN_SYSTEM_IMPLEMENTATION.md index 28609418..422fb21e 100644 --- a/docs/PLUGIN_SYSTEM_IMPLEMENTATION.md +++ b/docs/PLUGIN_SYSTEM_IMPLEMENTATION.md @@ -5,18 +5,21 @@ All requested features have been implemented! 🎉 ## ✅ Implemented Features ### 1. ✅ Enhanced Slash Commands + - **Simple commands**: `ctx.commands.register({ name: "shrug", run: () => "¯\\_(ツ)_/¯" })` - **Commands with args**: `ctx.commands.register({ name: "echo", args: ["text"], run: ({ text }) => text })` - Automatic argument parsing - Execution API: `ctx.commands.execute(name, args)` ### 2. ✅ Message Interceptors + - **Before send**: `ctx.messages.onBeforeSend((msg) => { msg.content = "modified" })` - **On receive**: `ctx.messages.onReceive((msg) => { /* process */ })` - Full MessageContext with content, roomId, metadata - Async support for interceptors ### 3. ✅ Custom Renderers & Button Registration + - **Register renderer**: `ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { /* render */ })` - **Unregister renderer**: `ctx.ui.unregisterRenderer("message")` - **Register button**: `ctx.ui.registerButton({ id, location, label, icon, onClick })` @@ -29,6 +32,7 @@ All requested features have been implemented! 🎉 - See [PLUGIN_BUTTON_API.md](PLUGIN_BUTTON_API.md) for full reference ### 4. ✅ Settings UI Per Plugin + - **Define schema**: `ctx.settings.define({ theme: { type: "select", options: [...] } })` - **Supported types**: string, number, boolean, select, color - **Get/Set**: `ctx.settings.get(key)` / `ctx.settings.set(key, value)` @@ -36,24 +40,28 @@ All requested features have been implemented! 🎉 - No JSON editing needed! ### 5. ✅ Hot Reload + - **API**: `pluginRegistry.reloadPlugin(pluginId, newPlugin, newContext)` - Auto-cleanup of old plugin resources - Maintains enabled/disabled state - Dev-friendly workflow ### 6. ✅ Dependency System + - **Declare**: `dependencies: { "paarrot.core-utils": "^1.0.0" }` - **Require**: `const utils = ctx.require("paarrot.utils")` - Error handling for missing dependencies - Plugin exports system ### 7. ✅ Raw Matrix Events Hook + - **Full SDK access**: `ctx.matrix.on("m.room.message", (ev) => { })` - **Any event type**: Room.timeline, sync, RoomState.events, etc. - Direct Matrix.js SDK integration - Power users will go nuts! ### 8. ✅ Background Tasks / Intervals + - **Interval**: `ctx.timers.setInterval(() => { /* cursed shit */ }, 10000)` - **Timeout**: `ctx.timers.setTimeout(() => { }, 5000)` - **Clear**: `ctx.timers.clearInterval(id)` / `ctx.timers.clearTimeout(id)` @@ -61,12 +69,14 @@ All requested features have been implemented! 🎉 - Perfect for bots, reminders, auto-cleanup ### 9. ✅ Notifications API + - **Simple**: `ctx.notify("Oi")` - **Advanced**: `ctx.notify({ title: "Oi", body: "New message from Steve", type: "info" })` - Action buttons support - Custom duration ### 10. ✅ Plugin Logs Panel + - **Logging**: `ctx.log()`, `ctx.warn()`, `ctx.error()` - Per-plugin log storage - Visible in `pluginRegistry.getLogs(pluginId)` @@ -85,16 +95,19 @@ All requested features have been implemented! 🎉 ## 📁 Files Changed ### Core System + - [`PluginAPI.ts`](cinny/src/app/features/settings/plugins/PluginAPI.ts) - Enhanced with all APIs - [`PluginLoader.tsx`](cinny/src/app/features/settings/plugins/PluginLoader.tsx) - Complete rewrite with context creation - [`index.ts`](cinny/src/app/features/settings/plugins/index.ts) - Exports updated ### Documentation + - [`PLUGIN_DEVELOPMENT.md`](cinny/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md) - Comprehensive guide - [`PLUGINS.md`](PLUGINS.md) - User guide - [`example-plugin/index.js`](example-plugin/index.js) - Full-featured example ### Integration + - [`ClientRoot.tsx`](cinny/src/app/pages/client/ClientRoot.tsx) - PluginLoader integrated - [`main.js`](electron/main.js) - IPC handler for reading plugin code - [`preload.js`](electron/preload.js) - readPluginCode API exposed @@ -103,32 +116,36 @@ All requested features have been implemented! 🎉 ## 🚀 Usage Examples ### Command with Args + ```javascript ctx.commands.register({ - name: "echo", - args: ["text"], - run: ({ text }) => text + name: 'echo', + args: ['text'], + run: ({ text }) => text, }); ``` ### Message Interceptor + ```javascript ctx.messages.onBeforeSend((msg) => { - if (msg.content === "brb") { - msg.content = "be right back ya legend"; + if (msg.content === 'brb') { + msg.content = 'be right back ya legend'; } }); ``` ### Custom Settings + ```javascript ctx.settings.define({ - theme: { type: "select", options: ["dark", "light"] }, - spamFilter: { type: "boolean", default: true } + theme: { type: 'select', options: ['dark', 'light'] }, + spamFilter: { type: 'boolean', default: true }, }); ``` ### Background Tasks + ```javascript ctx.timers.setInterval(() => { // do cursed shit every 10s @@ -136,15 +153,17 @@ ctx.timers.setInterval(() => { ``` ### Raw Matrix Events + ```javascript -ctx.matrix.on("m.room.message", (ev) => { +ctx.matrix.on('m.room.message', (ev) => { ctx.log('Message:', ev.getContent().body); }); ``` ### Plugin Dependencies + ```javascript -const utils = ctx.require("paarrot.utils"); +const utils = ctx.require('paarrot.utils'); utils.doSomething(); ``` @@ -155,43 +174,43 @@ interface PluginContext { pluginId: string; matrixClient: MatrixClient; React: typeof import('react'); - + commands: { register: (command: PluginCommand) => void; unregister: (name: string) => void; execute: (name: string, args: Record) => Promise; }; - + messages: { onBeforeSend: (interceptor: MessageInterceptor) => void; onReceive: (interceptor: MessageInterceptor) => void; }; - + ui: { registerButton: (button: UIButtonDefinition) => void; unregisterButton: (id: string) => void; registerRenderer: (type: string, renderer: CustomRenderer) => void; unregisterRenderer: (type: string) => void; }; - + settings: { define: (schema: SettingsSchema) => void; get: (key: string) => T | undefined; set: (key: string, value: any) => void; }; - + matrix: { on: (eventType: string, handler: (event: MatrixEvent) => void) => void; off: (eventType: string, handler: (event: MatrixEvent) => void) => void; }; - + timers: { setInterval: (callback: () => void, ms: number) => number; setTimeout: (callback: () => void, ms: number) => number; clearInterval: (id: number) => void; clearTimeout: (id: number) => void; }; - + notify: (options: NotificationOptions | string) => void; log: (...args: any[]) => void; warn: (...args: any[]) => void; diff --git a/docs/handoff/TEMPLATE.md b/docs/handoff/TEMPLATE.md index a52054cd..6441b642 100644 --- a/docs/handoff/TEMPLATE.md +++ b/docs/handoff/TEMPLATE.md @@ -20,8 +20,8 @@ ## Key files -| Path | Role | -|------|------| +| Path | Role | +| -------------- | --------------------- | | `path/to/file` | | ## Data model @@ -29,8 +29,8 @@ | Key / event | Scope | Shape | -|-------------|-------|-------| -| | | | +| ----------- | ----- | ----- | +| | | | ## Dependencies diff --git a/docs/handoff/features/android/HANDOFF.md b/docs/handoff/features/android/HANDOFF.md index 29f2ab79..d5a00d4e 100644 --- a/docs/handoff/features/android/HANDOFF.md +++ b/docs/handoff/features/android/HANDOFF.md @@ -25,14 +25,14 @@ tauri.ts → native notification APIs ## Key files -| Path | Role | -|------|------| -| `cinny/capacitor.config.json` | Capacitor app id, web dir | -| `src-tauri/src/main.rs` | Tauri Android entry | -| `cinny/src/app/utils/tauri.ts` | Platform detection, notifications | -| `cinny/src/app/utils/backgroundSync.ts` | UnifiedPush registration | -| `cinny/src/app/utils/androidShare.ts` | Share target handling | -| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Share listener wiring | +| Path | Role | +| ---------------------------------------------------- | --------------------------------- | +| `cinny/capacitor.config.json` | Capacitor app id, web dir | +| `src-tauri/src/main.rs` | Tauri Android entry | +| `cinny/src/app/utils/tauri.ts` | Platform detection, notifications | +| `cinny/src/app/utils/backgroundSync.ts` | UnifiedPush registration | +| `cinny/src/app/utils/androidShare.ts` | Share target handling | +| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Share listener wiring | ## Data model diff --git a/docs/handoff/features/authentication/HANDOFF.md b/docs/handoff/features/authentication/HANDOFF.md index d3e1448f..8c46c375 100644 --- a/docs/handoff/features/authentication/HANDOFF.md +++ b/docs/handoff/features/authentication/HANDOFF.md @@ -25,29 +25,29 @@ ClientRoot (authenticated) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/auth/login/Login.tsx` | Login hub | -| `cinny/src/app/pages/auth/login/PasswordLoginForm.tsx` | Password login | -| `cinny/src/app/pages/auth/login/TokenLogin.tsx` | Access token login | -| `cinny/src/app/pages/auth/SSOLogin.tsx` | SSO redirect | -| `cinny/src/app/pages/auth/register/Register.tsx` | Registration | -| `cinny/src/app/pages/auth/register/PasswordRegisterForm.tsx` | Password register | -| `cinny/src/app/pages/auth/reset-password/ResetPassword.tsx` | Password reset | -| `cinny/src/app/pages/auth/ServerPicker.tsx` | Homeserver selection | -| `cinny/src/app/pages/auth/AuthLayout.tsx` | Auth chrome + logo | -| `cinny/src/app/pages/auth/login/loginUtil.ts` | Login helpers | -| `cinny/src/app/pages/auth/register/registerUtil.ts` | Register helpers | -| `cinny/src/app/state/sessions.ts` | Session storage | -| `cinny/src/client/initMatrix.ts` | Client init from session | -| `cinny/src/app/pages/afterLoginRedirectPath.ts` | Post-login redirect | +| Path | Role | +| ------------------------------------------------------------ | ------------------------ | +| `cinny/src/app/pages/auth/login/Login.tsx` | Login hub | +| `cinny/src/app/pages/auth/login/PasswordLoginForm.tsx` | Password login | +| `cinny/src/app/pages/auth/login/TokenLogin.tsx` | Access token login | +| `cinny/src/app/pages/auth/SSOLogin.tsx` | SSO redirect | +| `cinny/src/app/pages/auth/register/Register.tsx` | Registration | +| `cinny/src/app/pages/auth/register/PasswordRegisterForm.tsx` | Password register | +| `cinny/src/app/pages/auth/reset-password/ResetPassword.tsx` | Password reset | +| `cinny/src/app/pages/auth/ServerPicker.tsx` | Homeserver selection | +| `cinny/src/app/pages/auth/AuthLayout.tsx` | Auth chrome + logo | +| `cinny/src/app/pages/auth/login/loginUtil.ts` | Login helpers | +| `cinny/src/app/pages/auth/register/registerUtil.ts` | Register helpers | +| `cinny/src/app/state/sessions.ts` | Session storage | +| `cinny/src/client/initMatrix.ts` | Client init from session | +| `cinny/src/app/pages/afterLoginRedirectPath.ts` | Post-login redirect | ## Data model -| Key | Storage | Content | -|-----|---------|---------| -| Session store | localStorage | access token, user id, device id, hs url | -| `setAfterLoginRedirectPath` | sessionStorage/memory | deep link target after login | +| Key | Storage | Content | +| --------------------------- | --------------------- | ---------------------------------------- | +| Session store | localStorage | access token, user id, device id, hs url | +| `setAfterLoginRedirectPath` | sessionStorage/memory | deep link target after login | ## Dependencies diff --git a/docs/handoff/features/avatar-metadata/HANDOFF.md b/docs/handoff/features/avatar-metadata/HANDOFF.md index 954db995..13dd7db6 100644 --- a/docs/handoff/features/avatar-metadata/HANDOFF.md +++ b/docs/handoff/features/avatar-metadata/HANDOFF.md @@ -24,25 +24,25 @@ Other clients / Profile.tsx ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/utils/imageMetadata.ts` | Unified embed/extract API | -| `cinny/src/app/utils/pngMetadata.ts` | PNG tEXt chunks | -| `cinny/src/app/utils/jpegMetadata.ts` | JPEG XMP APP1 | -| `cinny/src/app/utils/webpMetadata.ts` | WebP XMP | -| `cinny/src/app/utils/gifMetadata.ts` | GIF application extension | +| Path | Role | +| ----------------------------------------------------- | ----------------------------- | +| `cinny/src/app/utils/imageMetadata.ts` | Unified embed/extract API | +| `cinny/src/app/utils/pngMetadata.ts` | PNG tEXt chunks | +| `cinny/src/app/utils/jpegMetadata.ts` | JPEG XMP APP1 | +| `cinny/src/app/utils/webpMetadata.ts` | WebP XMP | +| `cinny/src/app/utils/gifMetadata.ts` | GIF application extension | | `cinny/src/app/features/settings/account/Profile.tsx` | Settings UI + upload pipeline | ## Data model Metadata keys (embedded in binary image, not Matrix): -| Key | Format | Notes | -|-----|--------|-------| -| `paarrot:color` | All | Accent color hex | -| `paarrot:banner` | PNG (+ unified API) | Banner image URL | -| `paarrot:borderColor` | PNG | Border accent | -| `paarrot:gradient` | PNG | Gradient spec | +| Key | Format | Notes | +| --------------------- | ------------------- | ---------------- | +| `paarrot:color` | All | Accent color hex | +| `paarrot:banner` | PNG (+ unified API) | Banner image URL | +| `paarrot:borderColor` | PNG | Border accent | +| `paarrot:gradient` | PNG | Gradient spec | XMP namespace: `http://paarrot.app/ns/1.0/` diff --git a/docs/handoff/features/background-notifications/HANDOFF.md b/docs/handoff/features/background-notifications/HANDOFF.md index 8b12c654..dc9cb689 100644 --- a/docs/handoff/features/background-notifications/HANDOFF.md +++ b/docs/handoff/features/background-notifications/HANDOFF.md @@ -27,22 +27,22 @@ tauri.ts / electron main ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Favicon, notifications, API init, background sync hooks | -| `cinny/src/app/utils/backgroundSync.ts` | Pushers, UnifiedPush, foreground state | -| `cinny/src/app/utils/tauri.ts` | Tauri/Capacitor notification helpers | -| `cinny/src/app/features/settings/notifications/SystemNotification.tsx` | Permission UX | -| `electron/main.js` | Tray, notification IPC (if applicable) | -| `src-tauri/src/main.rs` | Tauri Android shell | +| Path | Role | +| ---------------------------------------------------------------------- | ------------------------------------------------------- | +| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Favicon, notifications, API init, background sync hooks | +| `cinny/src/app/utils/backgroundSync.ts` | Pushers, UnifiedPush, foreground state | +| `cinny/src/app/utils/tauri.ts` | Tauri/Capacitor notification helpers | +| `cinny/src/app/features/settings/notifications/SystemNotification.tsx` | Permission UX | +| `electron/main.js` | Tray, notification IPC (if applicable) | +| `src-tauri/src/main.rs` | Tauri Android shell | ## Data model -| Key | Storage | Purpose | -|-----|---------|---------| -| `paarrot.unifiedpush.*` | localStorage prefix | UP endpoint state | -| `com.paarrot.app.android` | Pusher app id base | Android pushers | -| Matrix pusher | Homeserver | HTTP push gateway | +| Key | Storage | Purpose | +| ------------------------- | ------------------- | ----------------- | +| `paarrot.unifiedpush.*` | localStorage prefix | UP endpoint state | +| `com.paarrot.app.android` | Pusher app id base | Android pushers | +| Matrix pusher | Homeserver | HTTP push gateway | ## Dependencies diff --git a/docs/handoff/features/client-chrome/HANDOFF.md b/docs/handoff/features/client-chrome/HANDOFF.md index 78ffc2be..125ecbfa 100644 --- a/docs/handoff/features/client-chrome/HANDOFF.md +++ b/docs/handoff/features/client-chrome/HANDOFF.md @@ -27,24 +27,24 @@ SpecVersions in ClientRoot ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/components/title-bar/TitleBar.tsx` | Desktop title bar | -| `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Splash | -| `cinny/src/app/pages/client/WelcomePage.tsx` | Welcome / download links | -| `cinny/src/app/components/account-switcher/AccountSwitcher.tsx` | Multi-account | -| `cinny/src/app/components/update-notification/UpdateNotification.tsx` | Auto-update UI | -| `cinny/src/app/pages/FeatureCheck.tsx` | Browser capability gate | -| `cinny/src/app/pages/client/SpecVersions.tsx` | HS version warning | -| `cinny/src/app/pages/client/SyncStatus.tsx` | Sync indicator | -| `cinny/src/app/pages/ConfigConfig.tsx` | Config load error UI | -| `cinny/src/app/components/ClientConfigLoader.tsx` | Load config.json | +| Path | Role | +| --------------------------------------------------------------------- | ------------------------ | +| `cinny/src/app/components/title-bar/TitleBar.tsx` | Desktop title bar | +| `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Splash | +| `cinny/src/app/pages/client/WelcomePage.tsx` | Welcome / download links | +| `cinny/src/app/components/account-switcher/AccountSwitcher.tsx` | Multi-account | +| `cinny/src/app/components/update-notification/UpdateNotification.tsx` | Auto-update UI | +| `cinny/src/app/pages/FeatureCheck.tsx` | Browser capability gate | +| `cinny/src/app/pages/client/SpecVersions.tsx` | HS version warning | +| `cinny/src/app/pages/client/SyncStatus.tsx` | Sync indicator | +| `cinny/src/app/pages/ConfigConfig.tsx` | Config load error UI | +| `cinny/src/app/components/ClientConfigLoader.tsx` | Load config.json | ## Data model -| Key | Storage | -|-----|---------| -| Sessions | multi-account in sessions.ts | +| Key | Storage | +| -------------- | ---------------------------- | +| Sessions | multi-account in sessions.ts | | electron-store | window bounds (main process) | ## Dependencies diff --git a/docs/handoff/features/common-settings/HANDOFF.md b/docs/handoff/features/common-settings/HANDOFF.md index a7ab30fb..98938132 100644 --- a/docs/handoff/features/common-settings/HANDOFF.md +++ b/docs/handoff/features/common-settings/HANDOFF.md @@ -26,15 +26,15 @@ Imported by room-settings and space-settings shells ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/common-settings/general/RoomProfile.tsx` | Name/topic/avatar | -| `cinny/src/app/features/common-settings/general/RoomJoinRules.tsx` | Join rules | -| `cinny/src/app/features/common-settings/general/RoomEncryption.tsx` | E2E toggle | -| `cinny/src/app/features/common-settings/general/EmbedFilters.tsx` | Room-wide embed filters | -| `cinny/src/app/features/common-settings/members/Members.tsx` | Member management | -| `cinny/src/app/features/common-settings/permissions/PowersEditor.tsx` | Power levels | -| `cinny/src/app/features/common-settings/developer-tools/` | Dev event tools | +| Path | Role | +| --------------------------------------------------------------------- | ----------------------- | +| `cinny/src/app/features/common-settings/general/RoomProfile.tsx` | Name/topic/avatar | +| `cinny/src/app/features/common-settings/general/RoomJoinRules.tsx` | Join rules | +| `cinny/src/app/features/common-settings/general/RoomEncryption.tsx` | E2E toggle | +| `cinny/src/app/features/common-settings/general/EmbedFilters.tsx` | Room-wide embed filters | +| `cinny/src/app/features/common-settings/members/Members.tsx` | Member management | +| `cinny/src/app/features/common-settings/permissions/PowersEditor.tsx` | Power levels | +| `cinny/src/app/features/common-settings/developer-tools/` | Dev event tools | ## Data model diff --git a/docs/handoff/features/create-flows/HANDOFF.md b/docs/handoff/features/create-flows/HANDOFF.md index 8e58c263..750ff340 100644 --- a/docs/handoff/features/create-flows/HANDOFF.md +++ b/docs/handoff/features/create-flows/HANDOFF.md @@ -26,18 +26,18 @@ State: createRoomModal.ts, createSpaceModal.ts ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Room create + sub-room parent update | -| `cinny/src/app/features/create-space/CreateSpaceModal.tsx` | Space create | -| `cinny/src/app/features/create-chat/` | DM flows | -| `cinny/src/app/features/add-existing/AddExisting.tsx` | Add to space | -| `cinny/src/app/features/create-room/CreateRoom.tsx` | Standalone create page | -| `cinny/src/app/features/create-space/CreateSpace.tsx` | Standalone space create | -| `cinny/src/app/state/createRoomModal.ts` | Modal state + parent room id | -| `cinny/src/app/state/createSpaceModal.ts` | Space modal state | -| `cinny/src/app/pages/client/create/Create.tsx` | Create hub route | -| `cinny/src/app/pages/client/home/CreateRoom.tsx` | Home create entry | +| Path | Role | +| ---------------------------------------------------------- | ------------------------------------ | +| `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Room create + sub-room parent update | +| `cinny/src/app/features/create-space/CreateSpaceModal.tsx` | Space create | +| `cinny/src/app/features/create-chat/` | DM flows | +| `cinny/src/app/features/add-existing/AddExisting.tsx` | Add to space | +| `cinny/src/app/features/create-room/CreateRoom.tsx` | Standalone create page | +| `cinny/src/app/features/create-space/CreateSpace.tsx` | Standalone space create | +| `cinny/src/app/state/createRoomModal.ts` | Modal state + parent room id | +| `cinny/src/app/state/createSpaceModal.ts` | Space modal state | +| `cinny/src/app/pages/client/create/Create.tsx` | Create hub route | +| `cinny/src/app/pages/client/home/CreateRoom.tsx` | Home create entry | ## Data model diff --git a/docs/handoff/features/custom-emoji-packs/HANDOFF.md b/docs/handoff/features/custom-emoji-packs/HANDOFF.md index 22e210f0..1c8a9e6e 100644 --- a/docs/handoff/features/custom-emoji-packs/HANDOFF.md +++ b/docs/handoff/features/custom-emoji-packs/HANDOFF.md @@ -23,23 +23,23 @@ settings emojis-stickers + common-settings emojis ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/plugins/custom-emoji/PackMetaReader.ts` | Read pack metadata | -| `cinny/src/app/plugins/custom-emoji/PackImageReader.ts` | Single image | -| `cinny/src/app/plugins/custom-emoji/PackImagesReader.ts` | Bulk images | -| `cinny/src/app/plugins/custom-emoji/ImagePack.ts` | Pack model | -| `cinny/src/app/plugins/custom-emoji/types.ts` | Types | -| `cinny/src/app/plugins/emoji.ts` | Shortcode rendering | -| `cinny/src/app/plugins/recent-emoji.ts` | Recent emoji helper | -| `cinny/src/app/components/image-pack-view/ImagePackView.tsx` | Pack browser UI | -| `cinny/src/app/hooks/useImagePackRooms.ts` | Rooms with packs | +| Path | Role | +| ------------------------------------------------------------ | ------------------- | +| `cinny/src/app/plugins/custom-emoji/PackMetaReader.ts` | Read pack metadata | +| `cinny/src/app/plugins/custom-emoji/PackImageReader.ts` | Single image | +| `cinny/src/app/plugins/custom-emoji/PackImagesReader.ts` | Bulk images | +| `cinny/src/app/plugins/custom-emoji/ImagePack.ts` | Pack model | +| `cinny/src/app/plugins/custom-emoji/types.ts` | Types | +| `cinny/src/app/plugins/emoji.ts` | Shortcode rendering | +| `cinny/src/app/plugins/recent-emoji.ts` | Recent emoji helper | +| `cinny/src/app/components/image-pack-view/ImagePackView.tsx` | Pack browser UI | +| `cinny/src/app/hooks/useImagePackRooms.ts` | Rooms with packs | ## Data model -| Event | Purpose | -|-------|---------| -| `im.ponies.room_emotes` | Room emoji pack definition | +| Event | Purpose | +| ----------------------- | -------------------------------------- | +| `im.ponies.room_emotes` | Room emoji pack definition | | Image pack account data | User/global packs (see emoji-stickers) | ## Dependencies diff --git a/docs/handoff/features/developer-tools/HANDOFF.md b/docs/handoff/features/developer-tools/HANDOFF.md index 39d2454c..1eaea01b 100644 --- a/docs/handoff/features/developer-tools/HANDOFF.md +++ b/docs/handoff/features/developer-tools/HANDOFF.md @@ -21,13 +21,13 @@ common-settings/developer-tools/ ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/settings/developer-tools/DevelopTools.tsx` | User-level dev tools | -| `cinny/src/app/features/settings/developer-tools/AccountData.tsx` | Account data viewer | -| `cinny/src/app/features/common-settings/developer-tools/DevelopTools.tsx` | Room dev tools entry | -| `cinny/src/app/features/common-settings/developer-tools/StateEventEditor.tsx` | Edit state events | -| `cinny/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx` | Send events | +| Path | Role | +| ----------------------------------------------------------------------------- | -------------------- | +| `cinny/src/app/features/settings/developer-tools/DevelopTools.tsx` | User-level dev tools | +| `cinny/src/app/features/settings/developer-tools/AccountData.tsx` | Account data viewer | +| `cinny/src/app/features/common-settings/developer-tools/DevelopTools.tsx` | Room dev tools entry | +| `cinny/src/app/features/common-settings/developer-tools/StateEventEditor.tsx` | Edit state events | +| `cinny/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx` | Send events | ## Data model diff --git a/docs/handoff/features/direct-messages/HANDOFF.md b/docs/handoff/features/direct-messages/HANDOFF.md index d873f807..3205277f 100644 --- a/docs/handoff/features/direct-messages/HANDOFF.md +++ b/docs/handoff/features/direct-messages/HANDOFF.md @@ -24,19 +24,19 @@ mDirectAtom — direct room index ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/client/direct/Direct.tsx` | DM list | -| `cinny/src/app/pages/client/direct/DirectCreate.tsx` | Create DM | -| `cinny/src/app/pages/client/direct/useDirectRooms.ts` | List logic | -| `cinny/src/app/pages/client/sidebar/DirectTab.tsx` | Sidebar tab | -| `cinny/src/app/state/mDirectList.ts` | `mDirectAtom` | -| `cinny/src/app/hooks/useDirectUsers.ts` | DM user helpers | +| Path | Role | +| ----------------------------------------------------- | --------------- | +| `cinny/src/app/pages/client/direct/Direct.tsx` | DM list | +| `cinny/src/app/pages/client/direct/DirectCreate.tsx` | Create DM | +| `cinny/src/app/pages/client/direct/useDirectRooms.ts` | List logic | +| `cinny/src/app/pages/client/sidebar/DirectTab.tsx` | Sidebar tab | +| `cinny/src/app/state/mDirectList.ts` | `mDirectAtom` | +| `cinny/src/app/hooks/useDirectUsers.ts` | DM user helpers | ## Data model -| Key | Scope | -|-----|-------| +| Key | Scope | +| ---------- | ------------------------------------------ | | `m.direct` | User account data — map userId → roomIds[] | ## Dependencies diff --git a/docs/handoff/features/e2e-and-devices/HANDOFF.md b/docs/handoff/features/e2e-and-devices/HANDOFF.md index c8454a36..3afe12d8 100644 --- a/docs/handoff/features/e2e-and-devices/HANDOFF.md +++ b/docs/handoff/features/e2e-and-devices/HANDOFF.md @@ -24,26 +24,26 @@ useSecretStorage, useKeyBackup, useVerificationRequest hooks ## Key files -| Path | Role | -|------|------| -| `cinny/src/client/secretStorageKeys.ts` | SSSS key handling | -| `cinny/src/app/features/settings/devices/Devices.tsx` | Device list | -| `cinny/src/app/features/settings/devices/Verification.tsx` | Verification UI | -| `cinny/src/app/features/settings/devices/LocalBackup.tsx` | Key export | -| `cinny/src/app/features/settings/devices/OtherDevices.tsx` | Remote sessions | -| `cinny/src/app/components/DeviceVerification.tsx` | Incoming verify modal | -| `cinny/src/app/components/BackupRestore.tsx` | Auto restore | -| `cinny/src/app/components/SecretStorage.tsx` | Passphrase setup | -| `cinny/src/app/hooks/useSecretStorage.ts` | Secret storage API | -| `cinny/src/app/hooks/useKeyBackup.ts` | Backup API | -| `cinny/src/app/pages/client/sidebar/UnverifiedTab.tsx` | Unverified badge | +| Path | Role | +| ---------------------------------------------------------- | --------------------- | +| `cinny/src/client/secretStorageKeys.ts` | SSSS key handling | +| `cinny/src/app/features/settings/devices/Devices.tsx` | Device list | +| `cinny/src/app/features/settings/devices/Verification.tsx` | Verification UI | +| `cinny/src/app/features/settings/devices/LocalBackup.tsx` | Key export | +| `cinny/src/app/features/settings/devices/OtherDevices.tsx` | Remote sessions | +| `cinny/src/app/components/DeviceVerification.tsx` | Incoming verify modal | +| `cinny/src/app/components/BackupRestore.tsx` | Auto restore | +| `cinny/src/app/components/SecretStorage.tsx` | Passphrase setup | +| `cinny/src/app/hooks/useSecretStorage.ts` | Secret storage API | +| `cinny/src/app/hooks/useKeyBackup.ts` | Backup API | +| `cinny/src/app/pages/client/sidebar/UnverifiedTab.tsx` | Unverified badge | ## Data model -| Store | Purpose | -|-------|---------| -| IndexedDB crypto | Olm account, Megolm sessions | -| SSSS | Cross-signing keys, backup key | +| Store | Purpose | +| ------------------- | ----------------------------------------- | +| IndexedDB crypto | Olm account, Megolm sessions | +| SSSS | Cross-signing keys, backup key | | Matrix account data | `m.cross_signing.*`, `m.secret_storage.*` | ## Dependencies diff --git a/docs/handoff/features/editor-and-composer/HANDOFF.md b/docs/handoff/features/editor-and-composer/HANDOFF.md index 74d97d4e..02416bbf 100644 --- a/docs/handoff/features/editor-and-composer/HANDOFF.md +++ b/docs/handoff/features/editor-and-composer/HANDOFF.md @@ -25,25 +25,25 @@ text-area plugin (legacy/plain areas in some UI) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/components/editor/Editor.tsx` | Main Slate editor | -| `cinny/src/app/components/editor/Toolbar.tsx` | Formatting toolbar | -| `cinny/src/app/components/editor/input.ts` | Parse into editor | -| `cinny/src/app/components/editor/output.ts` | Serialize to Matrix | -| `cinny/src/app/components/editor/autocomplete/` | Mention/emoji menus | -| `cinny/src/app/features/room/RoomInput.tsx` | Room composer wrapper | -| `cinny/src/app/plugins/text-area/` | Plain text area utilities | -| `cinny/src/app/hooks/useFilePasteHandler.ts` | Paste files | -| `cinny/src/app/hooks/useFileDrop.ts` | Drag-drop files | -| `cinny/src/app/state/room/roomInputDrafts.ts` | Draft persistence | +| Path | Role | +| ----------------------------------------------- | ------------------------- | +| `cinny/src/app/components/editor/Editor.tsx` | Main Slate editor | +| `cinny/src/app/components/editor/Toolbar.tsx` | Formatting toolbar | +| `cinny/src/app/components/editor/input.ts` | Parse into editor | +| `cinny/src/app/components/editor/output.ts` | Serialize to Matrix | +| `cinny/src/app/components/editor/autocomplete/` | Mention/emoji menus | +| `cinny/src/app/features/room/RoomInput.tsx` | Room composer wrapper | +| `cinny/src/app/plugins/text-area/` | Plain text area utilities | +| `cinny/src/app/hooks/useFilePasteHandler.ts` | Paste files | +| `cinny/src/app/hooks/useFileDrop.ts` | Drag-drop files | +| `cinny/src/app/state/room/roomInputDrafts.ts` | Draft persistence | ## Data model -| Key | Storage | -|-----|---------| -| `roomIdToMsgDraftAtomFamily` | localStorage per room | -| `roomIdToUploadItemsAtomFamily` | pending uploads | +| Key | Storage | +| ------------------------------- | --------------------- | +| `roomIdToMsgDraftAtomFamily` | localStorage per room | +| `roomIdToUploadItemsAtomFamily` | pending uploads | ## Dependencies diff --git a/docs/handoff/features/electron-shell/HANDOFF.md b/docs/handoff/features/electron-shell/HANDOFF.md index 36042cbf..60bc4910 100644 --- a/docs/handoff/features/electron-shell/HANDOFF.md +++ b/docs/handoff/features/electron-shell/HANDOFF.md @@ -25,23 +25,23 @@ preload / contextBridge → window.electron in renderer ## Key files -| Path | Role | -|------|------| -| `electron/main.js` | Main process entry | -| `electron/api-server.js` | Local HTTP API | -| `electron/preload.js` (if exists) | IPC bridge | -| `electron-builder.json5` | Packaging config | -| `package.json` (root) | `npm run dev`, build scripts | -| `dev-app-update.yml` | Update channel config | -| `cinny/src/app/components/title-bar/TitleBar.tsx` | Custom title bar UI | -| `build-resources/` | Linux after-install, icons | +| Path | Role | +| ------------------------------------------------- | ---------------------------- | +| `electron/main.js` | Main process entry | +| `electron/api-server.js` | Local HTTP API | +| `electron/preload.js` (if exists) | IPC bridge | +| `electron-builder.json5` | Packaging config | +| `package.json` (root) | `npm run dev`, build scripts | +| `dev-app-update.yml` | Update channel config | +| `cinny/src/app/components/title-bar/TitleBar.tsx` | Custom title bar UI | +| `build-resources/` | Linux after-install, icons | ## Data model -| Store | Tool | Contents | -|-------|------|----------| -| `electron-store` | main.js | Window bounds, user prefs | -| UserData | Electron | plugins, caches | +| Store | Tool | Contents | +| ---------------- | -------- | ------------------------- | +| `electron-store` | main.js | Window bounds, user prefs | +| UserData | Electron | plugins, caches | Protocol: `PROTOCOL_SCHEME = 'paarrot'` in main.js diff --git a/docs/handoff/features/embed-filters/HANDOFF.md b/docs/handoff/features/embed-filters/HANDOFF.md index 1982d6c8..43fd457c 100644 --- a/docs/handoff/features/embed-filters/HANDOFF.md +++ b/docs/handoff/features/embed-filters/HANDOFF.md @@ -21,22 +21,22 @@ useRoomWideEmbedFilters (room state) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/hooks/useRoomEmbedFilters.ts` | Hooks, types, combine logic | -| `cinny/src/types/matrix/room.ts` | `StateEvent.RoomEmbedFilters` | -| `cinny/src/app/features/room/ThreadView.tsx` | Consumer | -| `cinny/src/app/features/room/RoomTimeline.tsx` | Consumer | -| `cinny/src/app/features/common-settings/general/EmbedFilters.tsx` | Room-wide settings UI | -| `cinny/src/app/components/RenderMessageContent.tsx` | Embed render gating | -| `cinny/src/app/features/forum/useForumMessageRenderOptions.ts` | Forum post embed options | +| Path | Role | +| ----------------------------------------------------------------- | ----------------------------- | +| `cinny/src/app/hooks/useRoomEmbedFilters.ts` | Hooks, types, combine logic | +| `cinny/src/types/matrix/room.ts` | `StateEvent.RoomEmbedFilters` | +| `cinny/src/app/features/room/ThreadView.tsx` | Consumer | +| `cinny/src/app/features/room/RoomTimeline.tsx` | Consumer | +| `cinny/src/app/features/common-settings/general/EmbedFilters.tsx` | Room-wide settings UI | +| `cinny/src/app/components/RenderMessageContent.tsx` | Embed render gating | +| `cinny/src/app/features/forum/useForumMessageRenderOptions.ts` | Forum post embed options | ## Data model -| Key | Scope | Content | -|-----|-------|---------| -| `im.paarrot.embed_filters` | Room account data (per user) | `{ disabledPatterns: string[] }` | -| `im.paarrot.room.embed_filters` | Room state | `{ disabledPatterns: string[] }` | +| Key | Scope | Content | +| ------------------------------- | ---------------------------- | -------------------------------- | +| `im.paarrot.embed_filters` | Room account data (per user) | `{ disabledPatterns: string[] }` | +| `im.paarrot.room.embed_filters` | Room state | `{ disabledPatterns: string[] }` | Patterns are JavaScript `RegExp` strings — invalid regex can throw; handle at input time. diff --git a/docs/handoff/features/emoji-stickers/HANDOFF.md b/docs/handoff/features/emoji-stickers/HANDOFF.md index 0120d0d2..b8cf33ea 100644 --- a/docs/handoff/features/emoji-stickers/HANDOFF.md +++ b/docs/handoff/features/emoji-stickers/HANDOFF.md @@ -24,25 +24,25 @@ Settings / common-settings EmojisStickers pages ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/hooks/useEmojiUsage.ts` | Usage stats in account data | -| `cinny/src/app/utils/telegramStickerImport.ts` | Telegram Bot API import | -| `cinny/src/app/features/settings/emojis-stickers/TelegramImport.tsx` | Import UI | -| `cinny/src/app/features/settings/emojis-stickers/EmojisStickers.tsx` | Settings hub | -| `cinny/src/app/features/settings/emojis-stickers/UserPack.tsx` | User pack editor | -| `cinny/src/app/features/settings/emojis-stickers/GlobalPacks.tsx` | Global packs | -| `cinny/src/app/plugins/custom-emoji/` | Custom emoji pack reader | -| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | `EmojiStyleFeature` | -| `cinny/src/app/state/settings.ts` | `EmojiStyle` enum | +| Path | Role | +| -------------------------------------------------------------------- | --------------------------- | +| `cinny/src/app/hooks/useEmojiUsage.ts` | Usage stats in account data | +| `cinny/src/app/utils/telegramStickerImport.ts` | Telegram Bot API import | +| `cinny/src/app/features/settings/emojis-stickers/TelegramImport.tsx` | Import UI | +| `cinny/src/app/features/settings/emojis-stickers/EmojisStickers.tsx` | Settings hub | +| `cinny/src/app/features/settings/emojis-stickers/UserPack.tsx` | User pack editor | +| `cinny/src/app/features/settings/emojis-stickers/GlobalPacks.tsx` | Global packs | +| `cinny/src/app/plugins/custom-emoji/` | Custom emoji pack reader | +| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | `EmojiStyleFeature` | +| `cinny/src/app/state/settings.ts` | `EmojiStyle` enum | ## Data model -| Key | Scope | Content | -|-----|-------|---------| -| `paarrot.favemojis` | User account data | Emoji usage counts | -| `cinny_telegram_bot_token` | localStorage | Telegram bot token (TelegramImport) | -| `im.ponies.room_emotes` | Room state | Standard Matrix emoji packs | +| Key | Scope | Content | +| -------------------------- | ----------------- | ----------------------------------- | +| `paarrot.favemojis` | User account data | Emoji usage counts | +| `cinny_telegram_bot_token` | localStorage | Telegram bot token (TelegramImport) | +| `im.ponies.room_emotes` | Room state | Standard Matrix emoji packs | ## Dependencies diff --git a/docs/handoff/features/explore/HANDOFF.md b/docs/handoff/features/explore/HANDOFF.md index af32759a..deda94c4 100644 --- a/docs/handoff/features/explore/HANDOFF.md +++ b/docs/handoff/features/explore/HANDOFF.md @@ -24,12 +24,12 @@ client/explore/ ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/client/explore/Explore.tsx` | Explore hub | -| `cinny/src/app/pages/client/explore/Server.tsx` | Server directory | -| `cinny/src/app/pages/client/explore/Featured.tsx` | Featured list | -| `cinny/src/app/pages/client/sidebar/ExploreTab.tsx` | Sidebar entry | +| Path | Role | +| --------------------------------------------------- | -------------------- | +| `cinny/src/app/pages/client/explore/Explore.tsx` | Explore hub | +| `cinny/src/app/pages/client/explore/Server.tsx` | Server directory | +| `cinny/src/app/pages/client/explore/Featured.tsx` | Featured list | +| `cinny/src/app/pages/client/sidebar/ExploreTab.tsx` | Sidebar entry | | `cinny/src/app/hooks/useRoomDirectoryVisibility.ts` | Directory visibility | ## Data model diff --git a/docs/handoff/features/forum/HANDOFF.md b/docs/handoff/features/forum/HANDOFF.md index 8b8e238b..f2e94916 100644 --- a/docs/handoff/features/forum/HANDOFF.md +++ b/docs/handoff/features/forum/HANDOFF.md @@ -27,31 +27,31 @@ Routing: `getSpaceDefaultPath` + `shouldShowForumLobby` in path utils / room uti ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/forum/ForumFeedPage.tsx` | Main feed page | -| `cinny/src/app/features/forum/ForumSpaceLayout.tsx` | Layout shell | -| `cinny/src/app/features/forum/ForumAwareSpaceLayout.tsx` | Forum vs non-forum switch | -| `cinny/src/app/features/forum/forumFeed.ts` | Post aggregation, root detection | -| `cinny/src/app/features/forum/types.ts` | ForumTopic, ForumPost, etc. | -| `cinny/src/app/features/forum/ForumBoardView.tsx` | Board listing | -| `cinny/src/app/features/forum/ForumThreadDetail.tsx` | Thread view | -| `cinny/src/app/features/forum/ForumNewPostModal.tsx` | Create post | -| `cinny/src/app/features/forum/ForumReplyComposer.tsx` | Replies | -| `cinny/src/app/features/forum/useForumBoard.ts` | Board data hook | -| `cinny/src/app/features/forum/useForumRoomLiveUpdates.ts` | Live timeline sync | -| `cinny/src/app/pages/pathUtils.ts` | Forum routing | +| Path | Role | +| --------------------------------------------------------- | -------------------------------- | +| `cinny/src/app/features/forum/ForumFeedPage.tsx` | Main feed page | +| `cinny/src/app/features/forum/ForumSpaceLayout.tsx` | Layout shell | +| `cinny/src/app/features/forum/ForumAwareSpaceLayout.tsx` | Forum vs non-forum switch | +| `cinny/src/app/features/forum/forumFeed.ts` | Post aggregation, root detection | +| `cinny/src/app/features/forum/types.ts` | ForumTopic, ForumPost, etc. | +| `cinny/src/app/features/forum/ForumBoardView.tsx` | Board listing | +| `cinny/src/app/features/forum/ForumThreadDetail.tsx` | Thread view | +| `cinny/src/app/features/forum/ForumNewPostModal.tsx` | Create post | +| `cinny/src/app/features/forum/ForumReplyComposer.tsx` | Replies | +| `cinny/src/app/features/forum/useForumBoard.ts` | Board data hook | +| `cinny/src/app/features/forum/useForumRoomLiveUpdates.ts` | Live timeline sync | +| `cinny/src/app/pages/pathUtils.ts` | Forum routing | ## Data model -| Signal | Purpose | -|--------|---------| -| `m.room.create` `type: m.forum` | Matrix forum room type | -| `im.paarrot.room.kind: forum_space` | Paarrot forum classification | -| `com.matrixsso.title` on messages | Forum post title (legacy/custom) | -| `formatted_body` with `

` | Root post detection | -| `m.relates_to` threads | Replies and edits | -| `im.paarrot.sub_rooms` | Topic room hierarchy (see sub-rooms) | +| Signal | Purpose | +| ----------------------------------- | ------------------------------------ | +| `m.room.create` `type: m.forum` | Matrix forum room type | +| `im.paarrot.room.kind: forum_space` | Paarrot forum classification | +| `com.matrixsso.title` on messages | Forum post title (legacy/custom) | +| `formatted_body` with `

` | Root post detection | +| `m.relates_to` threads | Replies and edits | +| `im.paarrot.sub_rooms` | Topic room hierarchy (see sub-rooms) | ## Dependencies diff --git a/docs/handoff/features/global-search/HANDOFF.md b/docs/handoff/features/global-search/HANDOFF.md index 4de2e735..a4ec4e86 100644 --- a/docs/handoff/features/global-search/HANDOFF.md +++ b/docs/handoff/features/global-search/HANDOFF.md @@ -21,17 +21,17 @@ useAsyncSearch or similar for filtering ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/search/Search.tsx` | Modal UI | -| `cinny/src/app/state/searchModal.ts` | Open/close state | -| `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Sidebar entry | +| Path | Role | +| -------------------------------------------------- | ---------------- | +| `cinny/src/app/features/search/Search.tsx` | Modal UI | +| `cinny/src/app/state/searchModal.ts` | Open/close state | +| `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Sidebar entry | ## Data model -| Key | Storage | -|-----|---------| -| `searchModal` atom | memory | +| Key | Storage | +| ------------------ | ------- | +| `searchModal` atom | memory | ## Dependencies diff --git a/docs/handoff/features/home-and-sidebar/HANDOFF.md b/docs/handoff/features/home-and-sidebar/HANDOFF.md index fd59c8a2..c87ae951 100644 --- a/docs/handoff/features/home-and-sidebar/HANDOFF.md +++ b/docs/handoff/features/home-and-sidebar/HANDOFF.md @@ -24,32 +24,32 @@ DirectTab.tsx → useDirectRooms.ts ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/client/home/Home.tsx` | Home room list UI | -| `cinny/src/app/pages/client/home/useHomeRooms.ts` | Room list logic + Paarrot room kind | -| `cinny/src/app/pages/client/SidebarNav.tsx` | Sidebar tab bar | -| `cinny/src/app/pages/client/sidebar/HomeTab.tsx` | Home tab | -| `cinny/src/app/pages/client/sidebar/DirectTab.tsx` | DMs tab + favicon logos | -| `cinny/src/app/pages/client/sidebar/InboxTab.tsx` | Inbox tab | -| `cinny/src/app/pages/client/sidebar/ExploreTab.tsx` | Explore tab | -| `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Search tab | -| `cinny/src/app/pages/client/sidebar/SettingsTab.tsx` | Settings tab | -| `cinny/src/app/pages/client/sidebar/SpaceTabs.tsx` | Space context tabs | -| `cinny/src/app/pages/client/home/HomeThreadsCategory.tsx` | Threads grouping | -| `cinny/src/app/hooks/useRoomListReorder.ts` | DnD reorder | -| `cinny/src/app/hooks/useSidebarItems.ts` | Sidebar item model | +| Path | Role | +| --------------------------------------------------------- | ----------------------------------- | +| `cinny/src/app/pages/client/home/Home.tsx` | Home room list UI | +| `cinny/src/app/pages/client/home/useHomeRooms.ts` | Room list logic + Paarrot room kind | +| `cinny/src/app/pages/client/SidebarNav.tsx` | Sidebar tab bar | +| `cinny/src/app/pages/client/sidebar/HomeTab.tsx` | Home tab | +| `cinny/src/app/pages/client/sidebar/DirectTab.tsx` | DMs tab + favicon logos | +| `cinny/src/app/pages/client/sidebar/InboxTab.tsx` | Inbox tab | +| `cinny/src/app/pages/client/sidebar/ExploreTab.tsx` | Explore tab | +| `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Search tab | +| `cinny/src/app/pages/client/sidebar/SettingsTab.tsx` | Settings tab | +| `cinny/src/app/pages/client/sidebar/SpaceTabs.tsx` | Space context tabs | +| `cinny/src/app/pages/client/home/HomeThreadsCategory.tsx` | Threads grouping | +| `cinny/src/app/hooks/useRoomListReorder.ts` | DnD reorder | +| `cinny/src/app/hooks/useSidebarItems.ts` | Sidebar item model | ## Data model -| Source | Data | -|--------|------| -| `allRoomsAtom` | Joined rooms | -| `roomToUnreadAtom` | Badge state | -| `mDirectAtom` | DM room mapping | +| Source | Data | +| ---------------------- | ------------------------------- | +| `allRoomsAtom` | Joined rooms | +| `roomToUnreadAtom` | Badge state | +| `mDirectAtom` | DM room mapping | | `im.paarrot.sub_rooms` | Nested children (see sub-rooms) | -| `im.paarrot.room.kind` | Room classification | -| localStorage | Category collapse, room order | +| `im.paarrot.room.kind` | Room classification | +| localStorage | Category collapse, room order | ## Dependencies diff --git a/docs/handoff/features/inbox-and-invites/HANDOFF.md b/docs/handoff/features/inbox-and-invites/HANDOFF.md index 9b4c2601..7649e942 100644 --- a/docs/handoff/features/inbox-and-invites/HANDOFF.md +++ b/docs/handoff/features/inbox-and-invites/HANDOFF.md @@ -22,21 +22,21 @@ ClientRoomsNotificationPreferences.tsx — bulk prefs ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/client/inbox/Inbox.tsx` | Inbox layout | -| `cinny/src/app/pages/client/inbox/Invites.tsx` | Invites UI | -| `cinny/src/app/pages/client/inbox/Notifications.tsx` | Notifications list | -| `cinny/src/app/state/room-list/inviteList.ts` | `allInvitesAtom` | -| `cinny/src/app/pages/client/ClientRoomsNotificationPreferences.tsx` | Room notif prefs | -| `cinny/src/app/pages/client/sidebar/InboxTab.tsx` | Sidebar entry | -| `cinny/src/app/hooks/useRoomsNotificationPreferences.ts` | Prefs hook | +| Path | Role | +| ------------------------------------------------------------------- | ------------------ | +| `cinny/src/app/pages/client/inbox/Inbox.tsx` | Inbox layout | +| `cinny/src/app/pages/client/inbox/Invites.tsx` | Invites UI | +| `cinny/src/app/pages/client/inbox/Notifications.tsx` | Notifications list | +| `cinny/src/app/state/room-list/inviteList.ts` | `allInvitesAtom` | +| `cinny/src/app/pages/client/ClientRoomsNotificationPreferences.tsx` | Room notif prefs | +| `cinny/src/app/pages/client/sidebar/InboxTab.tsx` | Sidebar entry | +| `cinny/src/app/hooks/useRoomsNotificationPreferences.ts` | Prefs hook | ## Data model -| Source | Data | -|--------|------| -| Sync | `m.room.member` invite membership | +| Source | Data | +| ------------ | --------------------------------------- | +| Sync | `m.room.member` invite membership | | Account data | push rules, per-room notification prefs | ## Dependencies diff --git a/docs/handoff/features/join-before-navigate/HANDOFF.md b/docs/handoff/features/join-before-navigate/HANDOFF.md index 5a11b251..678816ed 100644 --- a/docs/handoff/features/join-before-navigate/HANDOFF.md +++ b/docs/handoff/features/join-before-navigate/HANDOFF.md @@ -22,12 +22,12 @@ Route: _JOIN_PATH in Router.tsx ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx` | Preview + join UI | -| `cinny/src/app/components/RoomSummaryLoader.tsx` | Fetch room preview | -| `cinny/src/app/hooks/useRoomNavigate.ts` | Post-join navigation | -| `cinny/src/app/state/joiningProgress.ts` | Join in progress UX | +| Path | Role | +| -------------------------------------------------------------------- | -------------------- | +| `cinny/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx` | Preview + join UI | +| `cinny/src/app/components/RoomSummaryLoader.tsx` | Fetch room preview | +| `cinny/src/app/hooks/useRoomNavigate.ts` | Post-join navigation | +| `cinny/src/app/state/joiningProgress.ts` | Join in progress UX | ## Data model diff --git a/docs/handoff/features/lobby-forums/HANDOFF.md b/docs/handoff/features/lobby-forums/HANDOFF.md index ab2e0cd5..96aa52fc 100644 --- a/docs/handoff/features/lobby-forums/HANDOFF.md +++ b/docs/handoff/features/lobby-forums/HANDOFF.md @@ -23,29 +23,29 @@ Space route → Lobby.tsx (SpaceCardLobby) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/lobby/Lobby.tsx` | Main lobby view | -| `cinny/src/app/features/lobby/LobbyHeader.tsx` | Space header | -| `cinny/src/app/features/lobby/LobbyHero.tsx` | Hero banner area | -| `cinny/src/app/features/lobby/SpaceHierarchy.tsx` | Room tree/cards | -| `cinny/src/app/features/lobby/DnD.tsx` | Drag and drop | -| `cinny/src/app/features/lobby/RoomItem.tsx` | Room card | -| `cinny/src/app/state/closedLobbyCategories.ts` | Collapsed categories | -| `cinny/src/app/state/hooks/closedLobbyCategories.ts` | Jotai hook | -| `cinny/src/app/pages/pathUtils.ts` | `getSpaceLobbyPath`, forum routing | -| `cinny/src/app/utils/room.ts` | `shouldShowForumLobby`, `getStateEvent` | -| `cinny/src/types/matrix/room.ts` | `RoomType.Forum`, `PaarrotRoomKind` | +| Path | Role | +| ---------------------------------------------------- | --------------------------------------- | +| `cinny/src/app/features/lobby/Lobby.tsx` | Main lobby view | +| `cinny/src/app/features/lobby/LobbyHeader.tsx` | Space header | +| `cinny/src/app/features/lobby/LobbyHero.tsx` | Hero banner area | +| `cinny/src/app/features/lobby/SpaceHierarchy.tsx` | Room tree/cards | +| `cinny/src/app/features/lobby/DnD.tsx` | Drag and drop | +| `cinny/src/app/features/lobby/RoomItem.tsx` | Room card | +| `cinny/src/app/state/closedLobbyCategories.ts` | Collapsed categories | +| `cinny/src/app/state/hooks/closedLobbyCategories.ts` | Jotai hook | +| `cinny/src/app/pages/pathUtils.ts` | `getSpaceLobbyPath`, forum routing | +| `cinny/src/app/utils/room.ts` | `shouldShowForumLobby`, `getStateEvent` | +| `cinny/src/types/matrix/room.ts` | `RoomType.Forum`, `PaarrotRoomKind` | ## Data model -| Event / field | Purpose | -|---------------|---------| -| `m.space.child` | Child room membership + `order` | -| `im.paarrot.sub_rooms` | Paarrot nested children (see sub-rooms handoff) | -| `im.paarrot.room.kind` | e.g. `forum_space` for forum behavior | -| `m.room.create` `type` | `m.forum` for forum rooms | -| Local: `closedLobbyCategories` | UI collapse state (not Matrix) | +| Event / field | Purpose | +| ------------------------------ | ----------------------------------------------- | +| `m.space.child` | Child room membership + `order` | +| `im.paarrot.sub_rooms` | Paarrot nested children (see sub-rooms handoff) | +| `im.paarrot.room.kind` | e.g. `forum_space` for forum behavior | +| `m.room.create` `type` | `m.forum` for forum rooms | +| Local: `closedLobbyCategories` | UI collapse state (not Matrix) | ## Dependencies diff --git a/docs/handoff/features/local-api/HANDOFF.md b/docs/handoff/features/local-api/HANDOFF.md index ad58d3de..943c8bbc 100644 --- a/docs/handoff/features/local-api/HANDOFF.md +++ b/docs/handoff/features/local-api/HANDOFF.md @@ -25,14 +25,14 @@ Navigation for room changes uses `setPaarrotNavigate()` registered from the Reac ## Key files -| Path | Role | -|------|------| -| `electron/api-server.js` | Express routes, IPC bridge to renderer | -| `electron/main.js` | Starts `PaarrotAPIServer` with the main window | -| `cinny/src/app/paarrot-api.ts` | Action handlers (mute, deafen, channel, message, status) | -| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Calls `initPaarrotAPI()` and `setPaarrotNavigate()` | -| `test-api.js` / `test-api.sh` | Smoke tests for endpoints | -| `paarrot-api.postman_collection.json` | Postman collection (generated) | +| Path | Role | +| ---------------------------------------------------- | -------------------------------------------------------- | +| `electron/api-server.js` | Express routes, IPC bridge to renderer | +| `electron/main.js` | Starts `PaarrotAPIServer` with the main window | +| `cinny/src/app/paarrot-api.ts` | Action handlers (mute, deafen, channel, message, status) | +| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Calls `initPaarrotAPI()` and `setPaarrotNavigate()` | +| `test-api.js` / `test-api.sh` | Smoke tests for endpoints | +| `paarrot-api.postman_collection.json` | Postman collection (generated) | ## Data model @@ -40,22 +40,22 @@ No persistent storage. Actions read/write ephemeral app state (current room, cal ### IPC actions (renderer) -| Action | Params | Returns | -|--------|--------|---------| -| `get-status` | — | mute, deafen, currentRoom, connected, userId | -| `toggle-mute` / `set-mute` | `{ muted? }` | `{ muted }` | -| `toggle-deafen` / `set-deafen` | `{ deafened? }` | `{ deafened }` | -| `change-channel` | `{ roomId }` | navigation result | -| `get-channels` | — | room list | -| `send-message` | `{ roomId, message }` | send result | -| `send-message-current` | `{ message }` | send to active room | -| `get-current-room` | — | current room id | -| `get-messages-groups` | `{ limit? }` | recent messages across group channels | -| `get-messages-dms` | `{ limit? }` | recent messages across DMs | -| `get-messages-combined` | `{ limit? }` | recent messages across groups + DMs | -| `get-unreads-groups` | — | unread group conversations | -| `get-unreads-dms` | — | unread DM conversations | -| `get-unreads-combined` | — | unread groups + DMs | +| Action | Params | Returns | +| ------------------------------ | --------------------- | -------------------------------------------- | +| `get-status` | — | mute, deafen, currentRoom, connected, userId | +| `toggle-mute` / `set-mute` | `{ muted? }` | `{ muted }` | +| `toggle-deafen` / `set-deafen` | `{ deafened? }` | `{ deafened }` | +| `change-channel` | `{ roomId }` | navigation result | +| `get-channels` | — | room list | +| `send-message` | `{ roomId, message }` | send result | +| `send-message-current` | `{ message }` | send to active room | +| `get-current-room` | — | current room id | +| `get-messages-groups` | `{ limit? }` | recent messages across group channels | +| `get-messages-dms` | `{ limit? }` | recent messages across DMs | +| `get-messages-combined` | `{ limit? }` | recent messages across groups + DMs | +| `get-unreads-groups` | — | unread group conversations | +| `get-unreads-dms` | — | unread DM conversations | +| `get-unreads-combined` | — | unread groups + DMs | ## Dependencies diff --git a/docs/handoff/features/matrix-client/HANDOFF.md b/docs/handoff/features/matrix-client/HANDOFF.md index ca62bcbb..56a73dab 100644 --- a/docs/handoff/features/matrix-client/HANDOFF.md +++ b/docs/handoff/features/matrix-client/HANDOFF.md @@ -25,23 +25,23 @@ initMatrix.ts ## Key files -| Path | Role | -|------|------| -| `cinny/src/client/initMatrix.ts` | createClient, start/stop, logout, cache clear | -| `cinny/src/client/secretStorageKeys.ts` | SSSS / secret storage callbacks | -| `cinny/src/app/pages/client/ClientRoot.tsx` | Bootstrap, providers, title bar | -| `cinny/src/app/hooks/useMatrixClient.ts` | React context for `MatrixClient` | -| `cinny/src/app/hooks/useSyncState.ts` | Sync state subscription | -| `cinny/src/app/pages/client/SyncStatus.tsx` | Sync indicator UI | -| `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Loading shell | +| Path | Role | +| --------------------------------------------------------- | --------------------------------------------- | +| `cinny/src/client/initMatrix.ts` | createClient, start/stop, logout, cache clear | +| `cinny/src/client/secretStorageKeys.ts` | SSSS / secret storage callbacks | +| `cinny/src/app/pages/client/ClientRoot.tsx` | Bootstrap, providers, title bar | +| `cinny/src/app/hooks/useMatrixClient.ts` | React context for `MatrixClient` | +| `cinny/src/app/hooks/useSyncState.ts` | Sync state subscription | +| `cinny/src/app/pages/client/SyncStatus.tsx` | Sync indicator UI | +| `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Loading shell | ## Data model -| Store | Backend | Purpose | -|-------|---------|---------| -| IndexedDB sync store | matrix-js-sdk | Room timeline cache | -| IndexedDB crypto store | matrix-js-sdk | Olm/Megolm keys | -| Session | localStorage | Auth credentials | +| Store | Backend | Purpose | +| ---------------------- | ------------- | ------------------- | +| IndexedDB sync store | matrix-js-sdk | Room timeline cache | +| IndexedDB crypto store | matrix-js-sdk | Olm/Megolm keys | +| Session | localStorage | Auth credentials | ## Dependencies diff --git a/docs/handoff/features/media-and-url-preview/HANDOFF.md b/docs/handoff/features/media-and-url-preview/HANDOFF.md index 00a48773..b3823ee0 100644 --- a/docs/handoff/features/media-and-url-preview/HANDOFF.md +++ b/docs/handoff/features/media-and-url-preview/HANDOFF.md @@ -26,18 +26,18 @@ image-viewer/, video-viewer/ — fullscreen media ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/components/upload-card/UploadCardRenderer.tsx` | Upload UI | -| `cinny/src/app/state/upload.ts` | Upload state | -| `cinny/src/app/state/room/roomInputDrafts.ts` | `TUploadItem` | -| `cinny/src/app/utils/matrix.ts` | `encryptFile`, upload helpers | -| `cinny/src/app/components/url-preview/` | Link embed cards | -| `cinny/src/app/components/image-viewer/` | Image lightbox | -| `cinny/src/app/components/video-viewer/` | Video player | -| `cinny/src/app/hooks/useMediaAuthentication.ts` | Authenticated media URLs | -| `cinny/src/app/hooks/useAuthenticatedMediaUrl.ts` | MXC → HTTP with auth | -| `cinny/src/app/components/message/content/` | Image/video/thumbnail content | +| Path | Role | +| ------------------------------------------------------------- | ----------------------------- | +| `cinny/src/app/components/upload-card/UploadCardRenderer.tsx` | Upload UI | +| `cinny/src/app/state/upload.ts` | Upload state | +| `cinny/src/app/state/room/roomInputDrafts.ts` | `TUploadItem` | +| `cinny/src/app/utils/matrix.ts` | `encryptFile`, upload helpers | +| `cinny/src/app/components/url-preview/` | Link embed cards | +| `cinny/src/app/components/image-viewer/` | Image lightbox | +| `cinny/src/app/components/video-viewer/` | Video player | +| `cinny/src/app/hooks/useMediaAuthentication.ts` | Authenticated media URLs | +| `cinny/src/app/hooks/useAuthenticatedMediaUrl.ts` | MXC → HTTP with auth | +| `cinny/src/app/components/message/content/` | Image/video/thumbnail content | ## Data model diff --git a/docs/handoff/features/message-rendering/HANDOFF.md b/docs/handoff/features/message-rendering/HANDOFF.md index 69a4153d..1d75bd6e 100644 --- a/docs/handoff/features/message-rendering/HANDOFF.md +++ b/docs/handoff/features/message-rendering/HANDOFF.md @@ -24,18 +24,18 @@ msgContent.ts — content type detection ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/components/RenderMessageContent.tsx` | Main render entry | -| `cinny/src/app/plugins/react-custom-html-parser.tsx` | HTML → React | -| `cinny/src/app/plugins/markdown/` | Markdown rules + parsers | -| `cinny/src/app/plugins/react-prism/ReactPrism.tsx` | Code highlighting | -| `cinny/src/app/plugins/emoji.ts` | Emoji shortcodes | -| `cinny/src/app/plugins/matrix-to.ts` | matrix.to link handling | -| `cinny/src/app/plugins/bad-words.ts` | Content filter hook | -| `cinny/src/app/plugins/color.ts` | Text color | -| `cinny/src/app/utils/sanitize.ts` | HTML sanitization | -| `cinny/src/app/features/room/msgContent.ts` | Message content helpers | +| Path | Role | +| ---------------------------------------------------- | ------------------------ | +| `cinny/src/app/components/RenderMessageContent.tsx` | Main render entry | +| `cinny/src/app/plugins/react-custom-html-parser.tsx` | HTML → React | +| `cinny/src/app/plugins/markdown/` | Markdown rules + parsers | +| `cinny/src/app/plugins/react-prism/ReactPrism.tsx` | Code highlighting | +| `cinny/src/app/plugins/emoji.ts` | Emoji shortcodes | +| `cinny/src/app/plugins/matrix-to.ts` | matrix.to link handling | +| `cinny/src/app/plugins/bad-words.ts` | Content filter hook | +| `cinny/src/app/plugins/color.ts` | Text color | +| `cinny/src/app/utils/sanitize.ts` | HTML sanitization | +| `cinny/src/app/features/room/msgContent.ts` | Message content helpers | ## Data model diff --git a/docs/handoff/features/message-search/HANDOFF.md b/docs/handoff/features/message-search/HANDOFF.md index 083e9151..d71bb811 100644 --- a/docs/handoff/features/message-search/HANDOFF.md +++ b/docs/handoff/features/message-search/HANDOFF.md @@ -22,13 +22,13 @@ Router may mount search under client routes ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/message-search/MessageSearch.tsx` | Main UI | -| `cinny/src/app/features/message-search/useMessageSearch.ts` | Search logic | -| `cinny/src/app/features/message-search/SearchInput.tsx` | Query field | -| `cinny/src/app/features/message-search/SearchFilters.tsx` | Filters | -| `cinny/src/app/features/message-search/SearchResultGroup.tsx` | Result list | +| Path | Role | +| ------------------------------------------------------------- | ------------ | +| `cinny/src/app/features/message-search/MessageSearch.tsx` | Main UI | +| `cinny/src/app/features/message-search/useMessageSearch.ts` | Search logic | +| `cinny/src/app/features/message-search/SearchInput.tsx` | Query field | +| `cinny/src/app/features/message-search/SearchFilters.tsx` | Filters | +| `cinny/src/app/features/message-search/SearchResultGroup.tsx` | Result list | ## Data model diff --git a/docs/handoff/features/plugins/HANDOFF.md b/docs/handoff/features/plugins/HANDOFF.md index 0ab264be..5b13c9ce 100644 --- a/docs/handoff/features/plugins/HANDOFF.md +++ b/docs/handoff/features/plugins/HANDOFF.md @@ -22,18 +22,18 @@ Plugin folder (index.js + plugin-metadata.json) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/settings/plugins/PluginLoader.tsx` | Load/enable/disable plugins | -| `cinny/src/app/features/settings/plugins/PluginAPI.ts` | Re-exports plugin-manager + app hooks | -| `cinny/src/app/features/settings/plugins/Plugins.tsx` | Settings UI (installed + marketplace) | -| `cinny/src/app/features/settings/plugins/PluginButtonSlot.tsx` | Icon button injection | -| `cinny/src/app/features/settings/plugins/PluginNavSlot.tsx` | Nav row injection | -| `cinny/src/app/features/settings/plugins/PluginSidebarSlot.tsx` | Sidebar icon injection | -| `cinny/src/app/features/settings/plugins/types.ts` | Local types | -| `cinny/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md` | Author-facing dev guide | -| `example-plugin/` | Reference plugin at repo root | -| `cinny/docs/PLUGIN_*.md` | API reference docs | +| Path | Role | +| --------------------------------------------------------------- | ------------------------------------- | +| `cinny/src/app/features/settings/plugins/PluginLoader.tsx` | Load/enable/disable plugins | +| `cinny/src/app/features/settings/plugins/PluginAPI.ts` | Re-exports plugin-manager + app hooks | +| `cinny/src/app/features/settings/plugins/Plugins.tsx` | Settings UI (installed + marketplace) | +| `cinny/src/app/features/settings/plugins/PluginButtonSlot.tsx` | Icon button injection | +| `cinny/src/app/features/settings/plugins/PluginNavSlot.tsx` | Nav row injection | +| `cinny/src/app/features/settings/plugins/PluginSidebarSlot.tsx` | Sidebar icon injection | +| `cinny/src/app/features/settings/plugins/types.ts` | Local types | +| `cinny/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md` | Author-facing dev guide | +| `example-plugin/` | Reference plugin at repo root | +| `cinny/docs/PLUGIN_*.md` | API reference docs | ## Data model diff --git a/docs/handoff/features/room-app-ui/HANDOFF.md b/docs/handoff/features/room-app-ui/HANDOFF.md index f6b521dc..d2e6c0ef 100644 --- a/docs/handoff/features/room-app-ui/HANDOFF.md +++ b/docs/handoff/features/room-app-ui/HANDOFF.md @@ -23,21 +23,21 @@ Bot → state im.paarrot.ui ## Key files -| Path | Role | -|------|------| -| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotUi`, `MessageEvent.PaarrotUiAction`, node types | -| `cinny/src/app/utils/room.ts` | `getPaarrotUiContent`, `hasRoomAppUi` | -| `cinny/src/app/features/room/Room.tsx` | Takeover branch + Show chat / Show app | -| `cinny/src/app/features/room-app/` | `RoomAppView`, schema renderer, CSS sanitize/scope | -| `cinny/src/app/features/room/RoomTimeline.tsx` | Hides `im.paarrot.ui.action` | -| `cinny/src/app/features/room-settings/permissions/usePermissionItems.ts` | Permission labels | +| Path | Role | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotUi`, `MessageEvent.PaarrotUiAction`, node types | +| `cinny/src/app/utils/room.ts` | `getPaarrotUiContent`, `hasRoomAppUi` | +| `cinny/src/app/features/room/Room.tsx` | Takeover branch + Show chat / Show app | +| `cinny/src/app/features/room-app/` | `RoomAppView`, schema renderer, CSS sanitize/scope | +| `cinny/src/app/features/room/RoomTimeline.tsx` | Hides `im.paarrot.ui.action` | +| `cinny/src/app/features/room-settings/permissions/usePermissionItems.ts` | Permission labels | ## Data model -| Event | Kind | Content | -|-------|------|---------| -| `im.paarrot.ui` | state (`""`) | `{ version, title?, css?, root }` | -| `im.paarrot.ui.action` | timeline | `{ action, component_id, value?, values?, ui_event_id? }` | +| Event | Kind | Content | +| ---------------------- | ------------ | --------------------------------------------------------- | +| `im.paarrot.ui` | state (`""`) | `{ version, title?, css?, root }` | +| `im.paarrot.ui.action` | timeline | `{ action, component_id, value?, values?, ui_event_id? }` | See [samples/](./samples/) for pasteable Developer Tools payloads. diff --git a/docs/handoff/features/room-nav/HANDOFF.md b/docs/handoff/features/room-nav/HANDOFF.md index e620a54c..4594ee82 100644 --- a/docs/handoff/features/room-nav/HANDOFF.md +++ b/docs/handoff/features/room-nav/HANDOFF.md @@ -25,13 +25,13 @@ Used by Home.tsx, space sidebars, forum sidebars ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Main room row | -| `cinny/src/app/features/room-nav/RoomNavCategoryButton.tsx` | Category header | -| `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined sub-room | +| Path | Role | +| --------------------------------------------------------------- | ----------------- | +| `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Main room row | +| `cinny/src/app/features/room-nav/RoomNavCategoryButton.tsx` | Category header | +| `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined sub-room | | `cinny/src/app/features/room-nav/CallParticipantsIndicator.tsx` | In-call indicator | -| `cinny/src/app/features/room-nav/styles.css.ts` | Nav styles | +| `cinny/src/app/features/room-nav/styles.css.ts` | Nav styles | ## Data model diff --git a/docs/handoff/features/room-settings/HANDOFF.md b/docs/handoff/features/room-settings/HANDOFF.md index 362f5e6d..aa582050 100644 --- a/docs/handoff/features/room-settings/HANDOFF.md +++ b/docs/handoff/features/room-settings/HANDOFF.md @@ -23,15 +23,15 @@ roomSettings.ts atom — which page open ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/room-settings/RoomSettings.tsx` | Settings shell | -| `cinny/src/app/features/room-settings/general/` | General tab | -| `cinny/src/app/features/room-settings/permissions/` | Permissions | -| `cinny/src/app/features/room-settings/sub-rooms/SubRooms.tsx` | Sub-rooms (Paarrot) | -| `cinny/src/app/state/roomSettings.ts` | Modal/page state | -| `cinny/src/app/state/hooks/roomSettings.ts` | Open/close hooks | -| `cinny/src/app/features/common-settings/` | Shared setting pages | +| Path | Role | +| ------------------------------------------------------------- | -------------------- | +| `cinny/src/app/features/room-settings/RoomSettings.tsx` | Settings shell | +| `cinny/src/app/features/room-settings/general/` | General tab | +| `cinny/src/app/features/room-settings/permissions/` | Permissions | +| `cinny/src/app/features/room-settings/sub-rooms/SubRooms.tsx` | Sub-rooms (Paarrot) | +| `cinny/src/app/state/roomSettings.ts` | Modal/page state | +| `cinny/src/app/state/hooks/roomSettings.ts` | Open/close hooks | +| `cinny/src/app/features/common-settings/` | Shared setting pages | ## Data model diff --git a/docs/handoff/features/room-timeline/HANDOFF.md b/docs/handoff/features/room-timeline/HANDOFF.md index 94d7ea7b..a285c773 100644 --- a/docs/handoff/features/room-timeline/HANDOFF.md +++ b/docs/handoff/features/room-timeline/HANDOFF.md @@ -27,32 +27,32 @@ Hooks: useVirtualPaginator, useRoomLatestRenderedEvent, useMarkAsRead ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/room/Room.tsx` | Room entry | -| `cinny/src/app/features/room/RoomView.tsx` | Main layout | -| `cinny/src/app/features/room/RoomTimeline.tsx` | Timeline | -| `cinny/src/app/features/room/RoomInput.tsx` | Composer | -| `cinny/src/app/features/room/ThreadView.tsx` | Thread panel | -| `cinny/src/app/features/room/RoomViewHeader.tsx` | Header bar | -| `cinny/src/app/features/room/message/Message.tsx` | Single message | -| `cinny/src/app/features/room/message/Reactions.tsx` | Reaction row | -| `cinny/src/app/features/room/message/MessageEditor.tsx` | Edit message | -| `cinny/src/app/features/room/CommandAutocomplete.tsx` | Slash commands | -| `cinny/src/app/features/room/reaction-viewer/ReactionViewer.tsx` | Who reacted | -| `cinny/src/app/features/room/jump-to-time/JumpToTime.tsx` | Time jump UI | -| `cinny/src/app/features/room/room-pin-menu/RoomPinMenu.tsx` | Pinned messages | -| `cinny/src/app/components/RenderMessageContent.tsx` | Content render + embeds | -| `cinny/src/app/hooks/useVirtualPaginator.ts` | Timeline pagination | +| Path | Role | +| ---------------------------------------------------------------- | ----------------------- | +| `cinny/src/app/features/room/Room.tsx` | Room entry | +| `cinny/src/app/features/room/RoomView.tsx` | Main layout | +| `cinny/src/app/features/room/RoomTimeline.tsx` | Timeline | +| `cinny/src/app/features/room/RoomInput.tsx` | Composer | +| `cinny/src/app/features/room/ThreadView.tsx` | Thread panel | +| `cinny/src/app/features/room/RoomViewHeader.tsx` | Header bar | +| `cinny/src/app/features/room/message/Message.tsx` | Single message | +| `cinny/src/app/features/room/message/Reactions.tsx` | Reaction row | +| `cinny/src/app/features/room/message/MessageEditor.tsx` | Edit message | +| `cinny/src/app/features/room/CommandAutocomplete.tsx` | Slash commands | +| `cinny/src/app/features/room/reaction-viewer/ReactionViewer.tsx` | Who reacted | +| `cinny/src/app/features/room/jump-to-time/JumpToTime.tsx` | Time jump UI | +| `cinny/src/app/features/room/room-pin-menu/RoomPinMenu.tsx` | Pinned messages | +| `cinny/src/app/components/RenderMessageContent.tsx` | Content render + embeds | +| `cinny/src/app/hooks/useVirtualPaginator.ts` | Timeline pagination | ## Data model -| Source | Data | -|--------|------| -| Matrix sync | `m.room.message`, edits, reactions, pins | -| Room account data | drafts (`roomInputDrafts`) | -| `im.paarrot.embed_filters` | Personal embed blocks | -| `im.paarrot.room.embed_filters` | Room-wide embed blocks | +| Source | Data | +| ------------------------------- | ---------------------------------------- | +| Matrix sync | `m.room.message`, edits, reactions, pins | +| Room account data | drafts (`roomInputDrafts`) | +| `im.paarrot.embed_filters` | Personal embed blocks | +| `im.paarrot.room.embed_filters` | Room-wide embed blocks | ## Dependencies diff --git a/docs/handoff/features/routing-and-navigation/HANDOFF.md b/docs/handoff/features/routing-and-navigation/HANDOFF.md index 3cf50b24..c49e01a4 100644 --- a/docs/handoff/features/routing-and-navigation/HANDOFF.md +++ b/docs/handoff/features/routing-and-navigation/HANDOFF.md @@ -24,26 +24,26 @@ Router.tsx — route tree + loaders/guards ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/Router.tsx` | Full route tree | -| `cinny/src/app/pages/paths.ts` | Path constants | -| `cinny/src/app/pages/pathUtils.ts` | Path builder utilities | -| `cinny/src/app/pages/App.tsx` | RouterProvider setup | -| `cinny/src/app/pages/client/ClientLayout.tsx` | Authenticated layout shell | -| `cinny/src/app/pages/client/SidebarNav.tsx` | Left sidebar tabs | -| `cinny/src/app/pages/MobileFriendly.tsx` | Mobile nav adapters | -| `cinny/src/app/hooks/useRoomNavigate.ts` | Imperative room navigation | -| `cinny/src/app/hooks/useNavToActivePathMapper.ts` | Restore last path | -| `cinny/src/app/pages/afterLoginRedirectPath.ts` | Login redirect | -| `cinny/src/app/components/AnimatedOutlet.tsx` | Route transitions | +| Path | Role | +| ------------------------------------------------- | -------------------------- | +| `cinny/src/app/pages/Router.tsx` | Full route tree | +| `cinny/src/app/pages/paths.ts` | Path constants | +| `cinny/src/app/pages/pathUtils.ts` | Path builder utilities | +| `cinny/src/app/pages/App.tsx` | RouterProvider setup | +| `cinny/src/app/pages/client/ClientLayout.tsx` | Authenticated layout shell | +| `cinny/src/app/pages/client/SidebarNav.tsx` | Left sidebar tabs | +| `cinny/src/app/pages/MobileFriendly.tsx` | Mobile nav adapters | +| `cinny/src/app/hooks/useRoomNavigate.ts` | Imperative room navigation | +| `cinny/src/app/hooks/useNavToActivePathMapper.ts` | Restore last path | +| `cinny/src/app/pages/afterLoginRedirectPath.ts` | Login redirect | +| `cinny/src/app/components/AnimatedOutlet.tsx` | Route transitions | ## Data model -| Key | Purpose | -|-----|---------| -| `navToActivePath` atom | Per-context last URL | -| URL path params | roomId, spaceId, eventId | +| Key | Purpose | +| ---------------------- | ------------------------ | +| `navToActivePath` atom | Per-context last URL | +| URL path params | roomId, spaceId, eventId | ## Dependencies diff --git a/docs/handoff/features/space-settings/HANDOFF.md b/docs/handoff/features/space-settings/HANDOFF.md index d4d79f41..6723c6e5 100644 --- a/docs/handoff/features/space-settings/HANDOFF.md +++ b/docs/handoff/features/space-settings/HANDOFF.md @@ -21,13 +21,13 @@ spaceSettings.ts atom ## Key files -| Path | Role | -|------|------| +| Path | Role | +| --------------------------------------------------------- | -------------- | | `cinny/src/app/features/space-settings/SpaceSettings.tsx` | Settings shell | -| `cinny/src/app/features/space-settings/general/` | General tab | -| `cinny/src/app/features/space-settings/permissions/` | Permissions | -| `cinny/src/app/state/spaceSettings.ts` | Open state | -| `cinny/src/app/state/hooks/spaceSettings.ts` | Hooks | +| `cinny/src/app/features/space-settings/general/` | General tab | +| `cinny/src/app/features/space-settings/permissions/` | Permissions | +| `cinny/src/app/state/spaceSettings.ts` | Open state | +| `cinny/src/app/state/hooks/spaceSettings.ts` | Hooks | ## Data model diff --git a/docs/handoff/features/state-management/HANDOFF.md b/docs/handoff/features/state-management/HANDOFF.md index 2c129b87..896a3119 100644 --- a/docs/handoff/features/state-management/HANDOFF.md +++ b/docs/handoff/features/state-management/HANDOFF.md @@ -22,35 +22,35 @@ ClientBindAtoms.tsx binds Matrix events → atom updates ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/state/settings.ts` | User settings atom | -| `cinny/src/app/state/sessions.ts` | Auth sessions | -| `cinny/src/app/state/room-list/roomList.ts` | `allRoomsAtom`, ordering | -| `cinny/src/app/state/room/roomToUnread.ts` | Unread counts | -| `cinny/src/app/state/room/roomInputDrafts.ts` | Composer drafts + uploads | -| `cinny/src/app/state/room/roomToParents.ts` | Space parent mapping | -| `cinny/src/app/state/mDirectList.ts` | Direct message index | -| `cinny/src/app/state/navToActivePath.ts` | Last active path per context | -| `cinny/src/app/state/closedNavCategories.ts` | Collapsed nav sections | -| `cinny/src/app/state/closedLobbyCategories.ts` | Collapsed lobby categories | -| `cinny/src/app/state/createRoomModal.ts` | Create room modal state | -| `cinny/src/app/state/createSpaceModal.ts` | Create space modal state | -| `cinny/src/app/state/searchModal.ts` | Global search modal | -| `cinny/src/app/state/utils/atomWithLocalStorage.ts` | Persistence helper | -| `cinny/src/app/pages/client/ClientBindAtoms.ts` | Matrix → atom bindings | +| Path | Role | +| --------------------------------------------------- | ---------------------------- | +| `cinny/src/app/state/settings.ts` | User settings atom | +| `cinny/src/app/state/sessions.ts` | Auth sessions | +| `cinny/src/app/state/room-list/roomList.ts` | `allRoomsAtom`, ordering | +| `cinny/src/app/state/room/roomToUnread.ts` | Unread counts | +| `cinny/src/app/state/room/roomInputDrafts.ts` | Composer drafts + uploads | +| `cinny/src/app/state/room/roomToParents.ts` | Space parent mapping | +| `cinny/src/app/state/mDirectList.ts` | Direct message index | +| `cinny/src/app/state/navToActivePath.ts` | Last active path per context | +| `cinny/src/app/state/closedNavCategories.ts` | Collapsed nav sections | +| `cinny/src/app/state/closedLobbyCategories.ts` | Collapsed lobby categories | +| `cinny/src/app/state/createRoomModal.ts` | Create room modal state | +| `cinny/src/app/state/createSpaceModal.ts` | Create space modal state | +| `cinny/src/app/state/searchModal.ts` | Global search modal | +| `cinny/src/app/state/utils/atomWithLocalStorage.ts` | Persistence helper | +| `cinny/src/app/pages/client/ClientBindAtoms.ts` | Matrix → atom bindings | ## Data model Most state is **local only** (not Matrix). Exceptions: settings that also write account data (notification prefs via separate hooks). -| Atom area | Persists? | -|-----------|-----------| -| settings | localStorage | -| room list order | localStorage | -| drafts | localStorage | -| unread | memory (derived from sync) | -| modals | memory | +| Atom area | Persists? | +| --------------- | -------------------------- | +| settings | localStorage | +| room list order | localStorage | +| drafts | localStorage | +| unread | memory (derived from sync) | +| modals | memory | ## Dependencies diff --git a/docs/handoff/features/streamdeck/HANDOFF.md b/docs/handoff/features/streamdeck/HANDOFF.md index a9d69f63..9ef9bc7c 100644 --- a/docs/handoff/features/streamdeck/HANDOFF.md +++ b/docs/handoff/features/streamdeck/HANDOFF.md @@ -21,15 +21,15 @@ Stream Deck button press ## Key files -| Path | Role | -|------|------| -| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/manifest.json` | Plugin manifest | -| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.js` | Action implementations | -| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.html` | Property inspector UI | -| `streamdeck-plugin/build.js` | Build `.streamDeckPlugin` bundle | -| `streamdeck-plugin/validate.js` | Manifest validation | -| `streamdeck-plugin/README.md` | User install guide | -| `streamdeck-plugin/QUICKSTART.md` | Dev quickstart | +| Path | Role | +| --------------------------------------------------------------------- | -------------------------------- | +| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/manifest.json` | Plugin manifest | +| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.js` | Action implementations | +| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.html` | Property inspector UI | +| `streamdeck-plugin/build.js` | Build `.streamDeckPlugin` bundle | +| `streamdeck-plugin/validate.js` | Manifest validation | +| `streamdeck-plugin/README.md` | User install guide | +| `streamdeck-plugin/QUICKSTART.md` | Dev quickstart | ## Data model diff --git a/docs/handoff/features/sub-rooms/HANDOFF.md b/docs/handoff/features/sub-rooms/HANDOFF.md index d92c5773..4c08f519 100644 --- a/docs/handoff/features/sub-rooms/HANDOFF.md +++ b/docs/handoff/features/sub-rooms/HANDOFF.md @@ -25,21 +25,21 @@ Room state: im.paarrot.sub_rooms { children: string[] } ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/hooks/useRoomSubRooms.ts` | Hook + `PaarrotSubRoomsContent` type | -| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotSubRooms` | -| `cinny/src/app/pages/client/home/Home.tsx` | Renders nested list | -| `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Add sub-room action | -| `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined child UI | -| `cinny/src/app/features/room-settings/sub-rooms/SubRooms.tsx` | Settings page | -| `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Appends new room to parent state | -| `cinny/src/app/features/lobby/SpaceHierarchy.tsx` | Lobby hierarchy integration | +| Path | Role | +| ------------------------------------------------------------- | ------------------------------------ | +| `cinny/src/app/hooks/useRoomSubRooms.ts` | Hook + `PaarrotSubRoomsContent` type | +| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotSubRooms` | +| `cinny/src/app/pages/client/home/Home.tsx` | Renders nested list | +| `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Add sub-room action | +| `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined child UI | +| `cinny/src/app/features/room-settings/sub-rooms/SubRooms.tsx` | Settings page | +| `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Appends new room to parent state | +| `cinny/src/app/features/lobby/SpaceHierarchy.tsx` | Lobby hierarchy integration | ## Data model -| Event | State key | Content | -|-------|-----------|---------| +| Event | State key | Content | +| ---------------------- | ------------ | ---------------------------------------------------- | | `im.paarrot.sub_rooms` | `""` (empty) | `{ children: string[] }` — room IDs in display order | Power levels: treat like other state events; editors need `state_default` or explicit level for `im.paarrot.sub_rooms`. diff --git a/docs/handoff/features/themes-and-appearance/HANDOFF.md b/docs/handoff/features/themes-and-appearance/HANDOFF.md index 884f3273..3ef27f63 100644 --- a/docs/handoff/features/themes-and-appearance/HANDOFF.md +++ b/docs/handoff/features/themes-and-appearance/HANDOFF.md @@ -24,21 +24,21 @@ vanilla-extract / folds tokens in colors.css.ts ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/pages/ThemeManager.tsx` | Route-level theme | -| `cinny/src/app/state/settings.ts` | Settings including theme | -| `cinny/src/app/hooks/useTheme.ts` | Theme hook | -| `cinny/src/colors.css.ts` | Color tokens | -| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Page zoom CSS | -| `cinny/src/app/hooks/useViewTransitions.ts` | View transitions | -| `cinny/src/app/hooks/useMessageSpacing.ts` | Message density | -| `cinny/public/themes/` | Bundled theme files (if present) | +| Path | Role | +| ---------------------------------------------------- | -------------------------------- | +| `cinny/src/app/pages/ThemeManager.tsx` | Route-level theme | +| `cinny/src/app/state/settings.ts` | Settings including theme | +| `cinny/src/app/hooks/useTheme.ts` | Theme hook | +| `cinny/src/colors.css.ts` | Color tokens | +| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Page zoom CSS | +| `cinny/src/app/hooks/useViewTransitions.ts` | View transitions | +| `cinny/src/app/hooks/useMessageSpacing.ts` | Message density | +| `cinny/public/themes/` | Bundled theme files (if present) | ## Data model -| Key | Storage | -|-----|---------| +| Key | Storage | +| -------------- | ------------------------------------------- | | `settingsAtom` | theme, pageZoom, messageSpacing, emojiStyle | ## Dependencies diff --git a/docs/handoff/features/user-settings/HANDOFF.md b/docs/handoff/features/user-settings/HANDOFF.md index 95f9dbcc..8c885d0c 100644 --- a/docs/handoff/features/user-settings/HANDOFF.md +++ b/docs/handoff/features/user-settings/HANDOFF.md @@ -24,25 +24,25 @@ SettingsPages enum ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/settings/Settings.tsx` | Settings modal shell | -| `cinny/src/app/features/settings/general/General.tsx` | General prefs | +| Path | Role | +| ----------------------------------------------------- | ------------------------- | +| `cinny/src/app/features/settings/Settings.tsx` | Settings modal shell | +| `cinny/src/app/features/settings/general/General.tsx` | General prefs | | `cinny/src/app/features/settings/account/Profile.tsx` | Profile + avatar metadata | -| `cinny/src/app/features/settings/notifications/` | Notification rules | -| `cinny/src/app/features/settings/audio/Audio.tsx` | Call audio devices | -| `cinny/src/app/features/settings/devices/` | Sessions & verification | -| `cinny/src/app/features/settings/about/About.tsx` | About page | -| `cinny/src/app/state/settings.ts` | Settings atom | -| `cinny/src/app/pages/client/sidebar/SettingsTab.tsx` | Entry point | +| `cinny/src/app/features/settings/notifications/` | Notification rules | +| `cinny/src/app/features/settings/audio/Audio.tsx` | Call audio devices | +| `cinny/src/app/features/settings/devices/` | Sessions & verification | +| `cinny/src/app/features/settings/about/About.tsx` | About page | +| `cinny/src/app/state/settings.ts` | Settings atom | +| `cinny/src/app/pages/client/sidebar/SettingsTab.tsx` | Entry point | ## Data model -| Key | Storage | -|-----|---------| +| Key | Storage | +| -------------- | --------------------------------------------- | | `settingsAtom` | localStorage (theme, zoom, emoji style, etc.) | -| Profile | Matrix account data + avatar MXC | -| Push rules | Homeserver account data | +| Profile | Matrix account data + avatar MXC | +| Push rules | Homeserver account data | ## Dependencies diff --git a/docs/handoff/features/voice-calls/HANDOFF.md b/docs/handoff/features/voice-calls/HANDOFF.md index 09a0df7b..62c54730 100644 --- a/docs/handoff/features/voice-calls/HANDOFF.md +++ b/docs/handoff/features/voice-calls/HANDOFF.md @@ -23,26 +23,26 @@ useCallService (CallProvider) ## Key files -| Path | Role | -|------|------| -| `cinny/src/app/features/call/useCall.ts` | React context, global CallService ref | -| `cinny/src/app/features/call/CallService.ts` | Core call logic | -| `cinny/src/app/features/call/types.ts` | CallState, ActiveCall, events | -| `cinny/src/app/features/call/useRtcConfig.ts` | Homeserver RTC / LiveKit discovery | -| `cinny/src/app/features/call/CallOverlay.tsx` | Full-screen call UI | -| `cinny/src/app/features/call/DockedCallPanel.tsx` | Docked UI | -| `cinny/src/app/features/call/SidebarDockedCallPanel.tsx` | Sidebar variant | -| `cinny/src/app/features/call/useRemoteCursor.ts` | Screen-share cursor sync | -| `cinny/src/app/features/call/CallSounds.ts` | Join/leave sounds | -| `cinny/src/app/features/room-nav/CallParticipantsIndicator.tsx` | Nav badge | -| `cinny/src/types/matrix/room.ts` | `StateEvent.CallMember` | +| Path | Role | +| --------------------------------------------------------------- | ------------------------------------- | +| `cinny/src/app/features/call/useCall.ts` | React context, global CallService ref | +| `cinny/src/app/features/call/CallService.ts` | Core call logic | +| `cinny/src/app/features/call/types.ts` | CallState, ActiveCall, events | +| `cinny/src/app/features/call/useRtcConfig.ts` | Homeserver RTC / LiveKit discovery | +| `cinny/src/app/features/call/CallOverlay.tsx` | Full-screen call UI | +| `cinny/src/app/features/call/DockedCallPanel.tsx` | Docked UI | +| `cinny/src/app/features/call/SidebarDockedCallPanel.tsx` | Sidebar variant | +| `cinny/src/app/features/call/useRemoteCursor.ts` | Screen-share cursor sync | +| `cinny/src/app/features/call/CallSounds.ts` | Join/leave sounds | +| `cinny/src/app/features/room-nav/CallParticipantsIndicator.tsx` | Nav badge | +| `cinny/src/types/matrix/room.ts` | `StateEvent.CallMember` | ## Data model -| Key | Scope | Notes | -|-----|-------|-------| -| `org.matrix.msc3401.call.member` | Room state | Call membership | -| LiveKit JWT / room | Ephemeral | From homeserver RTC focus | +| Key | Scope | Notes | +| -------------------------------- | ---------- | ------------------------- | +| `org.matrix.msc3401.call.member` | Room state | Call membership | +| LiveKit JWT / room | Ephemeral | From homeserver RTC focus | Call mute/deafen/video state lives in `CallService` memory, not Matrix account data. diff --git a/eslint.config.js b/eslint.config.js index f8ff94cb..3cfc3141 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -18,7 +18,8 @@ const files = ['**/*.js', '**/*.mjs', '**/*.cjs', '**/*.ts', '**/*.tsx']; // eslint-config-airbnb 19 is legacy-only: `extends` are paths to rule modules and flat config // rejects `extends`/`env`/`parserOptions`, so take their rules and set the env here instead. -const airbnbRules = (config) => (config.extends || []).flatMap((p) => airbnbRules(require(p))).concat(config); +const airbnbRules = (config) => + (config.extends || []).flatMap((p) => airbnbRules(require(p))).concat(config); // Plugins are registered once (redefining a plugin is an error) and fixed up so the legacy // rules that call context.getFilename still work. @@ -53,38 +54,41 @@ export default [ rules: { 'linebreak-style': 0, 'no-underscore-dangle': 0, - "no-shadow": "off", + 'no-shadow': 'off', - "import/prefer-default-export": "off", - "import/extensions": "off", - "import/no-unresolved": "off", - "import/no-extraneous-dependencies": [ - "error", + 'import/prefer-default-export': 'off', + 'import/extensions': 'off', + 'import/no-unresolved': 'off', + 'import/no-extraneous-dependencies': [ + 'error', { devDependencies: true, }, ], - 'react/no-unstable-nested-components': [ + 'react/no-unstable-nested-components': ['error', { allowAsProps: true }], + 'react/jsx-filename-extension': [ 'error', - { allowAsProps: true }, - ], - "react/jsx-filename-extension": [ - "error", { - extensions: [".tsx", ".jsx"], + extensions: ['.tsx', '.jsx'], }, ], - "react/require-default-props": "off", - "react/jsx-props-no-spreading": "off", - "react-hooks/rules-of-hooks": "error", - "react-hooks/exhaustive-deps": "error", + 'react/require-default-props': 'off', + 'react/jsx-props-no-spreading': 'off', + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'error', - "@typescript-eslint/no-unused-vars": "error", - "@typescript-eslint/no-shadow": "error" + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/no-shadow': 'error', }, }, - ].flatMap((config) => (Array.isArray(config) ? config : [config]).map((config) => ({ files, rules: config.rules || {}, ...(config.settings ? { settings: config.settings } : {}) }))), + ].flatMap((config) => + (Array.isArray(config) ? config : [config]).map((config) => ({ + files, + rules: config.rules || {}, + ...(config.settings ? { settings: config.settings } : {}), + })), + ), { files: ['*.ts'], rules: { 'no-undef': 'off' } }, ]; diff --git a/index.html b/index.html index 3d1d48b3..2334c198 100644 --- a/index.html +++ b/index.html @@ -1,10 +1,13 @@ - + - + Paarrot @@ -12,10 +15,7 @@ name="description" content="A Matrix client where you can enjoy the conversation using simple, elegant and secure interface protected by e2ee with the power of open source." /> - + @@ -90,7 +90,7 @@ href="./public/res/apple/apple-touch-icon-180x180.png" /> - + diff --git a/playground.html b/playground.html index 8724897f..c9ddf9d5 100644 --- a/playground.html +++ b/playground.html @@ -5,7 +5,7 @@ Component Playground - +
diff --git a/public/gif.worker.js b/public/gif.worker.js index 269624e6..fd590f53 100644 --- a/public/gif.worker.js +++ b/public/gif.worker.js @@ -1,3 +1,859 @@ // gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j=0&&x1+x=0&&y1+y>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<0)cur_accum|=code<=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<>betashift;var betagamma=intbias<>3;var radiusbiasshift=6;var radiusbias=1<>3);var i,v;for(i=0;i>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(jlo){a=radpower[m++];if(jlo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i>intbiasshift-netbiasshift);if(biasdist>betashift;freq[i]-=betafreq;bias[i]+=betafreq<>1;for(j=previouscol+1;j>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i=0){if(i=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j= ByteArray.pageSize) this.newPage(); + this.pages[this.page][this.cursor++] = val; + }; + ByteArray.prototype.writeUTFBytes = function (string) { + for (var l = string.length, i = 0; i < l; i++) this.writeByte(string.charCodeAt(i)); + }; + ByteArray.prototype.writeBytes = function (array, offset, length) { + for (var l = length || array.length, i = offset || 0; i < l; i++) + this.writeByte(array[i]); + }; + function GIFEncoder(width, height) { + this.width = ~~width; + this.height = ~~height; + this.transparent = null; + this.transIndex = 0; + this.repeat = -1; + this.delay = 0; + this.image = null; + this.pixels = null; + this.indexedPixels = null; + this.colorDepth = null; + this.colorTab = null; + this.neuQuant = null; + this.usedEntry = new Array(); + this.palSize = 7; + this.dispose = -1; + this.firstFrame = true; + this.sample = 10; + this.dither = false; + this.globalPalette = false; + this.out = new ByteArray(); + } + GIFEncoder.prototype.setDelay = function (milliseconds) { + this.delay = Math.round(milliseconds / 10); + }; + GIFEncoder.prototype.setFrameRate = function (fps) { + this.delay = Math.round(100 / fps); + }; + GIFEncoder.prototype.setDispose = function (disposalCode) { + if (disposalCode >= 0) this.dispose = disposalCode; + }; + GIFEncoder.prototype.setRepeat = function (repeat) { + this.repeat = repeat; + }; + GIFEncoder.prototype.setTransparent = function (color) { + this.transparent = color; + }; + GIFEncoder.prototype.addFrame = function (imageData) { + this.image = imageData; + this.colorTab = + this.globalPalette && this.globalPalette.slice ? this.globalPalette : null; + this.getImagePixels(); + this.analyzePixels(); + if (this.globalPalette === true) this.globalPalette = this.colorTab; + if (this.firstFrame) { + this.writeLSD(); + this.writePalette(); + if (this.repeat >= 0) { + this.writeNetscapeExt(); + } + } + this.writeGraphicCtrlExt(); + this.writeImageDesc(); + if (!this.firstFrame && !this.globalPalette) this.writePalette(); + this.writePixels(); + this.firstFrame = false; + }; + GIFEncoder.prototype.finish = function () { + this.out.writeByte(59); + }; + GIFEncoder.prototype.setQuality = function (quality) { + if (quality < 1) quality = 1; + this.sample = quality; + }; + GIFEncoder.prototype.setDither = function (dither) { + if (dither === true) dither = 'FloydSteinberg'; + this.dither = dither; + }; + GIFEncoder.prototype.setGlobalPalette = function (palette) { + this.globalPalette = palette; + }; + GIFEncoder.prototype.getGlobalPalette = function () { + return ( + (this.globalPalette && this.globalPalette.slice && this.globalPalette.slice(0)) || + this.globalPalette + ); + }; + GIFEncoder.prototype.writeHeader = function () { + this.out.writeUTFBytes('GIF89a'); + }; + GIFEncoder.prototype.analyzePixels = function () { + if (!this.colorTab) { + this.neuQuant = new NeuQuant(this.pixels, this.sample); + this.neuQuant.buildColormap(); + this.colorTab = this.neuQuant.getColormap(); + } + if (this.dither) { + this.ditherPixels( + this.dither.replace('-serpentine', ''), + this.dither.match(/-serpentine/) !== null, + ); + } else { + this.indexPixels(); + } + this.pixels = null; + this.colorDepth = 8; + this.palSize = 7; + if (this.transparent !== null) { + this.transIndex = this.findClosest(this.transparent, true); + } + }; + GIFEncoder.prototype.indexPixels = function (imgq) { + var nPix = this.pixels.length / 3; + this.indexedPixels = new Uint8Array(nPix); + var k = 0; + for (var j = 0; j < nPix; j++) { + var index = this.findClosestRGB( + this.pixels[k++] & 255, + this.pixels[k++] & 255, + this.pixels[k++] & 255, + ); + this.usedEntry[index] = true; + this.indexedPixels[j] = index; + } + }; + GIFEncoder.prototype.ditherPixels = function (kernel, serpentine) { + var kernels = { + FalseFloydSteinberg: [ + [3 / 8, 1, 0], + [3 / 8, 0, 1], + [2 / 8, 1, 1], + ], + FloydSteinberg: [ + [7 / 16, 1, 0], + [3 / 16, -1, 1], + [5 / 16, 0, 1], + [1 / 16, 1, 1], + ], + Stucki: [ + [8 / 42, 1, 0], + [4 / 42, 2, 0], + [2 / 42, -2, 1], + [4 / 42, -1, 1], + [8 / 42, 0, 1], + [4 / 42, 1, 1], + [2 / 42, 2, 1], + [1 / 42, -2, 2], + [2 / 42, -1, 2], + [4 / 42, 0, 2], + [2 / 42, 1, 2], + [1 / 42, 2, 2], + ], + Atkinson: [ + [1 / 8, 1, 0], + [1 / 8, 2, 0], + [1 / 8, -1, 1], + [1 / 8, 0, 1], + [1 / 8, 1, 1], + [1 / 8, 0, 2], + ], + }; + if (!kernel || !kernels[kernel]) { + throw 'Unknown dithering kernel: ' + kernel; + } + var ds = kernels[kernel]; + var index = 0, + height = this.height, + width = this.width, + data = this.pixels; + var direction = serpentine ? -1 : 1; + this.indexedPixels = new Uint8Array(this.pixels.length / 3); + for (var y = 0; y < height; y++) { + if (serpentine) direction = direction * -1; + for ( + var x = direction == 1 ? 0 : width - 1, xend = direction == 1 ? width : 0; + x !== xend; + x += direction + ) { + index = y * width + x; + var idx = index * 3; + var r1 = data[idx]; + var g1 = data[idx + 1]; + var b1 = data[idx + 2]; + idx = this.findClosestRGB(r1, g1, b1); + this.usedEntry[idx] = true; + this.indexedPixels[index] = idx; + idx *= 3; + var r2 = this.colorTab[idx]; + var g2 = this.colorTab[idx + 1]; + var b2 = this.colorTab[idx + 2]; + var er = r1 - r2; + var eg = g1 - g2; + var eb = b1 - b2; + for ( + var i = direction == 1 ? 0 : ds.length - 1, end = direction == 1 ? ds.length : 0; + i !== end; + i += direction + ) { + var x1 = ds[i][1]; + var y1 = ds[i][2]; + if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) { + var d = ds[i][0]; + idx = index + x1 + y1 * width; + idx *= 3; + data[idx] = Math.max(0, Math.min(255, data[idx] + er * d)); + data[idx + 1] = Math.max(0, Math.min(255, data[idx + 1] + eg * d)); + data[idx + 2] = Math.max(0, Math.min(255, data[idx + 2] + eb * d)); + } + } + } + } + }; + GIFEncoder.prototype.findClosest = function (c, used) { + return this.findClosestRGB((c & 16711680) >> 16, (c & 65280) >> 8, c & 255, used); + }; + GIFEncoder.prototype.findClosestRGB = function (r, g, b, used) { + if (this.colorTab === null) return -1; + if (this.neuQuant && !used) { + return this.neuQuant.lookupRGB(r, g, b); + } + var c = b | (g << 8) | (r << 16); + var minpos = 0; + var dmin = 256 * 256 * 256; + var len = this.colorTab.length; + for (var i = 0, index = 0; i < len; index++) { + var dr = r - (this.colorTab[i++] & 255); + var dg = g - (this.colorTab[i++] & 255); + var db = b - (this.colorTab[i++] & 255); + var d = dr * dr + dg * dg + db * db; + if ((!used || this.usedEntry[index]) && d < dmin) { + dmin = d; + minpos = index; + } + } + return minpos; + }; + GIFEncoder.prototype.getImagePixels = function () { + var w = this.width; + var h = this.height; + this.pixels = new Uint8Array(w * h * 3); + var data = this.image; + var srcPos = 0; + var count = 0; + for (var i = 0; i < h; i++) { + for (var j = 0; j < w; j++) { + this.pixels[count++] = data[srcPos++]; + this.pixels[count++] = data[srcPos++]; + this.pixels[count++] = data[srcPos++]; + srcPos++; + } + } + }; + GIFEncoder.prototype.writeGraphicCtrlExt = function () { + this.out.writeByte(33); + this.out.writeByte(249); + this.out.writeByte(4); + var transp, disp; + if (this.transparent === null) { + transp = 0; + disp = 0; + } else { + transp = 1; + disp = 2; + } + if (this.dispose >= 0) { + disp = dispose & 7; + } + disp <<= 2; + this.out.writeByte(0 | disp | 0 | transp); + this.writeShort(this.delay); + this.out.writeByte(this.transIndex); + this.out.writeByte(0); + }; + GIFEncoder.prototype.writeImageDesc = function () { + this.out.writeByte(44); + this.writeShort(0); + this.writeShort(0); + this.writeShort(this.width); + this.writeShort(this.height); + if (this.firstFrame || this.globalPalette) { + this.out.writeByte(0); + } else { + this.out.writeByte(128 | 0 | 0 | 0 | this.palSize); + } + }; + GIFEncoder.prototype.writeLSD = function () { + this.writeShort(this.width); + this.writeShort(this.height); + this.out.writeByte(128 | 112 | 0 | this.palSize); + this.out.writeByte(0); + this.out.writeByte(0); + }; + GIFEncoder.prototype.writeNetscapeExt = function () { + this.out.writeByte(33); + this.out.writeByte(255); + this.out.writeByte(11); + this.out.writeUTFBytes('NETSCAPE2.0'); + this.out.writeByte(3); + this.out.writeByte(1); + this.writeShort(this.repeat); + this.out.writeByte(0); + }; + GIFEncoder.prototype.writePalette = function () { + this.out.writeBytes(this.colorTab); + var n = 3 * 256 - this.colorTab.length; + for (var i = 0; i < n; i++) this.out.writeByte(0); + }; + GIFEncoder.prototype.writeShort = function (pValue) { + this.out.writeByte(pValue & 255); + this.out.writeByte((pValue >> 8) & 255); + }; + GIFEncoder.prototype.writePixels = function () { + var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth); + enc.encode(this.out); + }; + GIFEncoder.prototype.stream = function () { + return this.out; + }; + module.exports = GIFEncoder; + }, + { './LZWEncoder.js': 2, './TypedNeuQuant.js': 3 }, + ], + 2: [ + function (require, module, exports) { + var EOF = -1; + var BITS = 12; + var HSIZE = 5003; + var masks = [ + 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, + ]; + function LZWEncoder(width, height, pixels, colorDepth) { + var initCodeSize = Math.max(2, colorDepth); + var accum = new Uint8Array(256); + var htab = new Int32Array(HSIZE); + var codetab = new Int32Array(HSIZE); + var cur_accum, + cur_bits = 0; + var a_count; + var free_ent = 0; + var maxcode; + var clear_flg = false; + var g_init_bits, ClearCode, EOFCode; + function char_out(c, outs) { + accum[a_count++] = c; + if (a_count >= 254) flush_char(outs); + } + function cl_block(outs) { + cl_hash(HSIZE); + free_ent = ClearCode + 2; + clear_flg = true; + output(ClearCode, outs); + } + function cl_hash(hsize) { + for (var i = 0; i < hsize; ++i) htab[i] = -1; + } + function compress(init_bits, outs) { + var fcode, c, i, ent, disp, hsize_reg, hshift; + g_init_bits = init_bits; + clear_flg = false; + n_bits = g_init_bits; + maxcode = MAXCODE(n_bits); + ClearCode = 1 << (init_bits - 1); + EOFCode = ClearCode + 1; + free_ent = ClearCode + 2; + a_count = 0; + ent = nextPixel(); + hshift = 0; + for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift; + hshift = 8 - hshift; + hsize_reg = HSIZE; + cl_hash(hsize_reg); + output(ClearCode, outs); + outer_loop: while ((c = nextPixel()) != EOF) { + fcode = (c << BITS) + ent; + i = (c << hshift) ^ ent; + if (htab[i] === fcode) { + ent = codetab[i]; + continue; + } else if (htab[i] >= 0) { + disp = hsize_reg - i; + if (i === 0) disp = 1; + do { + if ((i -= disp) < 0) i += hsize_reg; + if (htab[i] === fcode) { + ent = codetab[i]; + continue outer_loop; + } + } while (htab[i] >= 0); + } + output(ent, outs); + ent = c; + if (free_ent < 1 << BITS) { + codetab[i] = free_ent++; + htab[i] = fcode; + } else { + cl_block(outs); + } + } + output(ent, outs); + output(EOFCode, outs); + } + function encode(outs) { + outs.writeByte(initCodeSize); + remaining = width * height; + curPixel = 0; + compress(initCodeSize + 1, outs); + outs.writeByte(0); + } + function flush_char(outs) { + if (a_count > 0) { + outs.writeByte(a_count); + outs.writeBytes(accum, 0, a_count); + a_count = 0; + } + } + function MAXCODE(n_bits) { + return (1 << n_bits) - 1; + } + function nextPixel() { + if (remaining === 0) return EOF; + --remaining; + var pix = pixels[curPixel++]; + return pix & 255; + } + function output(code, outs) { + cur_accum &= masks[cur_bits]; + if (cur_bits > 0) cur_accum |= code << cur_bits; + else cur_accum = code; + cur_bits += n_bits; + while (cur_bits >= 8) { + char_out(cur_accum & 255, outs); + cur_accum >>= 8; + cur_bits -= 8; + } + if (free_ent > maxcode || clear_flg) { + if (clear_flg) { + maxcode = MAXCODE((n_bits = g_init_bits)); + clear_flg = false; + } else { + ++n_bits; + if (n_bits == BITS) maxcode = 1 << BITS; + else maxcode = MAXCODE(n_bits); + } + } + if (code == EOFCode) { + while (cur_bits > 0) { + char_out(cur_accum & 255, outs); + cur_accum >>= 8; + cur_bits -= 8; + } + flush_char(outs); + } + } + this.encode = encode; + } + module.exports = LZWEncoder; + }, + {}, + ], + 3: [ + function (require, module, exports) { + var ncycles = 100; + var netsize = 256; + var maxnetpos = netsize - 1; + var netbiasshift = 4; + var intbiasshift = 16; + var intbias = 1 << intbiasshift; + var gammashift = 10; + var gamma = 1 << gammashift; + var betashift = 10; + var beta = intbias >> betashift; + var betagamma = intbias << (gammashift - betashift); + var initrad = netsize >> 3; + var radiusbiasshift = 6; + var radiusbias = 1 << radiusbiasshift; + var initradius = initrad * radiusbias; + var radiusdec = 30; + var alphabiasshift = 10; + var initalpha = 1 << alphabiasshift; + var alphadec; + var radbiasshift = 8; + var radbias = 1 << radbiasshift; + var alpharadbshift = alphabiasshift + radbiasshift; + var alpharadbias = 1 << alpharadbshift; + var prime1 = 499; + var prime2 = 491; + var prime3 = 487; + var prime4 = 503; + var minpicturebytes = 3 * prime4; + function NeuQuant(pixels, samplefac) { + var network; + var netindex; + var bias; + var freq; + var radpower; + function init() { + network = []; + netindex = new Int32Array(256); + bias = new Int32Array(netsize); + freq = new Int32Array(netsize); + radpower = new Int32Array(netsize >> 3); + var i, v; + for (i = 0; i < netsize; i++) { + v = (i << (netbiasshift + 8)) / netsize; + network[i] = new Float64Array([v, v, v, 0]); + freq[i] = intbias / netsize; + bias[i] = 0; + } + } + function unbiasnet() { + for (var i = 0; i < netsize; i++) { + network[i][0] >>= netbiasshift; + network[i][1] >>= netbiasshift; + network[i][2] >>= netbiasshift; + network[i][3] = i; + } + } + function altersingle(alpha, i, b, g, r) { + network[i][0] -= (alpha * (network[i][0] - b)) / initalpha; + network[i][1] -= (alpha * (network[i][1] - g)) / initalpha; + network[i][2] -= (alpha * (network[i][2] - r)) / initalpha; + } + function alterneigh(radius, i, b, g, r) { + var lo = Math.abs(i - radius); + var hi = Math.min(i + radius, netsize); + var j = i + 1; + var k = i - 1; + var m = 1; + var p, a; + while (j < hi || k > lo) { + a = radpower[m++]; + if (j < hi) { + p = network[j++]; + p[0] -= (a * (p[0] - b)) / alpharadbias; + p[1] -= (a * (p[1] - g)) / alpharadbias; + p[2] -= (a * (p[2] - r)) / alpharadbias; + } + if (k > lo) { + p = network[k--]; + p[0] -= (a * (p[0] - b)) / alpharadbias; + p[1] -= (a * (p[1] - g)) / alpharadbias; + p[2] -= (a * (p[2] - r)) / alpharadbias; + } + } + } + function contest(b, g, r) { + var bestd = ~(1 << 31); + var bestbiasd = bestd; + var bestpos = -1; + var bestbiaspos = bestpos; + var i, n, dist, biasdist, betafreq; + for (i = 0; i < netsize; i++) { + n = network[i]; + dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r); + if (dist < bestd) { + bestd = dist; + bestpos = i; + } + biasdist = dist - (bias[i] >> (intbiasshift - netbiasshift)); + if (biasdist < bestbiasd) { + bestbiasd = biasdist; + bestbiaspos = i; + } + betafreq = freq[i] >> betashift; + freq[i] -= betafreq; + bias[i] += betafreq << gammashift; + } + freq[bestpos] += beta; + bias[bestpos] -= betagamma; + return bestbiaspos; + } + function inxbuild() { + var i, + j, + p, + q, + smallpos, + smallval, + previouscol = 0, + startpos = 0; + for (i = 0; i < netsize; i++) { + p = network[i]; + smallpos = i; + smallval = p[1]; + for (j = i + 1; j < netsize; j++) { + q = network[j]; + if (q[1] < smallval) { + smallpos = j; + smallval = q[1]; + } + } + q = network[smallpos]; + if (i != smallpos) { + j = q[0]; + q[0] = p[0]; + p[0] = j; + j = q[1]; + q[1] = p[1]; + p[1] = j; + j = q[2]; + q[2] = p[2]; + p[2] = j; + j = q[3]; + q[3] = p[3]; + p[3] = j; + } + if (smallval != previouscol) { + netindex[previouscol] = (startpos + i) >> 1; + for (j = previouscol + 1; j < smallval; j++) netindex[j] = i; + previouscol = smallval; + startpos = i; + } + } + netindex[previouscol] = (startpos + maxnetpos) >> 1; + for (j = previouscol + 1; j < 256; j++) netindex[j] = maxnetpos; + } + function inxsearch(b, g, r) { + var a, p, dist; + var bestd = 1e3; + var best = -1; + var i = netindex[g]; + var j = i - 1; + while (i < netsize || j >= 0) { + if (i < netsize) { + p = network[i]; + dist = p[1] - g; + if (dist >= bestd) i = netsize; + else { + i++; + if (dist < 0) dist = -dist; + a = p[0] - b; + if (a < 0) a = -a; + dist += a; + if (dist < bestd) { + a = p[2] - r; + if (a < 0) a = -a; + dist += a; + if (dist < bestd) { + bestd = dist; + best = p[3]; + } + } + } + } + if (j >= 0) { + p = network[j]; + dist = g - p[1]; + if (dist >= bestd) j = -1; + else { + j--; + if (dist < 0) dist = -dist; + a = p[0] - b; + if (a < 0) a = -a; + dist += a; + if (dist < bestd) { + a = p[2] - r; + if (a < 0) a = -a; + dist += a; + if (dist < bestd) { + bestd = dist; + best = p[3]; + } + } + } + } + } + return best; + } + function learn() { + var i; + var lengthcount = pixels.length; + var alphadec = 30 + (samplefac - 1) / 3; + var samplepixels = lengthcount / (3 * samplefac); + var delta = ~~(samplepixels / ncycles); + var alpha = initalpha; + var radius = initradius; + var rad = radius >> radiusbiasshift; + if (rad <= 1) rad = 0; + for (i = 0; i < rad; i++) + radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad)); + var step; + if (lengthcount < minpicturebytes) { + samplefac = 1; + step = 3; + } else if (lengthcount % prime1 !== 0) { + step = 3 * prime1; + } else if (lengthcount % prime2 !== 0) { + step = 3 * prime2; + } else if (lengthcount % prime3 !== 0) { + step = 3 * prime3; + } else { + step = 3 * prime4; + } + var b, g, r, j; + var pix = 0; + i = 0; + while (i < samplepixels) { + b = (pixels[pix] & 255) << netbiasshift; + g = (pixels[pix + 1] & 255) << netbiasshift; + r = (pixels[pix + 2] & 255) << netbiasshift; + j = contest(b, g, r); + altersingle(alpha, j, b, g, r); + if (rad !== 0) alterneigh(rad, j, b, g, r); + pix += step; + if (pix >= lengthcount) pix -= lengthcount; + i++; + if (delta === 0) delta = 1; + if (i % delta === 0) { + alpha -= alpha / alphadec; + radius -= radius / radiusdec; + rad = radius >> radiusbiasshift; + if (rad <= 1) rad = 0; + for (j = 0; j < rad; j++) + radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad)); + } + } + } + function buildColormap() { + init(); + learn(); + unbiasnet(); + inxbuild(); + } + this.buildColormap = buildColormap; + function getColormap() { + var map = []; + var index = []; + for (var i = 0; i < netsize; i++) index[network[i][3]] = i; + var k = 0; + for (var l = 0; l < netsize; l++) { + var j = index[l]; + map[k++] = network[j][0]; + map[k++] = network[j][1]; + map[k++] = network[j][2]; + } + return map; + } + this.getColormap = getColormap; + this.lookupRGB = inxsearch; + } + module.exports = NeuQuant; + }, + {}, + ], + 4: [ + function (require, module, exports) { + var GIFEncoder, renderFrame; + GIFEncoder = require('./GIFEncoder.js'); + renderFrame = function (frame) { + var encoder, page, stream, transfer; + encoder = new GIFEncoder(frame.width, frame.height); + if (frame.index === 0) { + encoder.writeHeader(); + } else { + encoder.firstFrame = false; + } + encoder.setTransparent(frame.transparent); + encoder.setRepeat(frame.repeat); + encoder.setDelay(frame.delay); + encoder.setQuality(frame.quality); + encoder.setDither(frame.dither); + encoder.setGlobalPalette(frame.globalPalette); + encoder.addFrame(frame.data); + if (frame.last) { + encoder.finish(); + } + if (frame.globalPalette === true) { + frame.globalPalette = encoder.getGlobalPalette(); + } + stream = encoder.stream(); + frame.data = stream.pages; + frame.cursor = stream.cursor; + frame.pageSize = stream.constructor.pageSize; + if (frame.canTransfer) { + transfer = (function () { + var i, len, ref, results; + ref = frame.data; + results = []; + for (i = 0, len = ref.length; i < len; i++) { + page = ref[i]; + results.push(page.buffer); + } + return results; + })(); + return self.postMessage(frame, transfer); + } else { + return self.postMessage(frame); + } + }; + self.onmessage = function (event) { + return renderFrame(event.data); + }; + }, + { './GIFEncoder.js': 1 }, + ], + }, + {}, + [4], +); //# sourceMappingURL=gif.worker.js.map diff --git a/public/update/4.11.185.md b/public/update/4.11.185.md index 0bbd1a64..f587ccc3 100644 --- a/public/update/4.11.185.md +++ b/public/update/4.11.185.md @@ -12,7 +12,6 @@ summary: Add Discord-style profile effects, nameplates, and avatar decorations t - The catalog now comes from a public git, and no Discord token is required in Paarrot for the cosmetics. - Profile-effect previews play their intro and loop animations, with a mini profile preview for each effect. - ![Discord Cosmetics 1](./images/discordcosmetics1.png) ![Discord Cosmetics 2](./images/discordcosmetics2.png) ## Profile presentation diff --git a/scripts/generate-update-manifest.mjs b/scripts/generate-update-manifest.mjs index aeb44fa3..fb6c7e3a 100644 --- a/scripts/generate-update-manifest.mjs +++ b/scripts/generate-update-manifest.mjs @@ -106,9 +106,7 @@ function main() { } fs.writeFileSync(MANIFEST_PATH, json, 'utf8'); - console.log( - `[update-manifest] wrote manifest.json (${manifest.older.length} older version(s))` - ); + console.log(`[update-manifest] wrote manifest.json (${manifest.older.length} older version(s))`); } main(); diff --git a/src/app/components/AccountDataEditor.tsx b/src/app/components/AccountDataEditor.tsx index 5a7febbc..3d289bec 100644 --- a/src/app/components/AccountDataEditor.tsx +++ b/src/app/components/AccountDataEditor.tsx @@ -1,7 +1,19 @@ import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Box, Text, IconButton, Input, Button, TextArea, color, Spinner, Chip, Scroll, config } from 'folds'; -import { Icon, Icons } from './icons'; +import { + Box, + Text, + IconButton, + Input, + Button, + TextArea, + color, + Spinner, + Chip, + Scroll, + config, +} from 'folds'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from './icons'; import { Cursor } from '../plugins/text-area'; import { syntaxErrorPosition } from '../utils/dom'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; @@ -41,7 +53,7 @@ function AccountDataEdit({ const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor( textAreaRef, - EDITOR_INTENT_SPACE_COUNT + EDITOR_INTENT_SPACE_COUNT, ); const [submitState, submit] = useAsyncCallback(submitChange); @@ -263,7 +275,7 @@ export function AccountDataEditor({ const contentJSONStr = useMemo( () => JSON.stringify(data.content, null, EDITOR_INTENT_SPACE_COUNT), - [data.content] + [data.content], ); return ( diff --git a/src/app/components/AngleSelector.tsx b/src/app/components/AngleSelector.tsx index 92e9e516..2be1848d 100644 --- a/src/app/components/AngleSelector.tsx +++ b/src/app/components/AngleSelector.tsx @@ -52,7 +52,7 @@ export function AngleSelector({ return Math.round(angle); }, - [value] + [value], ); /** @@ -67,7 +67,7 @@ export function AngleSelector({ const newAngle = calculateAngle(e.clientX, e.clientY); onChange(newAngle); }, - [disabled, calculateAngle, onChange] + [disabled, calculateAngle, onChange], ); /** @@ -79,7 +79,7 @@ export function AngleSelector({ const newAngle = calculateAngle(e.clientX, e.clientY); onChange(newAngle); }, - [isDragging, disabled, calculateAngle, onChange] + [isDragging, disabled, calculateAngle, onChange], ); /** @@ -90,7 +90,7 @@ export function AngleSelector({ }, []); // Calculate line endpoint position - const lineLength = (size / 2) - 8; + const lineLength = size / 2 - 8; const radians = ((value - 90) * Math.PI) / 180; const lineX = Math.cos(radians) * lineLength; const lineY = Math.sin(radians) * lineLength; @@ -160,7 +160,7 @@ export function AngleSelector({ {/* Cardinal direction markers */} {[0, 90, 180, 270].map((deg) => { const markerRadians = ((deg - 90) * Math.PI) / 180; - const markerDist = (size / 2) - 3; + const markerDist = size / 2 - 3; const markerX = Math.cos(markerRadians) * markerDist; const markerY = Math.sin(markerRadians) * markerDist; return ( diff --git a/src/app/components/AnimatedOutlet.tsx b/src/app/components/AnimatedOutlet.tsx index 01262f71..76d2d6c1 100644 --- a/src/app/components/AnimatedOutlet.tsx +++ b/src/app/components/AnimatedOutlet.tsx @@ -42,7 +42,7 @@ export function AnimatedOutlet() { const location = useLocation(); const transitionKey = useMemo( () => getOutletTransitionKey(location.pathname), - [location.pathname] + [location.pathname], ); return ( diff --git a/src/app/components/AuthFlowsLoader.tsx b/src/app/components/AuthFlowsLoader.tsx index f21bad04..47ec62c6 100644 --- a/src/app/components/AuthFlowsLoader.tsx +++ b/src/app/components/AuthFlowsLoader.tsx @@ -45,7 +45,7 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr }; return authFlows; - }, [mx]) + }, [mx]), ); useEffect(() => { diff --git a/src/app/components/BackupRestore.tsx b/src/app/components/BackupRestore.tsx index a9f92d28..53636e8b 100644 --- a/src/app/components/BackupRestore.tsx +++ b/src/app/components/BackupRestore.tsx @@ -1,9 +1,23 @@ import React, { MouseEventHandler, useCallback, useState } from 'react'; import { useAtom } from 'jotai'; import { CryptoApi, KeyBackupInfo } from 'matrix-js-sdk/lib/crypto-api'; -import { Badge, Box, Button, color, config, IconButton, Menu, percent, PopOut, ProgressBar, RectCords, Spinner, Text } from 'folds'; -import { Icon, Icons } from './icons'; +import { + Badge, + Box, + Button, + color, + config, + IconButton, + Menu, + percent, + PopOut, + ProgressBar, + RectCords, + Spinner, + Text, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from './icons'; import { BackupProgressStatus, backupRestoreProgressAtom } from '../state/backupRestore'; import { InfoCard } from './info-card'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; @@ -142,7 +156,7 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) { setRestoreProgress(progress); }, }); - }, [crypto, setRestoreProgress]) + }, [crypto, setRestoreProgress]), ); const handleRestore = () => { diff --git a/src/app/components/ConfirmPasswordMatch.tsx b/src/app/components/ConfirmPasswordMatch.tsx index bb50eb60..f4a66003 100644 --- a/src/app/components/ConfirmPasswordMatch.tsx +++ b/src/app/components/ConfirmPasswordMatch.tsx @@ -7,7 +7,7 @@ type ConfirmPasswordMatchProps = { match: boolean, doMatch: () => void, passRef: RefObject, - confPassRef: RefObject + confPassRef: RefObject, ) => ReactNode; }; export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) { @@ -28,7 +28,7 @@ export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPassword { wait: 500, immediate: false, - } + }, ); return children(match, doMatch, passRef, confPassRef); diff --git a/src/app/components/DeviceVerification.tsx b/src/app/components/DeviceVerification.tsx index 75f2779d..05310bc0 100644 --- a/src/app/components/DeviceVerification.tsx +++ b/src/app/components/DeviceVerification.tsx @@ -6,9 +6,21 @@ import { } from 'matrix-js-sdk/lib/crypto-api'; import React, { CSSProperties, useCallback, useEffect, useState } from 'react'; import { VerificationMethod } from 'matrix-js-sdk/lib/types'; -import { Box, Button, config, Dialog, Header, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds'; -import { Icon, Icons } from './icons'; +import { + Box, + Button, + config, + Dialog, + Header, + IconButton, + Overlay, + OverlayBackdrop, + OverlayCenter, + Spinner, + Text, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from './icons'; import { useVerificationRequestPhase, useVerificationRequestReceived, diff --git a/src/app/components/DeviceVerificationSetup.tsx b/src/app/components/DeviceVerificationSetup.tsx index a2203a50..769ac5d7 100644 --- a/src/app/components/DeviceVerificationSetup.tsx +++ b/src/app/components/DeviceVerificationSetup.tsx @@ -1,9 +1,9 @@ import React, { FormEventHandler, forwardRef, useCallback, useState } from 'react'; import { Dialog, Header, Box, Text, IconButton, config, Button, Chip, color, Spinner } from 'folds'; -import { Icon, Icons } from './icons'; import FileSaver from 'file-saver'; import to from 'await-to-js'; import { AuthDict, IAuthData, MatrixError, UIAuthCallback } from 'matrix-js-sdk'; +import { Icon, Icons } from './icons'; import { PasswordInput } from './password-input'; import { ContainerColor } from '../styles/ContainerColor.css'; import { copyToClipboard } from '../utils/dom'; @@ -15,7 +15,7 @@ import { useAlive } from '../hooks/useAlive'; import { UseStateProvider } from './UseStateProvider'; type UIACallback = ( - authDict: AuthDict | null + authDict: AuthDict | null, ) => Promise<[IAuthData, undefined] | [undefined, T]>; type PerformAction = (authDict: AuthDict | null) => Promise; @@ -30,7 +30,7 @@ function makeUIAAction( authData: IAuthData, performAction: PerformAction, resolve: (data: T) => void, - reject: (error?: any) => void + reject: (error?: any) => void, ): UIAAction { const action: UIAAction = { authData, @@ -79,7 +79,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { setNextAuthData(authData); } }, - [uiaAction, alive] + [uiaAction, alive], ); const resetUIA = useCallback(() => { @@ -106,7 +106,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { (err) => { resetUIA(); reject(err); - } + }, ); if (alive()) { setUIAAction(action); @@ -118,7 +118,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { reject(error); }); }), - [alive, resetUIA] + [alive, resetUIA], ); const [setupState, setup] = useAsyncCallback( @@ -147,8 +147,8 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { onComplete(recoveryKeyData.encodedPrivateKey); }, - [mx, onComplete, authUploadDeviceSigningKeys] - ) + [mx, onComplete, authUploadDeviceSigningKeys], + ), ); const loading = setupState.status === AsyncStatus.Loading; @@ -302,7 +302,7 @@ export const DeviceVerificationSetup = forwardRef ); - } + }, ); type DeviceVerificationResetProps = { onCancel: () => void; @@ -359,5 +359,5 @@ export const DeviceVerificationReset = forwardRef ); - } + }, ); diff --git a/src/app/components/JoinRulesSwitcher.tsx b/src/app/components/JoinRulesSwitcher.tsx index 878b609d..0683c218 100644 --- a/src/app/components/JoinRulesSwitcher.tsx +++ b/src/app/components/JoinRulesSwitcher.tsx @@ -1,8 +1,8 @@ import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react'; import { config, Box, MenuItem, Text, RectCords, PopOut, Menu, Button, Spinner } from 'folds'; -import { Icon, Icons, IconSrc } from './icons'; import { JoinRule } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons, IconSrc } from './icons'; import { stopPropagation } from '../utils/keyboard'; export type ExtraJoinRules = 'knock_restricted'; @@ -19,7 +19,7 @@ export const useRoomJoinRuleIcon = (): JoinRuleIcons => [JoinRule.Public]: Icons.HashGlobe, [JoinRule.Private]: Icons.HashLock, }), - [] + [], ); export const useSpaceJoinRuleIcon = (): JoinRuleIcons => useMemo( @@ -31,7 +31,7 @@ export const useSpaceJoinRuleIcon = (): JoinRuleIcons => [JoinRule.Public]: Icons.SpaceGlobe, [JoinRule.Private]: Icons.SpaceLock, }), - [] + [], ); type JoinRuleLabels = Record; @@ -45,7 +45,7 @@ export const useRoomJoinRuleLabel = (): JoinRuleLabels => [JoinRule.Public]: 'Public', [JoinRule.Private]: 'Invite Only', }), - [] + [], ); type JoinRulesSwitcherProps = { @@ -77,7 +77,7 @@ export function JoinRulesSwitcher({ setCords(undefined); onChange(selectedRule); }, - [onChange] + [onChange], ); return ( diff --git a/src/app/components/LogoutDialog.tsx b/src/app/components/LogoutDialog.tsx index cc9bf067..4ae6e0bc 100644 --- a/src/app/components/LogoutDialog.tsx +++ b/src/app/components/LogoutDialog.tsx @@ -21,13 +21,13 @@ export const LogoutDialog = forwardRef( const verificationStatus = useDeviceVerificationStatus( mx.getCrypto(), mx.getSafeUserId(), - mx.getDeviceId() ?? undefined + mx.getDeviceId() ?? undefined, ); const [logoutState, logout] = useAsyncCallback( useCallback(async () => { await logoutClient(mx); - }, [mx]) + }, [mx]), ); const ongoingLogout = logoutState.status === AsyncStatus.Loading; @@ -85,5 +85,5 @@ export const LogoutDialog = forwardRef( ); - } + }, ); diff --git a/src/app/components/ManualVerification.tsx b/src/app/components/ManualVerification.tsx index a505d5d0..4d8e6cfa 100644 --- a/src/app/components/ManualVerification.tsx +++ b/src/app/components/ManualVerification.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react'; import { Box, Text, Chip, RectCords, PopOut, Menu, config, MenuItem, color } from 'folds'; -import { Icon, Icons } from './icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from './icons'; import { stopPropagation } from '../utils/keyboard'; import { SettingTile } from './setting-tile'; import { SecretStorageKeyContent } from '../../types/matrix/accountData'; @@ -115,7 +115,7 @@ export function ManualVerificationTile({ const [method, setMethod] = useState( hasPassphrase ? ManualVerificationMethod.RecoveryPassphrase - : ManualVerificationMethod.RecoveryKey + : ManualVerificationMethod.RecoveryKey, ); const verifyAndRestoreBackup = useCallback( @@ -132,11 +132,11 @@ export function ManualVerificationTile({ await crypto.loadSessionBackupPrivateKeyFromSecretStorage(); }, - [mx, secretStorageKeyId] + [mx, secretStorageKeyId], ); const [verifyState, handleDecodedRecoveryKey] = useAsyncCallback( - verifyAndRestoreBackup + verifyAndRestoreBackup, ); const verifying = verifyState.status === AsyncStatus.Loading; diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index 709441a6..95d3d14f 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -1,10 +1,23 @@ -/* eslint-disable no-param-reassign */ -/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */ import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; -import { Box, Button, Chip, Header, IconButton, Input, Menu, PopOut, RectCords, Scroll, Spinner, Text, as, config } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Box, + Button, + Chip, + Header, + IconButton, + Input, + Menu, + PopOut, + RectCords, + Scroll, + Spinner, + Text, + as, + config, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../icons'; import { saveMediaBlob } from '../../utils/saveMedia'; import * as css from './PdfViewer.css'; import { AsyncStatus } from '../../hooks/useAsyncCallback'; @@ -27,7 +40,7 @@ export const PdfViewer = as<'div', PdfViewerProps>( const [pdfJSState, loadPdfJS] = usePdfJSLoader(); const [docState, loadPdfDocument] = usePdfDocumentLoader( pdfJSState.status === AsyncStatus.Success ? pdfJSState.data : undefined, - src + src, ); const isLoading = pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading; @@ -247,5 +260,5 @@ export const PdfViewer = as<'div', PdfViewerProps>( )} ); - } + }, ); diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index bb0a2103..7012db9d 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -25,7 +25,16 @@ import { VideoContent, VideoFrameThumbnail, } from './message'; -import { UrlPreviewCard, UrlPreviewHolder, YouTubeEmbed, isYouTubeUrl, TikTokEmbed, isTikTokUrl, GiphyEmbed, isGiphyUrl } from './url-preview'; +import { + UrlPreviewCard, + UrlPreviewHolder, + YouTubeEmbed, + isYouTubeUrl, + TikTokEmbed, + isTikTokUrl, + GiphyEmbed, + isGiphyUrl, +} from './url-preview'; import { Image, MediaControl, Video } from './media'; import { ImageViewer } from './image-viewer'; import { VideoViewer } from './video-viewer'; @@ -53,7 +62,7 @@ type RenderMessageContentProps = { onJumboEmojiClick?: ( targetEventId: string, body: string, - event: MouseEvent | KeyboardEvent + event: MouseEvent | KeyboardEvent, ) => void; }; export function RenderMessageContent({ @@ -81,7 +90,9 @@ export function RenderMessageContent({ const youtubeUrls = filteredUrls.filter(isYouTubeUrl); const tiktokUrls = filteredUrls.filter(isTikTokUrl); const giphyUrls = filteredUrls.filter(isGiphyUrl); - const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url)); + const otherUrls = filteredUrls.filter( + (url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url), + ); return ( <> @@ -275,8 +286,9 @@ export function RenderMessageContent({ content={getContent()} renderAsFile={renderFile} renderVideoContent={({ body, info, mimeType, url, encInfo, ...props }) => { - const hasValidThumbnail = - (typeof info.thumbnail_file?.url === 'string' || typeof info.thumbnail_url === 'string') && + const hasValidThumbnail = + (typeof info.thumbnail_file?.url === 'string' || + typeof info.thumbnail_url === 'string') && typeof info.thumbnail_info?.mimetype === 'string'; return ( @@ -290,23 +302,24 @@ export function RenderMessageContent({ {...props} renderThumbnail={ mediaAutoLoad - ? () => hasValidThumbnail ? ( - ( - {body} - )} - /> - ) : ( - ( - {body} - )} - /> - ) + ? () => + hasValidThumbnail ? ( + ( + {body} + )} + /> + ) : ( + ( + {body} + )} + /> + ) : undefined } renderViewer={(p) => } @@ -360,13 +373,10 @@ export function RenderMessageContent({ }; console.log('[RenderMessageContent] Calling customRenderer with msgtype:', msgType); console.log('[RenderMessageContent] messageData:', messageData); - const customContent = customRenderer( - messageData, - () => { - console.log('[RenderMessageContent] defaultRenderer called'); - return null; - } - ); + const customContent = customRenderer(messageData, () => { + console.log('[RenderMessageContent] defaultRenderer called'); + return null; + }); console.log('[RenderMessageContent] customRenderer returned:', customContent); console.log('[RenderMessageContent] customContent type:', typeof customContent); if (customContent) { diff --git a/src/app/components/RoomNotificationSwitcher.tsx b/src/app/components/RoomNotificationSwitcher.tsx index 5f3a290c..50f1af89 100644 --- a/src/app/components/RoomNotificationSwitcher.tsx +++ b/src/app/components/RoomNotificationSwitcher.tsx @@ -1,7 +1,7 @@ import { Box, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; -import { Icon } from './icons'; import React, { MouseEventHandler, ReactNode, useMemo, useState } from 'react'; import FocusTrap from 'focus-trap-react'; +import { Icon } from './icons'; import { stopPropagation } from '../utils/keyboard'; import { getRoomNotificationModeIcon, @@ -18,7 +18,7 @@ const useRoomNotificationModes = (): RoomNotificationMode[] => RoomNotificationMode.SpecialMessages, RoomNotificationMode.Mute, ], - [] + [], ); const useRoomNotificationModeStr = (): Record => @@ -29,7 +29,7 @@ const useRoomNotificationModeStr = (): Record => [RoomNotificationMode.SpecialMessages]: 'Mention & Keywords', [RoomNotificationMode.Mute]: 'Mute', }), - [] + [], ); type NotificationModeSwitcherProps = { @@ -38,7 +38,7 @@ type NotificationModeSwitcherProps = { children: ( handleOpen: MouseEventHandler, opened: boolean, - changing: boolean + changing: boolean, ) => ReactNode; }; export function RoomNotificationModeSwitcher({ diff --git a/src/app/components/RouteTransition.tsx b/src/app/components/RouteTransition.tsx index cb248b8d..d4fd0da1 100644 --- a/src/app/components/RouteTransition.tsx +++ b/src/app/components/RouteTransition.tsx @@ -88,11 +88,12 @@ export function RouteTransition({ children }: RouteTransitionProps) { }; }, [location, displayLocation]); - const className = transitionStage === 'entering' - ? `${transitionContent} ${animateIn}` - : transitionStage === 'exiting' - ? `${transitionContent} ${animateOut}` - : transitionContent; + const className = + transitionStage === 'entering' + ? `${transitionContent} ${animateIn}` + : transitionStage === 'exiting' + ? `${transitionContent} ${animateOut}` + : transitionContent; return (
diff --git a/src/app/components/SecretStorage.tsx b/src/app/components/SecretStorage.tsx index 9d8628e5..be83a449 100644 --- a/src/app/components/SecretStorage.tsx +++ b/src/app/components/SecretStorage.tsx @@ -36,7 +36,7 @@ export function SecretStorageRecoveryPassphrase({ passphrase, salt, iterations, - bits + bits, ); const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any); @@ -47,8 +47,8 @@ export function SecretStorageRecoveryPassphrase({ return decodedRecoveryKey; }, - [mx, keyContent] - ) + [mx, keyContent], + ), ); const drivingKey = driveKeyState.status === AsyncStatus.Loading; @@ -139,8 +139,8 @@ export function SecretStorageRecoveryKey({ return decodedRecoveryKey; }, - [mx, keyContent] - ) + [mx, keyContent], + ), ); const drivingKey = driveKeyState.status === AsyncStatus.Loading; diff --git a/src/app/components/ServerConfigsLoader.tsx b/src/app/components/ServerConfigsLoader.tsx index 3bf6feb2..9bc6776b 100644 --- a/src/app/components/ServerConfigsLoader.tsx +++ b/src/app/components/ServerConfigsLoader.tsx @@ -44,7 +44,7 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) { mediaConfig, authMetadata: validatedAuthMetadata, }; - }, [mx]) + }, [mx]), ); const configs: ServerConfigs = diff --git a/src/app/components/SpaceChildDirectsProvider.tsx b/src/app/components/SpaceChildDirectsProvider.tsx index 203363e1..486985be 100644 --- a/src/app/components/SpaceChildDirectsProvider.tsx +++ b/src/app/components/SpaceChildDirectsProvider.tsx @@ -21,7 +21,7 @@ export function SpaceChildDirectsProvider({ const childDirects = useSpaceChildren( allRoomsAtom, spaceId, - useChildDirectScopeFactory(mx, mDirects, roomToParents) + useChildDirectScopeFactory(mx, mDirects, roomToParents), ); return children(childDirects); diff --git a/src/app/components/SpaceChildRoomsProvider.tsx b/src/app/components/SpaceChildRoomsProvider.tsx index 65ed03be..e1933410 100644 --- a/src/app/components/SpaceChildRoomsProvider.tsx +++ b/src/app/components/SpaceChildRoomsProvider.tsx @@ -21,7 +21,7 @@ export function SpaceChildRoomsProvider({ const childRooms = useSpaceChildren( allRoomsAtom, spaceId, - useChildRoomScopeFactory(mx, mDirects, roomToParents) + useChildRoomScopeFactory(mx, mDirects, roomToParents), ); return children(childRooms); diff --git a/src/app/components/SpecVersionsLoader.tsx b/src/app/components/SpecVersionsLoader.tsx index 5ee47bdf..b7f938ec 100644 --- a/src/app/components/SpecVersionsLoader.tsx +++ b/src/app/components/SpecVersionsLoader.tsx @@ -15,7 +15,7 @@ export function SpecVersionsLoader({ children, }: SpecVersionsLoaderProps) { const [state, load] = useAsyncCallback( - useCallback(() => specVersions(fetch, baseUrl), [baseUrl]) + useCallback(() => specVersions(fetch, baseUrl), [baseUrl]), ); const [ignoreError, setIgnoreError] = useState(false); @@ -38,6 +38,6 @@ export function SpecVersionsLoader({ ? state.data : { versions: [], - } + }, ); } diff --git a/src/app/components/UIAFlowOverlay.tsx b/src/app/components/UIAFlowOverlay.tsx index 8b692aef..6fed023e 100644 --- a/src/app/components/UIAFlowOverlay.tsx +++ b/src/app/components/UIAFlowOverlay.tsx @@ -1,7 +1,17 @@ import React, { ReactNode } from 'react'; -import { Overlay, OverlayBackdrop, Box, config, Text, TooltipProvider, Tooltip, Chip, IconButton } from 'folds'; -import { Icons, Icon } from './icons'; +import { + Overlay, + OverlayBackdrop, + Box, + config, + Text, + TooltipProvider, + Tooltip, + Chip, + IconButton, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icons, Icon } from './icons'; export type UIAFlowOverlayProps = { currentStep: number; diff --git a/src/app/components/account-switcher/AccountSwitcher.tsx b/src/app/components/account-switcher/AccountSwitcher.tsx index 5ed2e514..106fa5b1 100644 --- a/src/app/components/account-switcher/AccountSwitcher.tsx +++ b/src/app/components/account-switcher/AccountSwitcher.tsx @@ -1,7 +1,7 @@ import React, { useEffect, useState } from 'react'; import { Avatar, Box, MenuItem, Text, config } from 'folds'; -import { Icon, Icons } from '../icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../icons'; import { sessionsAtom, Session } from '../../state/sessions'; import { setLocalStorageItem } from '../../state/utils/atomWithLocalStorage'; import { getMxIdServer, mxcUrlToHttp } from '../../utils/matrix'; @@ -26,7 +26,7 @@ function OtherSessionAvatar({ session }: { session: Session }) { try { const res = await fetch( `${session.baseUrl}/_matrix/client/v3/profile/${encodeURIComponent(session.userId)}`, - { headers: { Authorization: `Bearer ${session.accessToken}` } } + { headers: { Authorization: `Bearer ${session.accessToken}` } }, ); if (!res.ok) return; const data = await res.json(); @@ -34,7 +34,7 @@ function OtherSessionAvatar({ session }: { session: Session }) { const match = (data.avatar_url as string).match(/^mxc:\/\/([^/]+)\/(.+)$/); if (match) { setSrc( - `${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop` + `${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop`, ); } } @@ -59,25 +59,25 @@ function OtherSessionAvatar({ session }: { session: Session }) { const deleteAllMatrixDatabases = async (): Promise => { console.log('[AccountSwitcher] Deleting all Matrix IndexedDB databases...'); - + // List of known Matrix database names/patterns to delete const dbsToDelete = [ - 'matrix-js-sdk::matrix-sdk-crypto', // Shared crypto store (causes conflicts) + 'matrix-js-sdk::matrix-sdk-crypto', // Shared crypto store (causes conflicts) ]; - + // Try to get all databases if the API is available try { if ('databases' in indexedDB) { const allDbs = await (indexedDB as any).databases(); const matrixDbs = allDbs .map((db: any) => db.name) - .filter((name: string) => - name && ( - name.startsWith('matrix-js-sdk') || - name.includes('@@') || - name.startsWith('sync@@') || - name.startsWith('crypto@@') - ) + .filter( + (name: string) => + name && + (name.startsWith('matrix-js-sdk') || + name.includes('@@') || + name.startsWith('sync@@') || + name.startsWith('crypto@@')), ); dbsToDelete.push(...matrixDbs); console.log('[AccountSwitcher] Found Matrix databases:', matrixDbs); @@ -85,7 +85,7 @@ const deleteAllMatrixDatabases = async (): Promise => { } catch (e) { console.warn('[AccountSwitcher] Could not enumerate databases:', e); } - + // Delete each database with timeout const deletePromises = dbsToDelete.map(async (dbName) => { try { @@ -104,7 +104,7 @@ const deleteAllMatrixDatabases = async (): Promise => { resolve(); // Don't reject, reload will handle it }; }); - + // Add 1-second timeout per database const timeoutPromise = new Promise((resolve) => { setTimeout(() => { @@ -112,13 +112,13 @@ const deleteAllMatrixDatabases = async (): Promise => { resolve(); }, 1000); }); - + await Promise.race([deletePromise, timeoutPromise]); } catch (error) { console.warn(`[AccountSwitcher] Error deleting ${dbName}:`, error); } }); - + await Promise.all(deletePromises); console.log('[AccountSwitcher] ✅ Database cleanup complete'); }; @@ -129,14 +129,14 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) { const useAuthentication = useMediaAuthentication(); const currentProfile = useUserProfile(currentUserId ?? ''); const currentAvatarUrl = currentProfile.avatarUrl - ? mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined) : undefined; - + const handleSwitchAccount = async (session: Session) => { if (session.userId === currentUserId) return; - + console.log('[AccountSwitcher] Switching account from', currentUserId, 'to', session.userId); - + // Stop the current client before switching if (mx) { console.log('[AccountSwitcher] Stopping current Matrix client...'); @@ -147,16 +147,16 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) { console.error('[AccountSwitcher] Error stopping client:', error); } } - + // Set the new current session setLocalStorageItem('currentSessionUserId', session.userId); - + // Delete all Matrix databases to prevent conflicts await deleteAllMatrixDatabases(); - + // Small delay to ensure cleanup is complete - await new Promise(resolve => setTimeout(resolve, 100)); - + await new Promise((resolve) => setTimeout(resolve, 100)); + // Reload the page to initialize the new session console.log('[AccountSwitcher] Reloading page...'); window.location.reload(); @@ -168,15 +168,18 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) { } // Filter out other sessions (not current) - const otherSessions = sessions.filter(s => s.userId !== currentUserId); + const otherSessions = sessions.filter((s) => s.userId !== currentUserId); const hasMultipleAccounts = sessions.length > 1; return ( - + {hasMultipleAccounts ? 'Switch Account' : 'Accounts'} - + {/* Show current account */} {currentUserId && ( )} - + {/* Show other accounts if any */} {otherSessions.map((session) => { const server = getMxIdServer(session.userId); - + return ( ; - } + }, ); AuthenticatedAvatarImage.displayName = 'AuthenticatedAvatarImage'; diff --git a/src/app/components/authenticated-media/AuthenticatedMedia.tsx b/src/app/components/authenticated-media/AuthenticatedMedia.tsx index 37e68b75..fbc1f81f 100644 --- a/src/app/components/authenticated-media/AuthenticatedMedia.tsx +++ b/src/app/components/authenticated-media/AuthenticatedMedia.tsx @@ -2,8 +2,7 @@ import React, { ImgHTMLAttributes, forwardRef, useEffect, useState } from 'react import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; -export interface AuthenticatedMediaProps - extends Omit, 'src'> { +export interface AuthenticatedMediaProps extends Omit, 'src'> { /** The source URL of the media (may be an authenticated media URL) */ src?: string; /** Override for authentication - if not provided, uses useMediaAuthentication hook */ @@ -22,7 +21,7 @@ export const AuthenticatedMedia = forwardRef; - } + }, ); AuthenticatedMedia.displayName = 'AuthenticatedMedia'; @@ -39,7 +38,7 @@ export const AuthenticatedImg = forwardRef; - } + }, ); AuthenticatedImg.displayName = 'AuthenticatedImg'; diff --git a/src/app/components/create-room/AdditionalCreatorInput.tsx b/src/app/components/create-room/AdditionalCreatorInput.tsx index 1b1d21ad..141ded56 100644 --- a/src/app/components/create-room/AdditionalCreatorInput.tsx +++ b/src/app/components/create-room/AdditionalCreatorInput.tsx @@ -1,5 +1,18 @@ -import { Box, Button, Chip, config, Input, Line, Menu, MenuItem, PopOut, RectCords, Scroll, Text, toRem } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Box, + Button, + Chip, + config, + Input, + Line, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Text, + toRem, +} from 'folds'; import { isKeyHotkey } from 'is-hotkey'; import FocusTrap from 'focus-trap-react'; import React, { @@ -9,6 +22,7 @@ import React, { useMemo, useState, } from 'react'; +import { Icon, Icons } from '../icons'; import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix'; import { useDirectUsers } from '../../hooks/useDirectUsers'; import { SettingTile } from '../setting-tile'; @@ -20,7 +34,7 @@ import { highlightText, makeHighlightRegex } from '../../plugins/react-custom-ht export const useAdditionalCreators = (defaultCreators?: string[]) => { const mx = useMatrixClient(); const [additionalCreators, setAdditionalCreators] = useState( - () => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? [] + () => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? [], ); const addAdditionalCreator = (userId: string) => { @@ -75,12 +89,12 @@ export function AdditionalCreatorInput({ const [validUserId, setValidUserId] = useState(); const filteredUsers = useMemo( () => directUsers.filter((userId) => !additionalCreators.includes(userId)), - [directUsers, additionalCreators] + [directUsers, additionalCreators], ); const [result, search, resetSearch] = useAsyncSearch( filteredUsers, getUserIdString, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const queryHighlighRegex = result?.query ? makeHighlightRegex([result.query]) : undefined; diff --git a/src/app/components/create-room/CreateRoomAliasInput.tsx b/src/app/components/create-room/CreateRoomAliasInput.tsx index 6a958d39..de4fe1f1 100644 --- a/src/app/components/create-room/CreateRoomAliasInput.tsx +++ b/src/app/components/create-room/CreateRoomAliasInput.tsx @@ -8,8 +8,8 @@ import React, { } from 'react'; import { MatrixError } from 'matrix-js-sdk'; import { Box, color, Input, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../icons'; import { isKeyHotkey } from 'is-hotkey'; +import { Icon, Icons } from '../icons'; import { getMxIdServer } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { replaceSpaceWithDash } from '../../utils/common'; @@ -43,9 +43,9 @@ export function CreateRoomAliasInput({ disabled }: { disabled?: boolean }) { throw e; } }, - [mx] + [mx], ), - setAliasAvail + setAliasAvail, ); const aliasAvailable: boolean | undefined = aliasAvail.status === AsyncStatus.Success ? aliasAvail.data : undefined; diff --git a/src/app/components/create-room/RoomVersionSelector.tsx b/src/app/components/create-room/RoomVersionSelector.tsx index aa443c14..92c34fcd 100644 --- a/src/app/components/create-room/RoomVersionSelector.tsx +++ b/src/app/components/create-room/RoomVersionSelector.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, useState } from 'react'; import { Box, Button, Chip, config, Menu, PopOut, RectCords, Text, toRem } from 'folds'; -import { Icon, Icons } from '../icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../icons'; import { SettingTile } from '../setting-tile'; import { SequenceCard } from '../sequence-card'; import { stopPropagation } from '../../utils/keyboard'; diff --git a/src/app/components/create-room/utils.ts b/src/app/components/create-room/utils.ts index 83a9c0f4..0115fe7b 100644 --- a/src/app/components/create-room/utils.ts +++ b/src/app/components/create-room/utils.ts @@ -15,7 +15,7 @@ import { getMxIdServer } from '../../utils/matrix'; export const createRoomCreationContent = ( type: RoomType | undefined, allowFederation: boolean, - additionalCreators: string[] | undefined + additionalCreators: string[] | undefined, ): object => { const content: Record = {}; if (typeof type === 'string') { @@ -34,7 +34,7 @@ export const createRoomCreationContent = ( export const createRoomJoinRulesState = ( kind: CreateRoomKind, parent: Room | undefined, - knock: boolean + knock: boolean, ) => { let content: RoomJoinRulesEventContent = { join_rule: knock ? JoinRule.Knock : JoinRule.Invite, @@ -134,7 +134,7 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis creation_content: createRoomCreationContent( data.type, data.allowFederation, - data.additionalCreators + data.additionalCreators, ), initial_state: initialState, }; @@ -150,7 +150,7 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis suggested: false, via: [getMxIdServer(mx.getUserId() ?? '') ?? ''], }, - result.room_id + result.room_id, ); } diff --git a/src/app/components/custom-status/CustomStatusDialog.tsx b/src/app/components/custom-status/CustomStatusDialog.tsx index e587aa31..4fdb8afa 100644 --- a/src/app/components/custom-status/CustomStatusDialog.tsx +++ b/src/app/components/custom-status/CustomStatusDialog.tsx @@ -27,10 +27,10 @@ export interface CustomStatusDialogProps { /** * CustomStatusDialog Component - * + * * Provides a dialog interface for users to set or clear their custom status message. * The status is stored in Matrix presence and will be visible to other users. - * + * * @param props - Component props * @returns The custom status dialog component */ @@ -38,9 +38,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { const mx = useMatrixClient(); const userId = mx.getUserId(); const presence = useUserPresence(userId ?? ''); - + const [statusText, setStatusText] = useState(presence?.status || ''); - + /** * Handles input changes for the status text field * @param evt - The change event from the input @@ -48,7 +48,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { const handleChange: ChangeEventHandler = (evt) => { setStatusText(evt.currentTarget.value); }; - + /** * Async callback to save the status to Matrix presence */ @@ -59,9 +59,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { status_msg: statusText, }); onClose(); - }, [mx, presence?.presence, statusText, onClose]) + }, [mx, presence?.presence, statusText, onClose]), ); - + /** * Async callback to clear the status from Matrix presence */ @@ -73,9 +73,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { }); setStatusText(''); onClose(); - }, [mx, presence?.presence, onClose]) + }, [mx, presence?.presence, onClose]), ); - + /** * Handles form submission to save the custom status * @param evt - The form submit event @@ -84,7 +84,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { evt.preventDefault(); saveStatus(); }; - + /** * Handles the clear status button click */ @@ -118,7 +118,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { Your custom status will be visible to other users - + {statusText.length > 0 && ( @@ -135,7 +138,8 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { )} - {(saveState.status === AsyncStatus.Error || clearState.status === AsyncStatus.Error) && ( + {(saveState.status === AsyncStatus.Error || + clearState.status === AsyncStatus.Error) && ( Failed to update status. Please try again. @@ -146,7 +150,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { type="button" variant="Secondary" onClick={onClose} - disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} + disabled={ + saveState.status === AsyncStatus.Loading || + clearState.status === AsyncStatus.Loading + } > Cancel @@ -156,7 +163,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) { variant="Critical" fill="None" onClick={handleClear} - disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} + disabled={ + saveState.status === AsyncStatus.Loading || + clearState.status === AsyncStatus.Loading + } > Clear Status @@ -164,7 +174,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
); - } + }, ); diff --git a/src/app/components/editor/Toolbar.tsx b/src/app/components/editor/Toolbar.tsx index 6b1320a7..d227cff5 100644 --- a/src/app/components/editor/Toolbar.tsx +++ b/src/app/components/editor/Toolbar.tsx @@ -1,8 +1,22 @@ import FocusTrap from 'focus-trap-react'; -import { Badge, Box, config, IconButton, Line, Menu, PopOut, RectCords, Scroll, Text, Tooltip, TooltipProvider, toRem } from 'folds'; -import { Icon, Icons, IconSrc } from '../icons'; +import { + Badge, + Box, + config, + IconButton, + Line, + Menu, + PopOut, + RectCords, + Scroll, + Text, + Tooltip, + TooltipProvider, + toRem, +} from 'folds'; import React, { MouseEventHandler, ReactNode, useState } from 'react'; import { ReactEditor, useSlate } from 'slate-react'; +import { Icon, Icons, IconSrc } from '../icons'; import { headingLevel, isAnyMarkActive, diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index cc0dff19..aba140ba 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -51,14 +51,14 @@ export function EmoticonAutocomplete({ const list: Array = []; return list.concat( imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), - emojis + emojis, ); }, [imagePacks]); const [result, search, resetSearch] = useAsyncSearch( searchList, getEmoticonSearchStr, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji; diff --git a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx index 29c44d76..ea22da76 100644 --- a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx @@ -1,9 +1,9 @@ import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react'; import { Editor } from 'slate'; import { Avatar, MenuItem, Text } from 'folds'; -import { Icon, Icons } from '../../icons'; import { JoinRule, MatrixClient } from 'matrix-js-sdk'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../icons'; import { createMentionElement, moveCursor, replaceWithElement } from '../utils'; import { getDirectRoomAvatarUrl, guessPerfectParent } from '../../../utils/room'; @@ -94,9 +94,9 @@ export function RoomMentionAutocomplete({ if (alias) return [r.name, alias]; return r.name; }, - [mx] + [mx], ), - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const autoCompleteRoomIds = result ? result.items.slice(0, 20) : allRooms.slice(0, 20); @@ -107,40 +107,43 @@ export function RoomMentionAutocomplete({ }, [query.text, search, resetSearch]); // Build space hierarchy path for a room - const getSpacePath = useCallback((rId: string): string | null => { - // Skip DMs - if (mDirects.has(rId)) return null; - - const buildParentChain = (currentRoomId: string): string[] => { - const parents = roomToParents.get(currentRoomId); - if (!parents || parents.size === 0) { - return []; - } - - const parentsList = Array.from(parents); - let chosenParent: string; - - if (parentsList.length === 1) { - chosenParent = parentsList[0]; - } else { - const orphanParents = parentsList.filter(p => !roomToParents.has(p)); - if (orphanParents.length > 0) { - chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0]; - } else { - chosenParent = parentsList[0]; + const getSpacePath = useCallback( + (rId: string): string | null => { + // Skip DMs + if (mDirects.has(rId)) return null; + + const buildParentChain = (currentRoomId: string): string[] => { + const parents = roomToParents.get(currentRoomId); + if (!parents || parents.size === 0) { + return []; } - } - - const parentRoom = mx.getRoom(chosenParent); - if (!parentRoom?.name) return []; - - const upperChain = buildParentChain(chosenParent); - return [...upperChain, parentRoom.name]; - }; - - const parentChain = buildParentChain(rId); - return parentChain.length > 0 ? parentChain.join(' > ') : null; - }, [mx, mDirects, roomToParents]); + + const parentsList = Array.from(parents); + let chosenParent: string; + + if (parentsList.length === 1) { + chosenParent = parentsList[0]; + } else { + const orphanParents = parentsList.filter((p) => !roomToParents.has(p)); + if (orphanParents.length > 0) { + chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0]; + } else { + chosenParent = parentsList[0]; + } + } + + const parentRoom = mx.getRoom(chosenParent); + if (!parentRoom?.name) return []; + + const upperChain = buildParentChain(chosenParent); + return [...upperChain, parentRoom.name]; + }; + + const parentChain = buildParentChain(rId); + return parentChain.length > 0 ? parentChain.join(' > ') : null; + }, + [mx, mDirects, roomToParents], + ); const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => { const mentionRoom = mx.getRoom(roomAliasOrId); @@ -150,7 +153,7 @@ export function RoomMentionAutocomplete({ name.startsWith('#') ? name : `#${name}`, roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId, undefined, - viaServers + viaServers, ); replaceWithElement(editor, query.range, mentionEl); moveCursor(editor, true); diff --git a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx index 014fe446..14df4ccb 100644 --- a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx @@ -1,8 +1,8 @@ import React, { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react'; import { Editor } from 'slate'; import { Avatar, MenuItem, Text } from 'folds'; -import { Icon, Icons } from '../../icons'; import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../icons'; import { AutocompleteQuery } from './autocompleteQuery'; import { AutocompleteMenu } from './AutocompleteMenu'; @@ -99,7 +99,7 @@ export function UserMentionAutocomplete({ const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS); const autoCompleteMembers = (result ? result.items.slice(0, 20) : members.slice(0, 20)).filter( - withAllowedMembership + withAllowedMembership, ); useEffect(() => { @@ -111,7 +111,7 @@ export function UserMentionAutocomplete({ const mentionEl = createMentionElement( uId, name.startsWith('@') ? name : `@${name}`, - mx.getUserId() === uId || roomAliasOrId === uId + mx.getUserId() === uId || roomAliasOrId === uId, ); replaceWithElement(editor, query.range, mentionEl); moveCursor(editor, true); diff --git a/src/app/components/editor/autocomplete/autocompleteQuery.ts b/src/app/components/editor/autocomplete/autocompleteQuery.ts index 1baa44a1..72a0b484 100644 --- a/src/app/components/editor/autocomplete/autocompleteQuery.ts +++ b/src/app/components/editor/autocomplete/autocompleteQuery.ts @@ -22,7 +22,7 @@ export type AutocompleteQuery = { export const getAutocompletePrefix = ( editor: Editor, queryRange: BaseRange, - validPrefixes: readonly TPrefix[] + validPrefixes: readonly TPrefix[], ): TPrefix | undefined => { const world = Editor.string(editor, queryRange); return validPrefixes.find((p) => world.startsWith(p)); @@ -31,13 +31,13 @@ export const getAutocompletePrefix = ( export const getAutocompleteQueryText = ( editor: Editor, queryRange: BaseRange, - prefix: string + prefix: string, ): string => Editor.string(editor, queryRange).slice(prefix.length); export const getAutocompleteQuery = ( editor: Editor, queryRange: BaseRange, - validPrefixes: readonly TPrefix[] + validPrefixes: readonly TPrefix[], ): AutocompleteQuery | undefined => { const prefix = getAutocompletePrefix(editor, queryRange, validPrefixes); if (!prefix) return undefined; diff --git a/src/app/components/editor/input.ts b/src/app/components/editor/input.ts index ad314add..b6e5dfa1 100644 --- a/src/app/components/editor/input.ts +++ b/src/app/components/editor/input.ts @@ -77,7 +77,7 @@ const getInlineNodeMarkType = (node: Element): MarkType | undefined => { const getInlineMarkElement = ( markType: MarkType, node: Element, - getChild: (child: ChildNode) => InlineElement[] + getChild: (child: ChildNode) => InlineElement[], ): InlineElement[] => { const children = node.children.flatMap(getChild); const mdSequence = node.attribs['data-md']; @@ -115,7 +115,7 @@ const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElemen getText(node) || roomMention.roomIdOrAlias, false, undefined, - roomMention.viaServers + roomMention.viaServers, ); } const eventMention = parseMatrixToRoomEvent(href); @@ -125,7 +125,7 @@ const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElemen getText(node) || eventMention.roomIdOrAlias, false, eventMention.eventId, - eventMention.viaServers + eventMention.viaServers, ); } } @@ -165,7 +165,7 @@ const getInlineElement = (node: ChildNode, processText: ProcessTextCallback): In const parseBlockquoteNode = ( node: Element, - processText: ProcessTextCallback + processText: ProcessTextCallback, ): BlockQuoteElement[] | ParagraphElement[] => { const quoteLines: Array = []; let lineHolder: InlineElement[] = []; @@ -229,7 +229,7 @@ const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElemen })); const childCode = node.children[0]; const className = - isTag(childCode) && childCode.tagName === 'code' ? childCode.attribs.class ?? '' : ''; + isTag(childCode) && childCode.tagName === 'code' ? (childCode.attribs.class ?? '') : ''; const prefix = { text: `${mdSequence}${className.replace('language-', '')}` }; const suffix = { text: mdSequence }; return [ @@ -251,7 +251,7 @@ const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElemen }; const parseListNode = ( node: Element, - processText: ProcessTextCallback + processText: ProcessTextCallback, ): OrderedListElement[] | UnorderedListElement[] | ParagraphElement[] => { const listLines: Array = []; let lineHolder: InlineElement[] = []; @@ -323,7 +323,7 @@ const parseListNode = ( }; const parseHeadingNode = ( node: Element, - processText: ProcessTextCallback + processText: ProcessTextCallback, ): HeadingElement | ParagraphElement => { const children = node.children.flatMap((child) => getInlineElement(child, processText)); @@ -349,7 +349,7 @@ const parseHeadingNode = ( export const domToEditorInput = ( domNodes: ChildNode[], processText: ProcessTextCallback, - processLineStartText: ProcessTextCallback + processLineStartText: ProcessTextCallback, ): Descendant[] => { const children: Descendant[] = []; diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index dbdd51f3..53a31e1f 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -74,7 +74,7 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => { case BlockType.Emoticon: return node.key.startsWith('mxc://') ? `${sanitizeText(
-            node.shortcode
+            node.shortcode,
           )}` : sanitizeText(node.key); case BlockType.Link: @@ -92,12 +92,12 @@ const ignoreHTMLParseInlineMD = (text: string): string => text, HTML_TAG_REG_G, (match) => match[0], - (txt) => parseInlineMD(txt) + (txt) => parseInlineMD(txt), ).join(''); export const toMatrixCustomHTML = ( node: Descendant | Descendant[], - opts: OutputOptions + opts: OutputOptions, ): string => { let markdownLines = ''; const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => { diff --git a/src/app/components/editor/utils.ts b/src/app/components/editor/utils.ts index 6c66cc2d..4fc38c39 100644 --- a/src/app/components/editor/utils.ts +++ b/src/app/components/editor/utils.ts @@ -161,7 +161,7 @@ export const createMentionElement = ( name: string, highlight: boolean, eventId?: string, - viaServers?: string[] + viaServers?: string[], ): MentionElement => ({ type: BlockType.Mention, id, @@ -181,7 +181,7 @@ export const createEmoticonElement = (key: string, shortcode: string): EmoticonE export const createLinkElement = ( href: string, - children: string | FormattedText[] + children: string | FormattedText[], ): LinkElement => ({ type: BlockType.Link, href, @@ -237,7 +237,7 @@ interface PointUntilCharOptions { export const getPointUntilChar = ( editor: Editor, cursorPoint: BasePoint, - options: PointUntilCharOptions + options: PointUntilCharOptions, ): BasePoint | undefined => { let targetPoint: BasePoint | undefined; let prevPoint: BasePoint | undefined; diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 0778fdd2..4fb233af 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -10,12 +10,12 @@ import React, { useRef, } from 'react'; import { Box, config, Scroll } from 'folds'; -import { Icons } from '../icons'; import FocusTrap from 'focus-trap-react'; import { isKeyHotkey } from 'is-hotkey'; import { Room } from 'matrix-js-sdk'; import { atom, PrimitiveAtom, useAtom, useSetAtom } from 'jotai'; import { useVirtualizer } from '@tanstack/react-virtual'; +import { Icons } from '../icons'; import { IEmoji, emojiGroups, emojis } from '../../plugins/emoji'; import { useEmojiGroupLabels } from './useEmojiGroupLabels'; import { useEmojiGroupIcons } from './useEmojiGroupIcons'; @@ -71,7 +71,7 @@ type StickerGroupItem = { const useGroups = ( tab: EmojiBoardTab, - imagePacks: ImagePack[] + imagePacks: ImagePack[], ): [EmojiGroupItem[], StickerGroupItem[]] => { const mx = useMatrixClient(); const { getTopEmojis } = useEmojiUsage(); @@ -88,7 +88,7 @@ const useGroups = ( const mostUsedEmojis = topShortcodes .map((shortcode) => emojis.find((e) => e.shortcode === shortcode)) .filter((e): e is IEmoji => e !== undefined); - + if (mostUsedEmojis.length > 0) { g.push({ id: MOST_USED_GROUP_ID, @@ -320,7 +320,7 @@ function EmojiGroupHolder({ shortcode: emojiInfo.shortcode, }); }, - [setPreviewData] + [setPreviewData], ); const throttleEmojiHover = useThrottle(handleEmojiPreview, { @@ -398,7 +398,7 @@ export function EmojiBoard({ // Get default emoji - use most used or fallback to slight_smile const defaultPreview = useMemo((): PreviewData => { if (!emojiTab) return undefined; - + const mostUsedShortcode = getMostUsedEmoji(); if (mostUsedShortcode) { // Find emoji by shortcode @@ -411,10 +411,7 @@ export function EmojiBoard({ return DefaultEmojiPreview; }, [emojiTab, getMostUsedEmoji]); - const previewAtom = useMemo( - () => createPreviewDataAtom(defaultPreview), - [defaultPreview] - ); + const previewAtom = useMemo(() => createPreviewDataAtom(defaultPreview), [defaultPreview]); const activeGroupIdAtom = useMemo(() => atom(undefined), []); const setActiveGroupId = useSetAtom(activeGroupIdAtom); const imagePacks = useRelevantImagePacks(usage, imagePackRooms); @@ -432,7 +429,7 @@ export function EmojiBoard({ const [result, search, resetSearch] = useAsyncSearch( searchList, getEmoticonSearchStr, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const searchedItems = result?.items.slice(0, 100); @@ -444,9 +441,9 @@ export function EmojiBoard({ if (term) search(term); else resetSearch(); }, - [search, resetSearch] + [search, resetSearch], ), - { wait: 200 } + { wait: 200 }, ); const contentScrollRef = useRef(null); diff --git a/src/app/components/emoji-board/components/NoStickerPacks.tsx b/src/app/components/emoji-board/components/NoStickerPacks.tsx index 484751a6..1e1a7c35 100644 --- a/src/app/components/emoji-board/components/NoStickerPacks.tsx +++ b/src/app/components/emoji-board/components/NoStickerPacks.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { Box, toRem, config, Text } from 'folds'; import { Icons, Icon } from '../../icons'; + export function NoStickerPacks() { return ( [EmojiGroupId.Symbol]: Icons.Peace, [EmojiGroupId.Flag]: Icons.Flag, }), - [] + [], ); diff --git a/src/app/components/emoji-board/useEmojiGroupLabels.ts b/src/app/components/emoji-board/useEmojiGroupLabels.ts index a1e5cf2c..3b224891 100644 --- a/src/app/components/emoji-board/useEmojiGroupLabels.ts +++ b/src/app/components/emoji-board/useEmojiGroupLabels.ts @@ -15,5 +15,5 @@ export const useEmojiGroupLabels = (): IEmojiGroupLabels => [EmojiGroupId.Symbol]: 'Symbols', [EmojiGroupId.Flag]: 'Flags', }), - [] + [], ); diff --git a/src/app/components/event-readers/EventReaders.tsx b/src/app/components/event-readers/EventReaders.tsx index a98bdd3e..072e3fbc 100644 --- a/src/app/components/event-readers/EventReaders.tsx +++ b/src/app/components/event-readers/EventReaders.tsx @@ -1,8 +1,8 @@ import React from 'react'; import classNames from 'classnames'; import { Avatar, Box, Header, IconButton, MenuItem, Scroll, Text, as, config } from 'folds'; -import { Icon, Icons } from '../icons'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../icons'; import { useRoomEventReaders } from '../../hooks/useRoomEventReaders'; import { getMemberDisplayName } from '../../utils/room'; import { getMxIdLocalPart } from '../../utils/matrix'; @@ -59,7 +59,7 @@ export const EventReaders = as<'div', EventReadersProps>( 'crop', undefined, false, - useAuthentication + useAuthentication, ) : undefined; @@ -74,7 +74,7 @@ export const EventReaders = as<'div', EventReadersProps>( space?.roomId, readerId, getMouseEventCords(event.nativeEvent), - 'Bottom' + 'Bottom', ); }} before={ @@ -99,5 +99,5 @@ export const EventReaders = as<'div', EventReadersProps>( ); - } + }, ); diff --git a/src/app/components/icons/Icon.tsx b/src/app/components/icons/Icon.tsx index a0695f56..61a73e5e 100644 --- a/src/app/components/icons/Icon.tsx +++ b/src/app/components/icons/Icon.tsx @@ -15,7 +15,10 @@ export type IconProps = { } & Omit, 'fill'>; export const Icon = forwardRef( - ({ className, size = '400', filled = false, src: LucideIconComponent, style, fill, ...props }, ref) => { + ( + { className, size = '400', filled = false, src: LucideIconComponent, style, fill, ...props }, + ref, + ) => { const pixelSize = ICON_PIXEL_SIZES[size]; return ( @@ -33,11 +36,11 @@ export const Icon = forwardRef( // Emphasize selection with a heavier stroke instead. strokeWidth={filled ? 2.75 : 2} fill={fill ?? 'none'} - aria-hidden={props['aria-hidden'] ?? props['aria-label'] ? undefined : true} + aria-hidden={(props['aria-hidden'] ?? props['aria-label']) ? undefined : true} {...props} /> ); - } + }, ); Icon.displayName = 'Icon'; diff --git a/src/app/components/image-editor/ImageEditor.tsx b/src/app/components/image-editor/ImageEditor.tsx index 4655392d..579c71de 100644 --- a/src/app/components/image-editor/ImageEditor.tsx +++ b/src/app/components/image-editor/ImageEditor.tsx @@ -48,5 +48,5 @@ export const ImageEditor = as<'div', ImageEditorProps>( ); - } + }, ); diff --git a/src/app/components/image-pack-view/ImagePackContent.tsx b/src/app/components/image-pack-view/ImagePackContent.tsx index a696ebe8..b26b2219 100644 --- a/src/app/components/image-pack-view/ImagePackContent.tsx +++ b/src/app/components/image-pack-view/ImagePackContent.tsx @@ -57,7 +57,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( Array.from(savedImages).find(([, img]) => img.shortcode === shortcode) !== undefined; return hasInSaved; }, - [imagePack, savedImages, uploadedImages] + [imagePack, savedImages, uploadedImages], ); const pickFiles = useFilePicker( @@ -74,9 +74,9 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( setFiles((f) => [...f, ...uniqueFiles]); }, - [hasImageWithShortcode] + [hasImageWithShortcode], ), - true + true, ); const handleMetaSave = useCallback( @@ -88,10 +88,10 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( ...imagePack.meta.content, ...m?.content, ...editedMeta.content, - }) + }), ); }, - [imagePack.meta] + [imagePack.meta], ); const handleMetaCancel = () => setMetaEditing(false); @@ -104,10 +104,10 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( ...imagePack.meta.content, ...m?.content, usage: usg, - }) + }), ); }, - [imagePack.meta] + [imagePack.meta], ); const handleUploadRemove = useCallback((file: TUploadContent) => { @@ -123,13 +123,13 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( }; const image = PackImageReader.fromPackImage( getFileNameWithoutExt(data.file.name), - packImage + packImage, ); if (!image) return; handleUploadRemove(data.file); setUploadedImages((imgs) => [image, ...imgs]); }, - [handleUploadRemove] + [handleUploadRemove], ); const handleImageEdit = (shortcode: string) => { @@ -164,7 +164,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( ? new PackImageReader( suffixRename(image.shortcode, hasImageWithShortcode), image.url, - image.content + image.content, ) : image; @@ -199,7 +199,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( images.forEach((img) => pushImage(img)); return onUpdate?.(pack); - }, [imagePack, images, savedMeta, uploadedImages, savedImages, deleteImages, onUpdate]) + }, [imagePack, images, savedMeta, uploadedImages, savedImages, deleteImages, onUpdate]), ); useEffect(() => { @@ -384,5 +384,5 @@ export const ImagePackContent = as<'div', ImagePackContentProps>( )} ); - } + }, ); diff --git a/src/app/components/image-pack-view/PackMeta.tsx b/src/app/components/image-pack-view/PackMeta.tsx index 9de5bde6..9fb4662c 100644 --- a/src/app/components/image-pack-view/PackMeta.tsx +++ b/src/app/components/image-pack-view/PackMeta.tsx @@ -1,7 +1,7 @@ import React, { FormEventHandler, useCallback, useMemo, useState } from 'react'; import { Box, Text, Avatar, AvatarFallback, Button, Input, TextArea, Chip } from 'folds'; -import { Icon, Icons } from '../icons'; import Linkify from 'linkify-react'; +import { Icon, Icons } from '../icons'; import { mxcUrlToHttp } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { nameInitials } from '../../utils/common'; @@ -43,7 +43,7 @@ export function ImagePackProfile({ meta, canEdit, onEdit }: ImagePackProfileProp const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const avatarUrl = meta.avatar - ? mxcUrlToHttp(mx, meta.avatar, useAuthentication) ?? undefined + ? (mxcUrlToHttp(mx, meta.avatar, useAuthentication) ?? undefined) : undefined; return ( @@ -91,7 +91,7 @@ export function ImagePackProfileEdit({ meta, onCancel, onSave }: ImagePackProfil const useAuthentication = useMediaAuthentication(); const [avatar, setAvatar] = useState(meta.avatar); - const avatarUrl = avatar ? mxcUrlToHttp(mx, avatar, useAuthentication) ?? undefined : undefined; + const avatarUrl = avatar ? (mxcUrlToHttp(mx, avatar, useAuthentication) ?? undefined) : undefined; const [imageFile, setImageFile] = useState(); const avatarFileUrl = useObjectURL(imageFile); diff --git a/src/app/components/image-pack-view/RoomImagePack.tsx b/src/app/components/image-pack-view/RoomImagePack.tsx index 92b4ff21..511be318 100644 --- a/src/app/components/image-pack-view/RoomImagePack.tsx +++ b/src/app/components/image-pack-view/RoomImagePack.tsx @@ -32,7 +32,7 @@ export function RoomImagePack({ room, stateKey }: RoomImagePackProps) { { roomId: room.roomId, stateKey, - } + }, ); }, [room.roomId, stateKey]); const imagePack = useRoomImagePack(room, stateKey) ?? fallbackPack; @@ -46,10 +46,10 @@ export function RoomImagePack({ room, stateKey }: RoomImagePackProps) { address.roomId, StateEvent.PoniesRoomEmotes, packContent, - address.stateKey + address.stateKey, ); }, - [mx, imagePack] + [mx, imagePack], ); return ( diff --git a/src/app/components/image-pack-view/UsageSwitcher.tsx b/src/app/components/image-pack-view/UsageSwitcher.tsx index b8c805b6..aa508eef 100644 --- a/src/app/components/image-pack-view/UsageSwitcher.tsx +++ b/src/app/components/image-pack-view/UsageSwitcher.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, useMemo, useState } from 'react'; import { Box, Button, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; -import { Icon, Icons } from '../icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../icons'; import { ImageUsage } from '../../plugins/custom-emoji'; import { stopPropagation } from '../../utils/keyboard'; @@ -30,7 +30,7 @@ export function UsageSelector({ selected, onChange }: UsageSelectorProps) { const allUsages: ImageUsage[][] = useMemo( () => [[ImageUsage.Emoticon], [ImageUsage.Sticker], [ImageUsage.Sticker, ImageUsage.Emoticon]], - [] + [], ); return ( diff --git a/src/app/components/image-pack-view/UserImagePack.tsx b/src/app/components/image-pack-view/UserImagePack.tsx index 4987793d..05d30acd 100644 --- a/src/app/components/image-pack-view/UserImagePack.tsx +++ b/src/app/components/image-pack-view/UserImagePack.tsx @@ -15,7 +15,7 @@ export function UserImagePack() { async (packContent: PackContent) => { await mx.setAccountData(AccountDataEvent.PoniesUserEmotes, packContent); }, - [mx] + [mx], ); return ; diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index 4e9fd981..0f2b7fd0 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -1,11 +1,4 @@ -/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */ -import React, { - useCallback, - useEffect, - useLayoutEffect, - useRef, - useState, -} from 'react'; +import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import { as } from 'folds'; import { Icon, Icons } from '../icons'; @@ -42,16 +35,13 @@ function imageViewportMax() { }; } -function pointerDistance( - a: { x: number; y: number }, - b: { x: number; y: number } -): number { +function pointerDistance(a: { x: number; y: number }, b: { x: number; y: number }): number { return Math.hypot(a.x - b.x, a.y - b.y); } function pointerMidpoint( a: { x: number; y: number }, - b: { x: number; y: number } + b: { x: number; y: number }, ): { x: number; y: number } { return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; } @@ -123,7 +113,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( applyZoomCss(clamped); setZoom(clamped); }, - [applyZoomCss, clampPan] + [applyZoomCss, clampPan], ); const resetZoom = useCallback(() => { @@ -162,7 +152,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( ty: py - iy * scale, }); }, - [commitZoom] + [commitZoom], ); const framePoint = (clientX: number, clientY: number) => { @@ -202,7 +192,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( const local = framePoint(mid.x, mid.y); const scale = Math.min( ZOOM_MAX, - Math.max(ZOOM_MIN, pinch.startScale * (dist / pinch.startDist)) + Math.max(ZOOM_MIN, pinch.startScale * (dist / pinch.startDist)), ); // Keep the original content under the pinch midpoint while scaling + panning. @@ -441,5 +431,5 @@ export const ImageViewer = as<'div', ImageViewerProps>( ); - } + }, ); diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index ab1284ad..cae8362b 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -7,11 +7,30 @@ import React, { useRef, useState, } from 'react'; -import { Overlay, OverlayBackdrop, OverlayCenter, Box, Header, config, Text, IconButton, Input, Button, Spinner, color, TextArea, Dialog, Menu, toRem, Scroll, MenuItem } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Overlay, + OverlayBackdrop, + OverlayCenter, + Box, + Header, + config, + Text, + IconButton, + Input, + Button, + Spinner, + color, + TextArea, + Dialog, + Menu, + toRem, + Scroll, + MenuItem, +} from 'folds'; import { Room } from 'matrix-js-sdk'; import { isKeyHotkey } from 'is-hotkey'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../icons'; import { stopPropagation } from '../../utils/keyboard'; import { useDirectUsers } from '../../hooks/useDirectUsers'; import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix'; @@ -49,12 +68,12 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { const membership = room.getMember(userId)?.membership; return membership !== Membership.Join; }), - [directUsers, room] + [directUsers, room], ); const [result, search, resetSearch] = useAsyncSearch( filteredUsers, getUserIdString, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const queryHighlighRegex = result?.query ? makeHighlightRegex(result.query.split(' ')) @@ -65,8 +84,8 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { async (userId, reason) => { await mx.invite(room.roomId, userId, reason); }, - [mx, room] - ) + [mx, room], + ), ); const inviting = inviteState.status === AsyncStatus.Loading; diff --git a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx index 4eff4840..385f6208 100644 --- a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx +++ b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx @@ -1,6 +1,19 @@ import React, { FormEventHandler, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, Button, Input, color } from 'folds'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + Button, + Input, + color, +} from 'folds'; import { Icon, Icons } from '../icons'; import { stopPropagation } from '../../utils/keyboard'; import { isRoomAlias, isRoomId } from '../../utils/matrix'; diff --git a/src/app/components/join-space-prompt/JoinSpacePrompt.tsx b/src/app/components/join-space-prompt/JoinSpacePrompt.tsx index 631fb159..8980f88e 100644 --- a/src/app/components/join-space-prompt/JoinSpacePrompt.tsx +++ b/src/app/components/join-space-prompt/JoinSpacePrompt.tsx @@ -1,8 +1,25 @@ import React, { useMemo, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner, Scroll, Checkbox, Avatar, Badge } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + color, + Button, + Spinner, + Scroll, + Checkbox, + Avatar, + Badge, +} from 'folds'; import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces'; +import { Icon, Icons } from '../icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { stopPropagation } from '../../utils/keyboard'; import { RoomType, Membership } from '../../../types/matrix/room'; @@ -274,7 +291,7 @@ export function JoinSpacePrompt({ mx, item.room_id, RoomNotificationMode.SpecialMessages, - RoomNotificationMode.Unset + RoomNotificationMode.Unset, ); } @@ -290,12 +307,12 @@ export function JoinSpacePrompt({ // Join spaces first, then rooms await spacesToJoin.reduce( (promise, space) => promise.then(() => joinItem(space, true)), - Promise.resolve() + Promise.resolve(), ); await regularRoomsToJoin.reduce( (promise, room) => promise.then(() => joinItem(room, false)), - Promise.resolve() + Promise.resolve(), ); setProgress(null); @@ -334,11 +351,11 @@ export function JoinSpacePrompt({ const isJoining = phase === 'joining-space' || phase === 'joining-rooms'; const spaces = useMemo( () => hierarchyRooms.filter((r) => r.room_type === RoomType.Space), - [hierarchyRooms] + [hierarchyRooms], ); const rooms = useMemo( () => hierarchyRooms.filter((r) => r.room_type !== RoomType.Space), - [hierarchyRooms] + [hierarchyRooms], ); const getButtonText = () => { @@ -451,11 +468,7 @@ export function JoinSpacePrompt({ - + {spaces.length > 0 && ( @@ -525,7 +538,9 @@ export function JoinSpacePrompt({ variant="Primary" onClick={handlePrimaryAction} disabled={isJoining} - before={isJoining ? : undefined} + before={ + isJoining ? : undefined + } aria-disabled={isJoining} > {getButtonText()} diff --git a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx index d2b4f226..4d64f9df 100644 --- a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx +++ b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx @@ -1,8 +1,21 @@ import React, { useCallback, useEffect } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + color, + Button, + Spinner, +} from 'folds'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; @@ -18,7 +31,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro const [leaveState, leaveRoom] = useAsyncCallback( useCallback(async () => { mx.leave(roomId); - }, [mx, roomId]) + }, [mx, roomId]), ); const handleLeave = () => { diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx index 27e09a62..d8f289be 100644 --- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx +++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx @@ -1,9 +1,22 @@ import React, { useCallback, useEffect, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + color, + Button, + Spinner, +} from 'folds'; import { MatrixError, Room } from 'matrix-js-sdk'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; @@ -28,7 +41,7 @@ function delay(ms: number): Promise { async function leaveRoomsSequentially( mx: ReturnType, roomIds: string[], - onProgress?: (current: number, total: number) => void + onProgress?: (current: number, total: number) => void, ): Promise { const total = roomIds.length; @@ -53,7 +66,7 @@ async function leaveRoomsSequentially( function getDirectChildRoomsToLeave( mx: ReturnType, spaceRoom: Room, - mDirects: Set + mDirects: Set, ): string[] { const childIds = getSpaceChildren(spaceRoom); @@ -111,7 +124,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP // Clear progress and leave the space itself setProgress(null); await mx.leave(roomId); - }, [mx, roomId, mDirects]) + }, [mx, roomId, mDirects]), ); const handleLeave = () => { diff --git a/src/app/components/manage-rooms-prompt/ManageRoomsPrompt.tsx b/src/app/components/manage-rooms-prompt/ManageRoomsPrompt.tsx index 6ce94bbc..bbc7bc6b 100644 --- a/src/app/components/manage-rooms-prompt/ManageRoomsPrompt.tsx +++ b/src/app/components/manage-rooms-prompt/ManageRoomsPrompt.tsx @@ -1,8 +1,26 @@ import React, { useMemo, useState, useCallback, useRef, useEffect, MouseEvent } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner, Scroll, Checkbox, Badge, Line, Avatar } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + color, + Button, + Spinner, + Scroll, + Checkbox, + Badge, + Line, + Avatar, +} from 'folds'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { stopPropagation } from '../../utils/keyboard'; import { RoomAvatar } from '../room-avatar'; @@ -95,9 +113,7 @@ function RoomItem({ room, selected, onToggle, onShiftClick, disabled }: RoomItem roomId={room.roomId} src={avatarUrl} alt={roomName} - renderFallback={() => ( - {nameInitials(roomName, 2)} - )} + renderFallback={() => {nameInitials(roomName, 2)}} /> @@ -128,7 +144,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt const [selectedRoomIds, setSelectedRoomIds] = useState>(new Set()); const [phase, setPhase] = useState('selecting'); const [leaveProgress, setLeaveProgress] = useState<{ current: number; total: number } | null>( - null + null, ); const [errorMessage, setErrorMessage] = useState(null); const lastSelectedIndex = useRef(null); @@ -140,7 +156,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt const nameB = b.name?.toLowerCase() || ''; return nameA.localeCompare(nameB); }), - [rooms] + [rooms], ); /** @@ -179,7 +195,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt }); lastSelectedIndex.current = index; }, - [handleToggle, sortedRooms] + [handleToggle, sortedRooms], ); /** @@ -208,10 +224,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt } catch (error) { // Check if it's a rate limit error (429) const isRateLimited = - error && - typeof error === 'object' && - 'httpStatus' in error && - error.httpStatus === 429; + error && typeof error === 'object' && 'httpStatus' in error && error.httpStatus === 429; if (isRateLimited && attempt < MAX_RETRIES) { const retryDelay = getRetryDelay(error, attempt); @@ -221,7 +234,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt return false; } }, - [mx] + [mx], ); /** @@ -312,7 +325,9 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt ) : ( <> - Successfully left all selected rooms! + + Successfully left all selected rooms! + )} diff --git a/src/app/components/media/Image.tsx b/src/app/components/media/Image.tsx index b54a3a62..7ab64e2c 100644 --- a/src/app/components/media/Image.tsx +++ b/src/app/components/media/Image.tsx @@ -11,5 +11,5 @@ export const Image = forwardRef - ) + ), ); diff --git a/src/app/components/media/MediaControls.tsx b/src/app/components/media/MediaControls.tsx index 95a344ab..fb8565d2 100644 --- a/src/app/components/media/MediaControls.tsx +++ b/src/app/components/media/MediaControls.tsx @@ -23,5 +23,5 @@ export const MediaControl = as<'div', MediaControlProps>( {after && {after}} {children} - ) + ), ); diff --git a/src/app/components/media/Video.tsx b/src/app/components/media/Video.tsx index 8088b566..7b6079f6 100644 --- a/src/app/components/media/Video.tsx +++ b/src/app/components/media/Video.tsx @@ -44,13 +44,13 @@ export const Video = forwardRef( if (disableControls) { return ( // eslint-disable-next-line jsx-a11y/media-has-caption - ); - } + }, ); diff --git a/src/app/components/message/StationeryMedia.tsx b/src/app/components/message/StationeryMedia.tsx index 9a80b15f..9b426893 100644 --- a/src/app/components/message/StationeryMedia.tsx +++ b/src/app/components/message/StationeryMedia.tsx @@ -56,7 +56,7 @@ function cornerPeelPaths( cy: number, ux: number, uy: number, - size: number + size: number, ): { keep: string; flap: string; @@ -147,20 +147,21 @@ export function StationeryMedia({ const isStationery = isStationeryTheme(theme); const peelRef = useRef(null); - const tiltStyle = useMemo((): CSSProperties => { - return { + const tiltStyle = useMemo( + (): CSSProperties => ({ ...(style as CSSProperties | undefined), // Margin sits outside the paper chrome — snaps the grid without a white bar ...(isStationery && gridPad > 0 ? { marginBottom: `${gridPad}px` } : null), ['--media-rot' as string]: stationeryMediaRot(tiltSeed), - }; - }, [tiltSeed, style, isStationery, gridPad]); + }), + [tiltSeed, style, isStationery, gridPad], + ); const tapeAlt = useMemo(() => hashStationerySeed(tiltSeed) % 2 === 1, [tiltSeed]); // Default tape covers TL; alt covers TR — peel only the free top corner const peelCorner = useMemo( () => (tapeAlt ? CORNERS.find((c) => c.id === 'tl')! : CORNERS.find((c) => c.id === 'tr')!), - [tapeAlt] + [tapeAlt], ); const clearPeel = useCallback((host: HTMLElement) => { @@ -237,7 +238,7 @@ export function StationeryMedia({ cy, ux, uy, - size + size, ); target.style.clipPath = keep; peel.style.clipPath = flap; @@ -253,7 +254,7 @@ export function StationeryMedia({ clearPeel(host); } }, - [peelCorner, clearPeel] + [peelCorner, clearPeel], ); const handleMove: MouseEventHandler = (evt) => { diff --git a/src/app/components/message/Time.tsx b/src/app/components/message/Time.tsx index 3eab5cc2..29716c58 100644 --- a/src/app/components/message/Time.tsx +++ b/src/app/components/message/Time.tsx @@ -41,5 +41,5 @@ export const Time = as<'span', TimeProps & ComponentProps>( {time} ); - } + }, ); diff --git a/src/app/components/message/attachment/Attachment.tsx b/src/app/components/message/attachment/Attachment.tsx index 1f05598b..773c8792 100644 --- a/src/app/components/message/attachment/Attachment.tsx +++ b/src/app/components/message/attachment/Attachment.tsx @@ -12,7 +12,7 @@ export const Attachment = as<'div', css.AttachmentVariants>( {...props} ref={ref} /> - ) + ), ); export const AttachmentHeader = as<'div'>(({ className, ...props }, ref) => ( diff --git a/src/app/components/message/content/AudioContent.tsx b/src/app/components/message/content/AudioContent.tsx index 3bccb24d..01f0d01a 100644 --- a/src/app/components/message/content/AudioContent.tsx +++ b/src/app/components/message/content/AudioContent.tsx @@ -1,9 +1,9 @@ /* eslint-disable jsx-a11y/media-has-caption */ import React, { ReactNode, useCallback, useRef, useState } from 'react'; import { Badge, Chip, IconButton, ProgressBar, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../icons'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { Range } from 'react-range'; +import { Icon, Icons } from '../../icons'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { IAudioInfo } from '../../../../types/matrix/common'; @@ -60,10 +60,14 @@ export function AudioContent({ // Always use current session's token to avoid stale tokens during account switches const accessToken = getCurrentAccessToken(); const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken) + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, + ) : await downloadMedia(mediaUrl, accessToken); return URL.createObjectURL(fileContent); - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo]), ); const audioRef = useRef(null); @@ -84,7 +88,7 @@ export function AudioContent({ }, []); useMediaPlayTimeCallback( getAudioRef, - useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS) + useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS), ); const handlePlay = () => { @@ -152,7 +156,7 @@ export function AudioContent({ {`${secondsToMinutesAndSeconds( - currentTime + currentTime, )} / ${secondsToMinutesAndSeconds(duration)}`} ), diff --git a/src/app/components/message/content/EventContent.tsx b/src/app/components/message/content/EventContent.tsx index 43185cda..0f3d8da7 100644 --- a/src/app/components/message/content/EventContent.tsx +++ b/src/app/components/message/content/EventContent.tsx @@ -1,6 +1,6 @@ import { Box } from 'folds'; -import { Icon, IconSrc } from '../../icons'; import React, { ReactNode } from 'react'; +import { Icon, IconSrc } from '../../icons'; import { BubbleLayout, CompactLayout, ModernLayout } from '..'; import { MessageLayout } from '../../../state/settings'; diff --git a/src/app/components/message/content/FallbackContent.tsx b/src/app/components/message/content/FallbackContent.tsx index ba73a1a6..ce31c4f3 100644 --- a/src/app/components/message/content/FallbackContent.tsx +++ b/src/app/components/message/content/FallbackContent.tsx @@ -1,6 +1,6 @@ import { Box, Text, as, color, config } from 'folds'; -import { Icon, Icons } from '../../icons'; import React from 'react'; +import { Icon, Icons } from '../../icons'; const warningStyle = { color: color.Warning.Main, opacity: config.opacity.P300 }; const criticalStyle = { color: color.Critical.Main, opacity: config.opacity.P300 }; @@ -15,7 +15,7 @@ export const MessageDeletedContent = as<'div', { children?: never; reason?: stri This message has been deleted )} - ) + ), ); export const MessageUnsupportedContent = as<'div', { children?: never }>(({ ...props }, ref) => ( diff --git a/src/app/components/message/content/FileContent.tsx b/src/app/components/message/content/FileContent.tsx index 82f97068..9225a6a0 100644 --- a/src/app/components/message/content/FileContent.tsx +++ b/src/app/components/message/content/FileContent.tsx @@ -1,9 +1,21 @@ import React, { ReactNode, useCallback, useState } from 'react'; -import { Box, Button, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds'; -import { Icon, Icons } from '../../icons'; +import { + Box, + Button, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Spinner, + Text, + Tooltip, + TooltipProvider, + as, +} from 'folds'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; -import { saveMediaBlob } from '../../../utils/saveMedia'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../icons'; +import { saveMediaBlob } from '../../../utils/saveMedia'; import { IFileInfo } from '../../../../types/matrix/common'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; @@ -78,13 +90,17 @@ export function ReadTextFile({ body, mimeType, url, encInfo, renderViewer }: Rea // Always use current session's token to avoid stale tokens during account switches const accessToken = getCurrentAccessToken(); const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken) + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, + ) : await downloadMedia(mediaUrl, accessToken); const text = fileContent.text(); setTextViewer(true); return text; - }, [mx, useAuthentication, mimeType, encInfo, url]) + }, [mx, useAuthentication, mimeType, encInfo, url]), ); return ( @@ -170,11 +186,15 @@ export function ReadPdfFile({ body, mimeType, url, encInfo, renderViewer }: Read // Always use current session's token to avoid stale tokens during account switches const accessToken = getCurrentAccessToken(); const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken) + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, + ) : await downloadMedia(mediaUrl, accessToken); setPdfViewer(true); return URL.createObjectURL(fileContent); - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo]), ); return ( @@ -249,12 +269,16 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil // Always use current session's token to avoid stale tokens during account switches const accessToken = getCurrentAccessToken(); const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken) + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, + ) : await downloadMedia(mediaUrl, accessToken); await saveMediaBlob(fileContent, body); return fileContent; - }, [mx, url, useAuthentication, mimeType, encInfo, body]) + }, [mx, url, useAuthentication, mimeType, encInfo, body]), ); return downloadState.status === AsyncStatus.Error ? ( @@ -299,5 +323,5 @@ export const FileContent = as<'div', FileContentProps>( {mimeType === 'application/pdf' && renderAsPdfFile()} {children} - ) + ), ); diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 6b4c95b4..c8e6fb21 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -1,10 +1,21 @@ import React, { ReactNode, useCallback, useEffect, useState } from 'react'; -import { Badge, Box, Button, Chip, Overlay, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds'; -import { Icon, Icons } from '../../icons'; +import { + Badge, + Box, + Button, + Chip, + Overlay, + Spinner, + Text, + Tooltip, + TooltipProvider, + as, +} from 'folds'; import classNames from 'classnames'; import { Blurhash } from 'react-blurhash'; import FocusTrap from 'focus-trap-react'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; +import { Icon, Icons } from '../../icons'; import { IImageInfo, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../../types/matrix/common'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; @@ -16,7 +27,12 @@ import { decryptFile, downloadEncryptedMedia, mxcUrlToHttp } from '../../../util import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { validBlurHash } from '../../../utils/blurHash'; import { getCurrentAccessToken } from '../../../utils/auth'; -import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache'; +import { + setMediaDimensions, + getMediaBlurHash, + getMediaDimensions, + rememberMediaBlurHash, +} from '../../../state/mediaDimensionCache'; /** * Fetches media with authentication headers and returns a blob URL. @@ -26,28 +42,36 @@ import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMedia */ const fetchAuthenticatedMedia = async ( url: string, - accessToken: string | null + accessToken: string | null, ): Promise => { try { let response = await fetch(url, { method: 'GET', headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined, }); - + // If we got a 401 and we tried with auth, fallback to unauthenticated request if (!response.ok && response.status === 401 && accessToken) { - console.warn('[ImageContent] Auth failed (401), attempting unauthenticated fallback for:', url); + console.warn( + '[ImageContent] Auth failed (401), attempting unauthenticated fallback for:', + url, + ); response = await fetch(url, { method: 'GET' }); } - + if (!response.ok) { - console.warn(`[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`); + console.warn( + `[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`, + ); return url; } const blob = await response.blob(); return URL.createObjectURL(blob); } catch (error) { - console.warn('[ImageContent] Error fetching authenticated media, falling back to original URL:', error); + console.warn( + '[ImageContent] Error fetching authenticated media, falling back to original URL:', + error, + ); return url; } }; @@ -101,7 +125,7 @@ export const ImageContent = as<'div', ImageContentProps>( renderImage, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -132,7 +156,7 @@ export const ImageContent = as<'div', ImageContentProps>( const fileContent = await downloadEncryptedMedia( mediaUrl, (encBuf) => decryptFile(encBuf, mimeType ?? FALLBACK_MIMETYPE, encInfo), - accessToken + accessToken, ); return URL.createObjectURL(fileContent); } @@ -141,7 +165,7 @@ export const ImageContent = as<'div', ImageContentProps>( return fetchAuthenticatedMedia(mediaUrl, accessToken); } return mediaUrl; - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo]), ); const handleLoad = () => { @@ -228,7 +252,7 @@ export const ImageContent = as<'div', ImageContentProps>( css.AbsoluteContainer, css.MediaFadeIn, load && css.MediaFadeInLoaded, - blurred && css.Blur + blurred && css.Blur, )} > {renderImage({ @@ -327,5 +351,5 @@ export const ImageContent = as<'div', ImageContentProps>( )} ); - } + }, ); diff --git a/src/app/components/message/content/ThumbnailContent.tsx b/src/app/components/message/content/ThumbnailContent.tsx index c67e12ab..20acd734 100644 --- a/src/app/components/message/content/ThumbnailContent.tsx +++ b/src/app/components/message/content/ThumbnailContent.tsx @@ -2,7 +2,12 @@ import { ReactNode, useCallback, useEffect } from 'react'; import { IThumbnailContent } from '../../../../types/matrix/common'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; -import { decryptFile, downloadEncryptedMedia, isAuthenticatedMediaUrl, mxcUrlToHttp } from '../../../utils/matrix'; +import { + decryptFile, + downloadEncryptedMedia, + isAuthenticatedMediaUrl, + mxcUrlToHttp, +} from '../../../utils/matrix'; import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { FALLBACK_MIMETYPE } from '../../../utils/mimeTypes'; import { getCurrentAccessToken } from '../../../utils/auth'; @@ -14,28 +19,36 @@ import { getCurrentAccessToken } from '../../../utils/auth'; */ const fetchAuthenticatedMedia = async ( url: string, - accessToken: string | null + accessToken: string | null, ): Promise => { try { let response = await fetch(url, { method: 'GET', headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined, }); - + // If we got a 401 and we tried with auth, fallback to unauthenticated request if (!response.ok && response.status === 401 && accessToken) { - console.warn('[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:', url); + console.warn( + '[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:', + url, + ); response = await fetch(url, { method: 'GET' }); } - + if (!response.ok) { - console.warn(`[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`); + console.warn( + `[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`, + ); return url; } const blob = await response.blob(); return URL.createObjectURL(blob); } catch (error) { - console.warn('[ThumbnailContent] Error fetching authenticated media, falling back to original URL:', error); + console.warn( + '[ThumbnailContent] Error fetching authenticated media, falling back to original URL:', + error, + ); return url; } }; @@ -51,7 +64,8 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) { // Check if we have valid thumbnail data const thumbInfo = info.thumbnail_info; const thumbMxcUrl = info.thumbnail_file?.url ?? info.thumbnail_url; - const hasValidThumbnail = typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string'; + const hasValidThumbnail = + typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string'; const [thumbSrcState, loadThumbSrc] = useAsyncCallback( useCallback(async () => { @@ -64,7 +78,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) { const fileContent = await downloadEncryptedMedia( mediaUrl, (encBuf) => decryptFile(encBuf, thumbInfo.mimetype ?? FALLBACK_MIMETYPE, encInfo), - accessToken + accessToken, ); return URL.createObjectURL(fileContent); } @@ -75,7 +89,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) { } return mediaUrl; - }, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication]) + }, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication]), ); useEffect(() => { diff --git a/src/app/components/message/content/VideoContent.tsx b/src/app/components/message/content/VideoContent.tsx index ca615a6f..cc0ec072 100644 --- a/src/app/components/message/content/VideoContent.tsx +++ b/src/app/components/message/content/VideoContent.tsx @@ -1,10 +1,24 @@ import React, { ReactNode, useCallback, useEffect, useState } from 'react'; -import { Badge, Box, Button, Chip, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds'; -import { Icon, Icons } from '../../icons'; +import { + Badge, + Box, + Button, + Chip, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Spinner, + Text, + Tooltip, + TooltipProvider, + as, +} from 'folds'; import classNames from 'classnames'; import { Blurhash } from 'react-blurhash'; import FocusTrap from 'focus-trap-react'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; +import { Icon, Icons } from '../../icons'; import { IThumbnailContent, IVideoInfo, @@ -25,7 +39,12 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { validBlurHash } from '../../../utils/blurHash'; import { ModalWide } from '../../../styles/Modal.css'; import { stopPropagation } from '../../../utils/keyboard'; -import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache'; +import { + setMediaDimensions, + getMediaBlurHash, + getMediaDimensions, + rememberMediaBlurHash, +} from '../../../state/mediaDimensionCache'; type RenderViewerProps = { src: string; @@ -71,7 +90,7 @@ export const VideoContent = as<'div', VideoContentProps>( renderVideo, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -83,9 +102,7 @@ export const VideoContent = as<'div', VideoContentProps>( const blurW = info.w ?? info.thumbnail_info?.w ?? cachedDims?.w; const blurH = info.h ?? info.thumbnail_info?.h ?? cachedDims?.h; const blurResolutionY = - blurW && blurH && blurW > 0 - ? Math.max(1, Math.round(blurResolutionX * (blurH / blurW))) - : 32; + blurW && blurH && blurW > 0 ? Math.max(1, Math.round(blurResolutionX * (blurH / blurW))) : 32; const [load, setLoad] = useState(false); const [error, setError] = useState(false); @@ -99,12 +116,14 @@ export const VideoContent = as<'div', VideoContentProps>( // Always use current session's token to avoid stale tokens during account switches const accessToken = getCurrentAccessToken(); const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => - decryptFile(encBuf, mimeType, encInfo), accessToken + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, ) : await downloadMedia(mediaUrl, accessToken); return URL.createObjectURL(fileContent); - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo]), ); const handleLoad = (video?: HTMLVideoElement) => { @@ -207,7 +226,7 @@ export const VideoContent = as<'div', VideoContentProps>( css.AbsoluteContainer, css.MediaFadeIn, load && css.MediaFadeInLoaded, - blurred && css.Blur + blurred && css.Blur, )} > {renderVideo({ @@ -306,5 +325,5 @@ export const VideoContent = as<'div', VideoContentProps>( )} ); - } + }, ); diff --git a/src/app/components/message/content/VideoFrameThumbnail.tsx b/src/app/components/message/content/VideoFrameThumbnail.tsx index 1edcff59..b8e80025 100644 --- a/src/app/components/message/content/VideoFrameThumbnail.tsx +++ b/src/app/components/message/content/VideoFrameThumbnail.tsx @@ -2,13 +2,18 @@ import { ReactNode, useCallback, useEffect, useState } from 'react'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; -import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '../../../utils/matrix'; +import { + decryptFile, + downloadEncryptedMedia, + downloadMedia, + mxcUrlToHttp, +} from '../../../utils/matrix'; import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { getCurrentAccessToken } from '../../../utils/auth'; /** * Extracts the first frame from a video file and renders it as a thumbnail. - * This is used as a fallback when no thumbnail metadata is provided. + * This is used as a fallback when no thumbnail metadata is provided. */ export type VideoFrameThumbnailProps = { mimeType: string; @@ -31,15 +36,17 @@ export function VideoFrameThumbnail({ useCallback(async () => { const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication) ?? url; const accessToken = getCurrentAccessToken(); - + const fileContent = encInfo - ? await downloadEncryptedMedia(mediaUrl, (encBuf) => - decryptFile(encBuf, mimeType, encInfo), accessToken + ? await downloadEncryptedMedia( + mediaUrl, + (encBuf) => decryptFile(encBuf, mimeType, encInfo), + accessToken, ) : await downloadMedia(mediaUrl, accessToken); - + return URL.createObjectURL(fileContent); - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo]), ); useEffect(() => { @@ -69,7 +76,7 @@ export function VideoFrameThumbnail({ const cleanup = () => { if (isCleanedUp) return; isCleanedUp = true; - + if (handlers.loadedData) video.removeEventListener('loadeddata', handlers.loadedData); if (handlers.seeked) video.removeEventListener('seeked', handlers.seeked); if (handlers.error) video.removeEventListener('error', handlers.error); @@ -90,7 +97,7 @@ export function VideoFrameThumbnail({ const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; - + const ctx = canvas.getContext('2d'); if (!ctx) { cleanup(); @@ -98,14 +105,18 @@ export function VideoFrameThumbnail({ } ctx.drawImage(video, 0, 0, canvas.width, canvas.height); - - canvas.toBlob((blob) => { - if (blob) { - const thumbnailUrl = URL.createObjectURL(blob); - setThumbnailSrc(thumbnailUrl); - } - cleanup(); - }, 'image/jpeg', 0.85); + + canvas.toBlob( + (blob) => { + if (blob) { + const thumbnailUrl = URL.createObjectURL(blob); + setThumbnailSrc(thumbnailUrl); + } + cleanup(); + }, + 'image/jpeg', + 0.85, + ); } catch { cleanup(); } diff --git a/src/app/components/message/layout/Base.tsx b/src/app/components/message/layout/Base.tsx index 02da6444..4d1fa3fb 100644 --- a/src/app/components/message/layout/Base.tsx +++ b/src/app/components/message/layout/Base.tsx @@ -6,17 +6,20 @@ import { isStationeryTheme, useTheme } from '../../../hooks/useTheme'; import { STATIONERY_NAME_INK } from '../../../utils/paperSafeInk'; export const MessageBase = as<'div', css.MessageBaseVariants>( - ({ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props }, ref) => ( + ( + { className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props }, + ref, + ) => (
- ) + ), ); export const AvatarBase = as<'span'>(({ className, ...props }, ref) => ( @@ -28,37 +31,39 @@ export const AvatarBase = as<'span'>(({ className, ...props }, ref) => ( /> )); -export const Username = as<'span'>(({ as: AsUsername = 'span', className, style, ...props }, ref) => { - const theme = useTheme(); - const isStationery = isStationeryTheme(theme); - const userColor = - typeof (style as CSSProperties | undefined)?.color === 'string' - ? ((style as CSSProperties).color as string) - : undefined; +export const Username = as<'span'>( + ({ as: AsUsername = 'span', className, style, ...props }, ref) => { + const theme = useTheme(); + const isStationery = isStationeryTheme(theme); + const userColor = + typeof (style as CSSProperties | undefined)?.color === 'string' + ? ((style as CSSProperties).color as string) + : undefined; - const safeStyle = useMemo((): CSSProperties | undefined => { - if (!isStationery) return style as CSSProperties | undefined; - return { - ...(style as CSSProperties | undefined), - // Name in ink; keep their color as an accent underline - color: STATIONERY_NAME_INK, - ...(userColor - ? { ['--username-accent' as string]: userColor, textDecorationColor: userColor } - : null), - }; - }, [style, isStationery, userColor]); + const safeStyle = useMemo((): CSSProperties | undefined => { + if (!isStationery) return style as CSSProperties | undefined; + return { + ...(style as CSSProperties | undefined), + // Name in ink; keep their color as an accent underline + color: STATIONERY_NAME_INK, + ...(userColor + ? { ['--username-accent' as string]: userColor, textDecorationColor: userColor } + : null), + }; + }, [style, isStationery, userColor]); - return ( - - ); -}); + return ( + + ); + }, +); export const UsernameBold = as<'b'>(({ as: AsUsernameBold = 'b', className, ...props }, ref) => ( @@ -77,5 +82,5 @@ export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice? {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/message/layout/Bubble.tsx b/src/app/components/message/layout/Bubble.tsx index 93ff84bc..965d7971 100644 --- a/src/app/components/message/layout/Bubble.tsx +++ b/src/app/components/message/layout/Bubble.tsx @@ -59,5 +59,5 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>( )} - ) + ), ); diff --git a/src/app/components/message/layout/Compact.tsx b/src/app/components/message/layout/Compact.tsx index a033919f..83522ae4 100644 --- a/src/app/components/message/layout/Compact.tsx +++ b/src/app/components/message/layout/Compact.tsx @@ -14,5 +14,5 @@ export const CompactLayout = as<'div', CompactLayoutProps>( {children} - ) + ), ); diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index c920f9ac..b0003825 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -1,7 +1,7 @@ import { createVar, globalStyle, keyframes, style, styleVariants } from '@vanilla-extract/css'; -import * as htmlCss from '../../../styles/CustomHtml.css'; import { recipe, RecipeVariants } from '@vanilla-extract/recipes'; import { DefaultReset, color, config, toRem } from 'folds'; +import * as htmlCss from '../../../styles/CustomHtml.css'; export const StickySection = style({ position: 'sticky', diff --git a/src/app/components/message/placeholder/CompactPlaceholder.tsx b/src/app/components/message/placeholder/CompactPlaceholder.tsx index e6168ae3..5abd24be 100644 --- a/src/app/components/message/placeholder/CompactPlaceholder.tsx +++ b/src/app/components/message/placeholder/CompactPlaceholder.tsx @@ -23,5 +23,5 @@ export const CompactPlaceholder = as<'div', { variant?: ContainerColor }>( ); - } + }, ); diff --git a/src/app/components/message/placeholder/DefaultPlaceholder.tsx b/src/app/components/message/placeholder/DefaultPlaceholder.tsx index 725ac4b9..7b3e8c6e 100644 --- a/src/app/components/message/placeholder/DefaultPlaceholder.tsx +++ b/src/app/components/message/placeholder/DefaultPlaceholder.tsx @@ -35,5 +35,5 @@ export const DefaultPlaceholder = as<'div', { variant?: ContainerColor }>( ); - } + }, ); diff --git a/src/app/components/message/placeholder/LinePlaceholder.tsx b/src/app/components/message/placeholder/LinePlaceholder.tsx index 58fc52c0..521df0e0 100644 --- a/src/app/components/message/placeholder/LinePlaceholder.tsx +++ b/src/app/components/message/placeholder/LinePlaceholder.tsx @@ -11,5 +11,5 @@ export const LinePlaceholder = as<'div', css.LinePlaceholderVariants>( {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/nav/NavCategoryHeader.tsx b/src/app/components/nav/NavCategoryHeader.tsx index e6ae700a..d1118426 100644 --- a/src/app/components/nav/NavCategoryHeader.tsx +++ b/src/app/components/nav/NavCategoryHeader.tsx @@ -15,5 +15,5 @@ export const NavCategoryHeader = as<'div', NavCategoryHeaderProps>( {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/nav/NavItem.tsx b/src/app/components/nav/NavItem.tsx index 7a12d438..04c4b1ec 100644 --- a/src/app/components/nav/NavItem.tsx +++ b/src/app/components/nav/NavItem.tsx @@ -24,11 +24,11 @@ export const NavItem = as< export const NavLink = forwardRef>( ({ className, ...props }, ref) => ( - ) + ), ); export const NavButton = as<'button'>( ({ as: AsNavButton = 'button', className, ...props }, ref) => ( - ) + ), ); diff --git a/src/app/components/nav/NavItemContent.tsx b/src/app/components/nav/NavItemContent.tsx index d835dfe2..adb850dd 100644 --- a/src/app/components/nav/NavItemContent.tsx +++ b/src/app/components/nav/NavItemContent.tsx @@ -6,5 +6,5 @@ import * as css from './styles.css'; export const NavItemContent = as<'span', ComponentProps>( ({ className, ...props }, ref) => ( - ) + ), ); diff --git a/src/app/components/nav/NavItemOptions.tsx b/src/app/components/nav/NavItemOptions.tsx index 1c2ffd3f..10b6f6ac 100644 --- a/src/app/components/nav/NavItemOptions.tsx +++ b/src/app/components/nav/NavItemOptions.tsx @@ -13,5 +13,5 @@ export const NavItemOptions = as<'div', ComponentProps>( {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/page/Page.tsx b/src/app/components/page/Page.tsx index 56287d9b..0b37226e 100644 --- a/src/app/components/page/Page.tsx +++ b/src/app/components/page/Page.tsx @@ -65,7 +65,7 @@ export const PageNavHeader = as<'header', css.PageNavHeaderVariants>( {...props} ref={ref} /> - ) + ), ); export function PageNavContent({ @@ -118,7 +118,7 @@ export const PageHeader = as<'div', css.PageHeaderVariants>( {...props} ref={ref} /> - ) + ), ); export const PageContent = as<'div'>(({ className, ...props }, ref) => ( @@ -147,7 +147,7 @@ export const PageHeroSection = as<'div', ComponentProps>( {...props} ref={ref} /> - ) + ), ); export function PageHero({ diff --git a/src/app/components/password-input/PasswordInput.tsx b/src/app/components/password-input/PasswordInput.tsx index 44c2e08d..e14607ca 100644 --- a/src/app/components/password-input/PasswordInput.tsx +++ b/src/app/components/password-input/PasswordInput.tsx @@ -42,5 +42,5 @@ export const PasswordInput = forwardRef( )} ); - } + }, ); diff --git a/src/app/components/power/PowerColorBadge.tsx b/src/app/components/power/PowerColorBadge.tsx index 497385b7..d018fe05 100644 --- a/src/app/components/power/PowerColorBadge.tsx +++ b/src/app/components/power/PowerColorBadge.tsx @@ -17,5 +17,5 @@ export const PowerColorBadge = as<'span', PowerColorBadgeProps>( {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/power/PowerSelector.tsx b/src/app/components/power/PowerSelector.tsx index 2b3b48c3..dbb1584e 100644 --- a/src/app/components/power/PowerSelector.tsx +++ b/src/app/components/power/PowerSelector.tsx @@ -46,7 +46,7 @@ export const PowerSelector = forwardRef( - ) + ), ); type PowerSwitcherProps = PowerSelectorProps & { diff --git a/src/app/components/presence/Presence.tsx b/src/app/components/presence/Presence.tsx index fde4439c..75f7c8e8 100644 --- a/src/app/components/presence/Presence.tsx +++ b/src/app/components/presence/Presence.tsx @@ -65,7 +65,10 @@ type AvatarPresenceProps = { badgeBackgroundColor?: string; }; export const AvatarPresence = as<'div', AvatarPresenceProps>( - ({ as: AsAvatarPresence, badge, variant = 'Surface', badgeBackgroundColor, children, ...props }, ref) => ( + ( + { as: AsAvatarPresence, badge, variant = 'Surface', badgeBackgroundColor, children, ...props }, + ref, + ) => ( {children} {badge && ( @@ -77,5 +80,5 @@ export const AvatarPresence = as<'div', AvatarPresenceProps>(
)} - ) + ), ); diff --git a/src/app/components/remove-inaccessible-prompt/RemoveInaccessiblePrompt.tsx b/src/app/components/remove-inaccessible-prompt/RemoveInaccessiblePrompt.tsx index 2b4df784..e6dd6bc9 100644 --- a/src/app/components/remove-inaccessible-prompt/RemoveInaccessiblePrompt.tsx +++ b/src/app/components/remove-inaccessible-prompt/RemoveInaccessiblePrompt.tsx @@ -66,7 +66,7 @@ export type InaccessibleScanResult = { */ export async function collectInaccessibleSpaceChildren( mx: MatrixClient, - rootSpaceId: string + rootSpaceId: string, ): Promise { let hierarchySummaries = new Map(); try { @@ -125,7 +125,7 @@ export async function collectInaccessibleSpaceChildren( async function removeSpaceChildrenSequentially( mx: MatrixClient, children: InaccessibleSpaceChild[], - onProgress?: (current: number, total: number) => void + onProgress?: (current: number, total: number) => void, ): Promise { const total = children.length; @@ -160,7 +160,7 @@ export function RemoveInaccessiblePrompt({ const [scanResult, setScanResult] = useState(null); const [scanState, scan] = useAsyncCallback( - useCallback(async () => collectInaccessibleSpaceChildren(mx, roomId), [mx, roomId]) + useCallback(async () => collectInaccessibleSpaceChildren(mx, roomId), [mx, roomId]), ); const children = scanResult?.inaccessible ?? null; @@ -172,7 +172,7 @@ export function RemoveInaccessiblePrompt({ setProgress({ current, total }); }); setProgress(null); - }, [mx, children]) + }, [mx, children]), ); useEffect(() => { @@ -191,8 +191,12 @@ export function RemoveInaccessiblePrompt({ } }, [removeState, onDone]); - const previewIds = useMemo(() => (children ?? []).slice(0, PREVIEW_LIMIT).map((c) => c.roomId), [children]); - const isScanning = scanState.status === AsyncStatus.Loading || scanState.status === AsyncStatus.Idle; + const previewIds = useMemo( + () => (children ?? []).slice(0, PREVIEW_LIMIT).map((c) => c.roomId), + [children], + ); + const isScanning = + scanState.status === AsyncStatus.Loading || scanState.status === AsyncStatus.Idle; const isRemoving = removeState.status === AsyncStatus.Loading; const count = children?.length ?? 0; diff --git a/src/app/components/room-avatar/RoomAvatar.tsx b/src/app/components/room-avatar/RoomAvatar.tsx index 53060572..b75bef47 100644 --- a/src/app/components/room-avatar/RoomAvatar.tsx +++ b/src/app/components/room-avatar/RoomAvatar.tsx @@ -1,8 +1,15 @@ import { JoinRule } from 'matrix-js-sdk'; import { AvatarFallback, AvatarImage, color } from 'folds'; -import { Icon, Icons } from '../icons'; -import React, { ComponentProps, ReactEventHandler, ReactNode, forwardRef, useEffect, useState } from 'react'; +import React, { + ComponentProps, + ReactEventHandler, + ReactNode, + forwardRef, + useEffect, + useState, +} from 'react'; import { Blurhash } from 'react-blurhash'; +import { Icon, Icons } from '../icons'; import * as css from './RoomAvatar.css'; import { joinRuleToIconSrc } from '../../utils/room'; import colorMXID from '../../../util/colorMXID'; @@ -33,16 +40,17 @@ export function RoomAvatar({ roomId, src, alt, renderFallback }: RoomAvatarProps const dims = getMediaDimensions(src ?? ''); const blobCached = !!src && - (!useAuthentication || - !isAuthenticatedMediaUrl(src) || - !!getCachedAuthenticatedMediaUrl(src)); + (!useAuthentication || !isAuthenticatedMediaUrl(src) || !!getCachedAuthenticatedMediaUrl(src)); const [loaded, setLoaded] = useState(() => isAvatarCached(src) || blobCached); useEffect(() => { if ( authenticatedSrc && (isAvatarCached(src) || - (src && (!useAuthentication || !isAuthenticatedMediaUrl(src) || getCachedAuthenticatedMediaUrl(src)))) + (src && + (!useAuthentication || + !isAuthenticatedMediaUrl(src) || + getCachedAuthenticatedMediaUrl(src)))) ) { setLoaded(true); } diff --git a/src/app/components/room-card/RoomCard.tsx b/src/app/components/room-card/RoomCard.tsx index c51dd337..ea2a2c20 100644 --- a/src/app/components/room-card/RoomCard.tsx +++ b/src/app/components/room-card/RoomCard.tsx @@ -1,9 +1,23 @@ import React, { ReactNode, useCallback, useRef, useState } from 'react'; import { MatrixError, Room } from 'matrix-js-sdk'; -import { Avatar, Badge, Box, Button, Dialog, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, as, color, config } from 'folds'; -import { Icon, Icons } from '../icons'; +import { + Avatar, + Badge, + Box, + Button, + Dialog, + Overlay, + OverlayBackdrop, + OverlayCenter, + Spinner, + Text, + as, + color, + config, +} from 'folds'; import classNames from 'classnames'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../icons'; import * as css from './style.css'; import { RoomAvatar } from '../room-avatar'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; @@ -36,7 +50,7 @@ export function RoomCardGrid({ children }: { children: ReactNode }) { useElementSizeObserver( useCallback(() => gridRef.current, []), - useCallback((width, _, target) => setGridColumnCount(target, getGridColumnCount(width)), []) + useCallback((width, _, target) => setGridColumnCount(target, getGridColumnCount(width)), []), ); return ( @@ -145,7 +159,7 @@ export const RoomCard = as<'div', RoomCardProps>( renderTopicViewer, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -153,7 +167,7 @@ export const RoomCard = as<'div', RoomCardProps>( const joinedRoom = mx.getRoom(joinedRoomId); const createEvent = joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomCreate) : undefined; const [topicEvent, setTopicEvent] = useState(() => - joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomTopic) : undefined + joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomTopic) : undefined, ); const fallbackName = getMxIdLocalPart(roomIdOrAlias) ?? roomIdOrAlias; @@ -180,12 +194,15 @@ export const RoomCard = as<'div', RoomCardProps>( setTopicEvent(getStateEvent(joinedRoom, StateEvent.RoomTopic)); } }, - [joinedRoom] - ) + [joinedRoom], + ), ); const [joinState, join] = useAsyncCallback( - useCallback(() => mx.joinRoom(roomIdOrAlias, { viaServers }), [mx, roomIdOrAlias, viaServers]) + useCallback( + () => mx.joinRoom(roomIdOrAlias, { viaServers }), + [mx, roomIdOrAlias, viaServers], + ), ); const joining = joinState.status === AsyncStatus.Loading || joinState.status === AsyncStatus.Success; @@ -197,7 +214,8 @@ export const RoomCard = as<'div', RoomCardProps>( const [showSpaceJoinPrompt, setShowSpaceJoinPrompt] = useState(false); const isSpace = roomType === RoomType.Space || joinedRoom?.isSpaceRoom(); const isForum = - roomType === RoomType.Forum || createEvent?.getContent<{ type?: string }>().type === RoomType.Forum; + roomType === RoomType.Forum || + createEvent?.getContent<{ type?: string }>().type === RoomType.Forum; const handleJoinClick = () => { if (isSpace) { @@ -334,5 +352,5 @@ export const RoomCard = as<'div', RoomCardProps>( )} ); - } + }, ); diff --git a/src/app/components/room-intro/RoomIntro.tsx b/src/app/components/room-intro/RoomIntro.tsx index ce550992..4719d3a5 100644 --- a/src/app/components/room-intro/RoomIntro.tsx +++ b/src/app/components/room-intro/RoomIntro.tsx @@ -43,7 +43,7 @@ export const RoomIntro = as<'div', RoomIntroProps>(({ room, ...props }, ref) => const prevRoomId = createContent?.predecessor?.room_id; const [prevRoomState, joinPrevRoom] = useAsyncCallback( - useCallback(async (roomId: string) => mx.joinRoom(roomId), [mx]) + useCallback(async (roomId: string) => mx.joinRoom(roomId), [mx]), ); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); diff --git a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx index 1a3646ef..e5321a26 100644 --- a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx +++ b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx @@ -1,8 +1,8 @@ import React from 'react'; import { as, Box, Header, IconButton, Modal, Scroll, Text } from 'folds'; -import { Icon, Icons } from '../icons'; import classNames from 'classnames'; import Linkify from 'linkify-react'; +import { Icon, Icons } from '../icons'; import * as css from './style.css'; import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser'; diff --git a/src/app/components/scroll-top-container/ScrollTopContainer.tsx b/src/app/components/scroll-top-container/ScrollTopContainer.tsx index e91d0580..b68fa672 100644 --- a/src/app/components/scroll-top-container/ScrollTopContainer.tsx +++ b/src/app/components/scroll-top-container/ScrollTopContainer.tsx @@ -27,10 +27,10 @@ export const ScrollTopContainer = as< onVisibilityChange?.(entry.isIntersecting); } }, - [anchorRef, onVisibilityChange] + [anchorRef, onVisibilityChange], ), useCallback(() => ({ root: scrollRef?.current }), [scrollRef]), - useCallback(() => anchorRef.current, [anchorRef]) + useCallback(() => anchorRef.current, [anchorRef]), ); if (onTop) return null; diff --git a/src/app/components/sequence-card/SequenceCard.tsx b/src/app/components/sequence-card/SequenceCard.tsx index d0e77ae6..b8f56ebd 100644 --- a/src/app/components/sequence-card/SequenceCard.tsx +++ b/src/app/components/sequence-card/SequenceCard.tsx @@ -19,19 +19,19 @@ export const SequenceCard = as< outlined, ...props }, - ref + ref, ) => ( - ) + ), ); diff --git a/src/app/components/sidebar/Sidebar.tsx b/src/app/components/sidebar/Sidebar.tsx index 71b6a7b8..4b867851 100644 --- a/src/app/components/sidebar/Sidebar.tsx +++ b/src/app/components/sidebar/Sidebar.tsx @@ -4,10 +4,5 @@ import React from 'react'; import * as css from './Sidebar.css'; export const Sidebar = as<'div'>(({ as: AsSidebar = 'div', className, ...props }, ref) => ( - + )); diff --git a/src/app/components/sidebar/SidebarContent.tsx b/src/app/components/sidebar/SidebarContent.tsx index 6d060d25..ae3d6972 100644 --- a/src/app/components/sidebar/SidebarContent.tsx +++ b/src/app/components/sidebar/SidebarContent.tsx @@ -8,7 +8,12 @@ type SidebarContentProps = { export function SidebarContent({ scrollable, sticky }: SidebarContentProps) { return ( <> - + {scrollable} diff --git a/src/app/components/sidebar/SidebarItem.tsx b/src/app/components/sidebar/SidebarItem.tsx index c7f1414f..87fc3e4a 100644 --- a/src/app/components/sidebar/SidebarItem.tsx +++ b/src/app/components/sidebar/SidebarItem.tsx @@ -11,7 +11,7 @@ export const SidebarItem = as<'div', css.SidebarItemVariants>( {...props} ref={ref} /> - ) + ), ); export const SidebarItemBadge = as<'div', css.SidebarItemBadgeVariants>( @@ -21,7 +21,7 @@ export const SidebarItemBadge = as<'div', css.SidebarItemBadgeVariants>( {...props} ref={ref} /> - ) + ), ); export function SidebarItemTooltip({ @@ -59,7 +59,7 @@ export const SidebarAvatar = as<'div', css.SidebarAvatarVariants & ComponentProp {...props} ref={ref} /> - ) + ), ); export const SidebarFolder = as<'div', css.SidebarFolderVariants>( @@ -70,7 +70,7 @@ export const SidebarFolder = as<'div', css.SidebarFolderVariants>( {...props} ref={ref} /> - ) + ), ); export const SidebarFolderDropTarget = as<'div', css.SidebarFolderDropTargetVariants>( @@ -80,5 +80,5 @@ export const SidebarFolderDropTarget = as<'div', css.SidebarFolderDropTargetVari {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/components/sidebar/SidebarStack.tsx b/src/app/components/sidebar/SidebarStack.tsx index c0e976c8..253d7cc1 100644 --- a/src/app/components/sidebar/SidebarStack.tsx +++ b/src/app/components/sidebar/SidebarStack.tsx @@ -6,5 +6,5 @@ import * as css from './Sidebar.css'; export const SidebarStack = as<'div'>( ({ as: AsSidebarStack = 'div', className, ...props }, ref) => ( - ) + ), ); diff --git a/src/app/components/speech-bubble/SpeechBubble.css.ts b/src/app/components/speech-bubble/SpeechBubble.css.ts index af80af1c..d42730cd 100644 --- a/src/app/components/speech-bubble/SpeechBubble.css.ts +++ b/src/app/components/speech-bubble/SpeechBubble.css.ts @@ -57,4 +57,3 @@ globalStyle(`${SpeechBubbleMenu} > *`, { border: 'none', boxShadow: 'none', }); - diff --git a/src/app/components/speech-bubble/SpeechBubble.tsx b/src/app/components/speech-bubble/SpeechBubble.tsx index bc56d196..b0316280 100644 --- a/src/app/components/speech-bubble/SpeechBubble.tsx +++ b/src/app/components/speech-bubble/SpeechBubble.tsx @@ -28,8 +28,12 @@ export function SpeechBubble({
); } - diff --git a/src/app/components/text-viewer/TextViewer.tsx b/src/app/components/text-viewer/TextViewer.tsx index 702e1ec6..0af3175a 100644 --- a/src/app/components/text-viewer/TextViewer.tsx +++ b/src/app/components/text-viewer/TextViewer.tsx @@ -1,9 +1,8 @@ -/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */ import React, { ComponentProps, HTMLAttributes, Suspense, forwardRef, lazy } from 'react'; import classNames from 'classnames'; import { Box, Chip, Header, IconButton, Scroll, Text, as } from 'folds'; -import { Icon, Icons } from '../icons'; import { ErrorBoundary } from 'react-error-boundary'; +import { Icon, Icons } from '../icons'; import * as css from './TextViewer.css'; import { copyToClipboard } from '../../utils/dom'; @@ -29,7 +28,7 @@ export const TextViewerContent = forwardRef - ) + ), ); export type TextViewerProps = { @@ -84,5 +83,5 @@ export const TextViewer = as<'div', TextViewerProps>( ); - } + }, ); diff --git a/src/app/components/time-date/DatePicker.tsx b/src/app/components/time-date/DatePicker.tsx index faa43a3f..d822a559 100644 --- a/src/app/components/time-date/DatePicker.tsx +++ b/src/app/components/time-date/DatePicker.tsx @@ -125,5 +125,5 @@ export const DatePicker = forwardRef( ); - } + }, ); diff --git a/src/app/components/time-date/TimePicker.tsx b/src/app/components/time-date/TimePicker.tsx index c835ed09..399c996f 100644 --- a/src/app/components/time-date/TimePicker.tsx +++ b/src/app/components/time-date/TimePicker.tsx @@ -149,5 +149,5 @@ export const TimePicker = forwardRef( ); - } + }, ); diff --git a/src/app/components/title-bar/TitleBar.tsx b/src/app/components/title-bar/TitleBar.tsx index 75bab3a9..851ceb6b 100644 --- a/src/app/components/title-bar/TitleBar.tsx +++ b/src/app/components/title-bar/TitleBar.tsx @@ -1,14 +1,27 @@ import React, { ReactNode, useMemo, useEffect, useState, useCallback, useRef } from 'react'; import { Box, Text, IconButton } from 'folds'; import { invoke } from '@tauri-apps/api/core'; -import { MatrixClient, RoomEvent, ClientEvent, MatrixEvent, Room, IPushRules, SyncState } from 'matrix-js-sdk'; +import { + MatrixClient, + RoomEvent, + ClientEvent, + MatrixEvent, + Room, + IPushRules, + SyncState, +} from 'matrix-js-sdk'; import { useAtomValue } from 'jotai'; import { useNavigate } from 'react-router-dom'; import { WindowControls } from './WindowControls'; import { UpdateNotification } from '../update-notification'; import * as css from './TitleBar.css'; -import { getUnreadInfos, getOrphanParents, guessPerfectParent, getAllParents } from '../../utils/room'; -import { getCanonicalAliasOrRoomId, getMxIdLocalPart } from '../../utils/matrix'; +import { + getUnreadInfos, + getOrphanParents, + guessPerfectParent, + getAllParents, +} from '../../utils/room'; +import { getCanonicalAliasOrRoomId, getMxIdLocalPart, isRoomId } from '../../utils/matrix'; import { activeRoomIdAtom } from '../../state/activeRoom'; import { roomToParentsAtom } from '../../state/room/roomToParents'; import { mDirectAtom } from '../../state/mDirectList'; @@ -16,7 +29,6 @@ import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '../../page import { RoomNotificationMode } from '../../hooks/useRoomsNotificationPreferences'; import { AccountDataEvent } from '../../../types/matrix/accountData'; import { getNotificationMode, NotificationMode } from '../../hooks/useNotificationMode'; -import { isRoomId } from '../../utils/matrix'; import { useSyncState } from '../../hooks/useSyncState'; import { useBackRoute } from '../../hooks/useBackRoute'; import { Icon, Icons } from '../icons'; @@ -65,7 +77,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { } return { current, previous }; }); - }, []) + }, []), ); // Notification-related state - only populated when mx is available @@ -99,7 +111,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { // We can't use hooks here, so we'll fetch the data directly const userId = mx.getUserId(); - + // Get push rules for keywords const pushRulesEvt = mx.getAccountData(AccountDataEvent.PushRules); const pushRules = pushRulesEvt?.getContent() ?? { global: {} }; @@ -125,14 +137,14 @@ export function TitleBar({ mx, children }: TitleBarProps) { preferences.mute.add(rule.rule_id); } }); - + // Check room rules for special messages (OFF mode = mentions only) room.forEach((rule: any) => { if (getNotificationMode(rule.actions) === NotificationMode.OFF) { preferences.specialMessages.add(rule.rule_id); } }); - + // Check room rules for all messages (Notify or NotifyLoud mode) room.forEach((rule: any) => { if (getNotificationMode(rule.actions) !== NotificationMode.OFF) { @@ -160,56 +172,63 @@ export function TitleBar({ mx, children }: TitleBarProps) { }, [mx]); // Check if message should trigger a notification for SpecialMessages mode - const shouldNotifySpecialMessage = useCallback((event: MatrixEvent): boolean => { - if (!notificationData.userId) return false; - - const content = event.getContent(); - const body = content.body?.toLowerCase() || ''; - - // Check for user mentions in m.mentions - const mentions = content['m.mentions']; - if (mentions?.user_ids?.includes(notificationData.userId)) { - return true; - } - - // Check for @room mention - if (mentions?.room === true) { - return true; - } - - // Check if body contains @room - if (body.includes('@room')) { - return true; - } - - // Check if body contains user's display name - if (notificationData.displayName && body.includes(notificationData.displayName.toLowerCase())) { - return true; - } - - // Check if body contains user's username/localpart - const username = getMxIdLocalPart(notificationData.userId); - if (username && body.includes(username.toLowerCase())) { - return true; - } - - // Check if body contains any of the user's keywords - for (const keyword of notificationData.keywordPatterns) { - if (body.includes(keyword.toLowerCase())) { + const shouldNotifySpecialMessage = useCallback( + (event: MatrixEvent): boolean => { + if (!notificationData.userId) return false; + + const content = event.getContent(); + const body = content.body?.toLowerCase() || ''; + + // Check for user mentions in m.mentions + const mentions = content['m.mentions']; + if (mentions?.user_ids?.includes(notificationData.userId)) { return true; } - } - - return false; - }, [notificationData]); + + // Check for @room mention + if (mentions?.room === true) { + return true; + } + + // Check if body contains @room + if (body.includes('@room')) { + return true; + } + + // Check if body contains user's display name + if ( + notificationData.displayName && + body.includes(notificationData.displayName.toLowerCase()) + ) { + return true; + } + + // Check if body contains user's username/localpart + const username = getMxIdLocalPart(notificationData.userId); + if (username && body.includes(username.toLowerCase())) { + return true; + } + + // Check if body contains any of the user's keywords + for (const keyword of notificationData.keywordPatterns) { + if (body.includes(keyword.toLowerCase())) { + return true; + } + } + + return false; + }, + [notificationData], + ); // Clear all dismiss timers on unmount - useEffect(() => { - return () => { - dismissTimersRef.current.forEach(timer => clearTimeout(timer)); + useEffect( + () => () => { + dismissTimersRef.current.forEach((timer) => clearTimeout(timer)); dismissTimersRef.current.clear(); - }; - }, []); + }, + [], + ); // Auto-dismiss notification after 10 seconds const scheduleDismiss = useCallback((notificationId: string) => { @@ -218,113 +237,117 @@ export function TitleBar({ mx, children }: TitleBarProps) { if (existingTimer) { clearTimeout(existingTimer); } - + // Schedule new dismiss timer const timer = setTimeout(() => { - setNotifications(prev => - prev.map(n => n.id === notificationId ? { ...n, exiting: true } : n) + setNotifications((prev) => + prev.map((n) => (n.id === notificationId ? { ...n, exiting: true } : n)), ); setTimeout(() => { - setNotifications(prev => prev.filter(n => n.id !== notificationId)); + setNotifications((prev) => prev.filter((n) => n.id !== notificationId)); dismissTimersRef.current.delete(notificationId); }, 200); // Wait for exit animation }, 10000); - + dismissTimersRef.current.set(notificationId, timer); }, []); // Navigate to the new message - const handleNotificationClick = useCallback((notification: NewMessageNotification) => (e: React.MouseEvent) => { - e.stopPropagation(); - e.preventDefault(); - - if (!mx) return; + const handleNotificationClick = useCallback( + (notification: NewMessageNotification) => (e: React.MouseEvent) => { + e.stopPropagation(); + e.preventDefault(); - const targetRoomId = notification.roomId; - const eventId = notification.eventId; + if (!mx) return; - // Dismiss this notification - const timer = dismissTimersRef.current.get(notification.id); - if (timer) { - clearTimeout(timer); - dismissTimersRef.current.delete(notification.id); - } - - setNotifications(prev => - prev.map(n => n.id === notification.id ? { ...n, exiting: true } : n) - ); - setTimeout(() => { - setNotifications(prev => prev.filter(n => n.id !== notification.id)); - }, 200); + const targetRoomId = notification.roomId; + const { eventId } = notification; - // Simple navigation approach - just try all paths - try { - const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, targetRoomId); - - // Check if it's a direct message - if (mDirects.has(targetRoomId)) { - const path = getDirectRoomPath(roomIdOrAlias, eventId); - console.log('Navigating to direct room:', path); - navigate(path); - return; + // Dismiss this notification + const timer = dismissTimersRef.current.get(notification.id); + if (timer) { + clearTimeout(timer); + dismissTimersRef.current.delete(notification.id); } - // Check if it belongs to a space - const orphanParents = getOrphanParents(roomToParents, targetRoomId); - if (orphanParents.length > 0) { - const parentSpace = guessPerfectParent(mx, targetRoomId, orphanParents) ?? orphanParents[0]; - const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace); - const path = getSpaceRoomPath(pSpaceIdOrAlias, roomIdOrAlias, eventId); - console.log('Navigating to space room:', path); - navigate(path); - return; - } + setNotifications((prev) => + prev.map((n) => (n.id === notification.id ? { ...n, exiting: true } : n)), + ); + setTimeout(() => { + setNotifications((prev) => prev.filter((n) => n.id !== notification.id)); + }, 200); - // Default to home room - const path = getHomeRoomPath(roomIdOrAlias, eventId); - console.log('Navigating to home room:', path); - navigate(path); - } catch (error) { - console.error('Error navigating to room:', error); - // Last resort - navigate without event ID + // Simple navigation approach - just try all paths try { const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, targetRoomId); - navigate(getHomeRoomPath(roomIdOrAlias)); - } catch (fallbackError) { - console.error('Fallback navigation also failed:', fallbackError); + + // Check if it's a direct message + if (mDirects.has(targetRoomId)) { + const path = getDirectRoomPath(roomIdOrAlias, eventId); + console.log('Navigating to direct room:', path); + navigate(path); + return; + } + + // Check if it belongs to a space + const orphanParents = getOrphanParents(roomToParents, targetRoomId); + if (orphanParents.length > 0) { + const parentSpace = + guessPerfectParent(mx, targetRoomId, orphanParents) ?? orphanParents[0]; + const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace); + const path = getSpaceRoomPath(pSpaceIdOrAlias, roomIdOrAlias, eventId); + console.log('Navigating to space room:', path); + navigate(path); + return; + } + + // Default to home room + const path = getHomeRoomPath(roomIdOrAlias, eventId); + console.log('Navigating to home room:', path); + navigate(path); + } catch (error) { + console.error('Error navigating to room:', error); + // Last resort - navigate without event ID + try { + const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, targetRoomId); + navigate(getHomeRoomPath(roomIdOrAlias)); + } catch (fallbackError) { + console.error('Fallback navigation also failed:', fallbackError); + } } - } - }, [mx, roomToParents, mDirects, navigate]); + }, + [mx, roomToParents, mDirects, navigate], + ); // Subscribe to room changes for unread updates and new messages useEffect(() => { if (!mx) return; - const update = () => setUpdateCounter(c => c + 1); + const update = () => setUpdateCounter((c) => c + 1); const handleTimelineEvent = (event: MatrixEvent, room: Room | undefined) => { update(); - + // Check if this is a new message we should notify about if (!room || !event) return; - + // Ignore if it's the currently active room if (room.roomId === roomId) { return; } - + // Ignore if it's our own message if (event.getSender() === mx.getUserId()) { console.log('[TitleBar] Skipping: own message'); return; } - + // Only notify for actual messages if (event.getType() !== 'm.room.message') { console.log('[TitleBar] Skipping: not a message event, type:', event.getType()); return; } - + // Only show for recent messages (within 15 seconds) to avoid showing notifications // for old messages when loading history const eventTime = event.getTs(); @@ -333,25 +356,31 @@ export function TitleBar({ mx, children }: TitleBarProps) { console.log('[TitleBar] Skipping: message too old', (now - eventTime) / 1000, 'seconds'); return; // More than 15 seconds old } - + // Only show for unread messages - check if event is after the last read receipt const readUpToEventId = room.getEventReadUpTo(mx.getUserId() ?? ''); if (readUpToEventId) { const timeline = room.getLiveTimeline().getEvents(); - const readUpToIndex = timeline.findIndex(e => e.getId() === readUpToEventId); - const eventIndex = timeline.findIndex(e => e.getId() === event.getId()); - + const readUpToIndex = timeline.findIndex((e) => e.getId() === readUpToEventId); + const eventIndex = timeline.findIndex((e) => e.getId() === event.getId()); + // If we found both events and the new event is not after the read marker, skip it if (readUpToIndex !== -1 && eventIndex !== -1 && eventIndex <= readUpToIndex) { - console.log('[TitleBar] Skipping: already read (eventIndex:', eventIndex, ', readUpToIndex:', readUpToIndex, ')'); + console.log( + '[TitleBar] Skipping: already read (eventIndex:', + eventIndex, + ', readUpToIndex:', + readUpToIndex, + ')', + ); return; } } - + // Determine notification mode for this room const roomIdStr = room.roomId; let notificationMode: RoomNotificationMode; - + if (notificationData.preferences.mute.has(roomIdStr)) { notificationMode = RoomNotificationMode.Mute; } else if (notificationData.preferences.specialMessages.has(roomIdStr)) { @@ -361,7 +390,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { } else { notificationMode = RoomNotificationMode.Unset; } - + // Debug logging console.log('[TitleBar Notification]', { roomId: roomIdStr, @@ -374,17 +403,18 @@ export function TitleBar({ mx, children }: TitleBarProps) { allMessages: notificationData.preferences.allMessages.has(roomIdStr), }, }); - + // Never show for muted rooms if (notificationMode === RoomNotificationMode.Mute) return; - + // DMs with Unset mode should notify for all messages (underride rule behavior) const isDM = mDirects.has(roomIdStr); - const treatAsAllMessages = notificationMode === RoomNotificationMode.AllMessages || - (notificationMode === RoomNotificationMode.Unset && isDM); - + const treatAsAllMessages = + notificationMode === RoomNotificationMode.AllMessages || + (notificationMode === RoomNotificationMode.Unset && isDM); + console.log('[TitleBar] treatAsAllMessages:', treatAsAllMessages, 'isDM:', isDM); - + // For SpecialMessages mode, only show if message would trigger a notification // For Unset mode (non-DM), also check for special messages if (!treatAsAllMessages && notificationMode === RoomNotificationMode.SpecialMessages) { @@ -397,29 +427,28 @@ export function TitleBar({ mx, children }: TitleBarProps) { console.log('[TitleBar] Unset mode (non-DM) check:', shouldNotify); if (!shouldNotify) return; } - + console.log('[TitleBar] Passed all checks, showing notification bubble'); - + // For AllMessages mode, show all messages (no additional check needed) - + // Get content const content = event.getContent(); if (!content.body) return; - + // Get sender display name const sender = room.getMember(event.getSender() || ''); const senderName = sender?.name || event.getSender() || 'Unknown'; - + // Create preview (truncate if needed) - const preview = content.body.length > 30 - ? content.body.substring(0, 30) + '...' - : content.body; - + const preview = + content.body.length > 30 ? `${content.body.substring(0, 30)}...` : content.body; + // Generate unique ID for this notification const notificationId = `${room.roomId}-${event.getId()}-${Date.now()}`; - + // Add to notifications array (limit to 4 notifications) - setNotifications(prev => { + setNotifications((prev) => { const newNotification: NewMessageNotification = { id: notificationId, roomId: room.roomId, @@ -427,19 +456,19 @@ export function TitleBar({ mx, children }: TitleBarProps) { senderName, preview, }; - + // Remove oldest if we already have 4 const updated = prev.length >= 4 ? prev.slice(1) : prev; return [...updated, newNotification]; }); - + scheduleDismiss(notificationId); }; mx.on(RoomEvent.Timeline, handleTimelineEvent); mx.on(RoomEvent.Receipt, update); mx.on(ClientEvent.Room, update); - + return () => { mx.off(RoomEvent.Timeline, handleTimelineEvent); mx.off(RoomEvent.Receipt, update); @@ -454,20 +483,20 @@ export function TitleBar({ mx, children }: TitleBarProps) { const handleReceipt = (event: MatrixEvent, room: Room) => { const myUserId = mx.getUserId(); if (!myUserId) return; - + const content = event.getContent(); const isMyReceipt = Object.keys(content).find((eventId) => (Object.keys(content[eventId]) as any[]).find( - (receiptType) => content[eventId][receiptType][myUserId] - ) + (receiptType) => content[eventId][receiptType][myUserId], + ), ); - + // If this is my receipt, clear all notifications for this room if (isMyReceipt) { - setNotifications(prev => { - const updated = prev.filter(n => n.roomId !== room.roomId); + setNotifications((prev) => { + const updated = prev.filter((n) => n.roomId !== room.roomId); // Clear timers for removed notifications - prev.forEach(n => { + prev.forEach((n) => { if (n.roomId === room.roomId) { const timer = dismissTimersRef.current.get(n.id); if (timer) { @@ -490,11 +519,11 @@ export function TitleBar({ mx, children }: TitleBarProps) { // Clear notifications for the active room when it changes useEffect(() => { if (!roomId) return; - - setNotifications(prev => { - const updated = prev.filter(n => n.roomId !== roomId); + + setNotifications((prev) => { + const updated = prev.filter((n) => n.roomId !== roomId); // Clear timers for removed notifications - prev.forEach(n => { + prev.forEach((n) => { if (n.roomId === roomId) { const timer = dismissTimersRef.current.get(n.id); if (timer) { @@ -510,25 +539,25 @@ export function TitleBar({ mx, children }: TitleBarProps) { // Build breadcrumb path for room (Space > Subspace > RoomName) const breadcrumbPath = useMemo(() => { if (!mx || !roomId) return null; - + const room = mx.getRoom(roomId); if (!room) return null; - + const roomName = room.name; if (!roomName) return null; - + // DMs just show the room name without hierarchy if (mDirects.has(roomId)) { return roomName; } - + // Get the parent chain const directParents = roomToParents.get(roomId); if (!directParents || directParents.size === 0) { // No parents, just the room name return roomName; } - + // Build the parent chain recursively // This returns the chain of parent names ABOVE the given roomId, not including roomId itself const buildParentChain = (currentRoomId: string): string[] => { @@ -537,17 +566,17 @@ export function TitleBar({ mx, children }: TitleBarProps) { // No parents above this room return []; } - + // Pick the best parent (or first if only one) const parentsList = Array.from(parents); let chosenParent: string; - + if (parentsList.length === 1) { chosenParent = parentsList[0]; } else { // Use heuristic to pick best parent // Prefer a parent that is itself a top-level space (orphan) - const orphanParents = parentsList.filter(p => !roomToParents.has(p)); + const orphanParents = parentsList.filter((p) => !roomToParents.has(p)); if (orphanParents.length > 0) { // Use guessPerfectParent if available, otherwise just pick first orphan chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0]; @@ -556,23 +585,23 @@ export function TitleBar({ mx, children }: TitleBarProps) { chosenParent = parentsList[0]; } } - + // Get the parent's name const parentRoom = mx.getRoom(chosenParent); if (!parentRoom?.name) return []; - + // Get the chain above the parent const upperChain = buildParentChain(chosenParent); - + // Return the upper chain plus this parent return [...upperChain, parentRoom.name]; }; - + const parentChain = buildParentChain(roomId); const path = [...parentChain, roomName]; - + return path.join(' > '); - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps }, [mx, roomId, roomToParents, mDirects, updateCounter]); // Get room name (for backward compatibility, keeping simple name too) @@ -580,7 +609,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { if (!mx || !roomId) return null; const room = mx.getRoom(roomId); return room?.name || null; - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps }, [mx, roomId, updateCounter]); // Get total unread count @@ -588,7 +617,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { if (!mx) return 0; const unreadInfos = getUnreadInfos(mx); return unreadInfos.reduce((sum, info) => sum + info.total, 0); - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps }, [mx, updateCounter]); // Build title parts @@ -626,21 +655,15 @@ export function TitleBar({ mx, children }: TitleBarProps) { syncStateData.previous !== SyncState.Syncing ) { syncStatusBadge = ( -
- Connecting... -
+
Connecting...
); } else if (syncStateData.current === SyncState.Reconnecting) { syncStatusBadge = ( -
- Reconnecting... -
+
Reconnecting...
); } else if (syncStateData.current === SyncState.Error) { syncStatusBadge = ( -
- Connection Lost -
+
Connection Lost
); } } @@ -648,7 +671,7 @@ export function TitleBar({ mx, children }: TitleBarProps) { return ( {syncStatusBadge} - )} - Paarrot{titleParts.suffix} + Paarrot + {titleParts.suffix} {notifications.map((notification) => ( -
e.stopPropagation()} title={`${notification.senderName}: ${notification.preview}`} > - {notification.senderName}: {notification.preview} + + {notification.senderName}: {notification.preview} +
))} {children} diff --git a/src/app/components/title-bar/WindowControls.css.ts b/src/app/components/title-bar/WindowControls.css.ts index c07f3e11..094be2be 100644 --- a/src/app/components/title-bar/WindowControls.css.ts +++ b/src/app/components/title-bar/WindowControls.css.ts @@ -22,24 +22,27 @@ export const WindowButton = style({ cursor: 'pointer', transition: 'background-color 0.1s ease', outline: 'none', - + ':hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)', }, - + ':active': { backgroundColor: 'rgba(255, 255, 255, 0.05)', }, }); -export const WindowButtonClose = style([WindowButton, { - ':hover': { - backgroundColor: '#e81123', - color: '#ffffff', +export const WindowButtonClose = style([ + WindowButton, + { + ':hover': { + backgroundColor: '#e81123', + color: '#ffffff', + }, + + ':active': { + backgroundColor: '#c50f1f', + color: '#ffffff', + }, }, - - ':active': { - backgroundColor: '#c50f1f', - color: '#ffffff', - }, -}]); +]); diff --git a/src/app/components/title-bar/WindowControls.tsx b/src/app/components/title-bar/WindowControls.tsx index 6fe2b397..3d8bf5e1 100644 --- a/src/app/components/title-bar/WindowControls.tsx +++ b/src/app/components/title-bar/WindowControls.tsx @@ -1,7 +1,7 @@ import React, { useState, useEffect } from 'react'; import { Box, IconButton } from 'folds'; -import { Icon } from '../icons'; import { invoke } from '@tauri-apps/api/core'; +import { Icon } from '../icons'; import * as css from './WindowControls.css'; export function WindowControls() { @@ -56,7 +56,7 @@ export function WindowControls() { return ( - - - - -
, - document.body + document.body, ); } diff --git a/src/app/components/updates-dialog/UpdatesDialogHost.tsx b/src/app/components/updates-dialog/UpdatesDialogHost.tsx index 8db2c914..11e375c4 100644 --- a/src/app/components/updates-dialog/UpdatesDialogHost.tsx +++ b/src/app/components/updates-dialog/UpdatesDialogHost.tsx @@ -60,7 +60,7 @@ export function UpdatesDialogHost() { // Persist updater metadata when a download finishes (version tracking after restart). useEffect(() => { - const electron = window.electron; + const { electron } = window; if (!electron?.updater?.onUpdateDownloaded) return undefined; const onDownloaded = (info: UpdaterInfo) => { diff --git a/src/app/components/upload-board/UploadBoard.tsx b/src/app/components/upload-board/UploadBoard.tsx index 7458db2f..5587a9a8 100644 --- a/src/app/components/upload-board/UploadBoard.tsx +++ b/src/app/components/upload-board/UploadBoard.tsx @@ -1,8 +1,8 @@ import React, { MutableRefObject, ReactNode, useImperativeHandle, useRef } from 'react'; import { Badge, Box, Chip, Header, Spinner, Text, as, percent } from 'folds'; -import { Icon, Icons } from '../icons'; import classNames from 'classnames'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../icons'; import * as css from './UploadBoard.css'; import { TUploadFamilyObserverAtom, Upload, UploadStatus, UploadSuccess } from '../../state/upload'; @@ -60,14 +60,14 @@ export function UploadBoardHeader({ } return acc; }, - { loaded: 0, total: 0 } + { loaded: 0, total: 0 }, ); const handleSend = async () => { if (sendingRef.current) return; sendingRef.current = true; await onSend( - uploads.filter((upload) => upload.status === UploadStatus.Success) as UploadSuccess[] + uploads.filter((upload) => upload.status === UploadStatus.Success) as UploadSuccess[], ); sendingRef.current = false; }; diff --git a/src/app/components/upload-card/UploadCard.tsx b/src/app/components/upload-card/UploadCard.tsx index e0d0b8b8..9b83b70b 100644 --- a/src/app/components/upload-card/UploadCard.tsx +++ b/src/app/components/upload-card/UploadCard.tsx @@ -1,6 +1,6 @@ import { Badge, Box, ProgressBar, Text, percent } from 'folds'; -import { Icon, Icons } from '../icons'; import React, { ReactNode, forwardRef } from 'react'; +import { Icon, Icons } from '../icons'; import * as css from './UploadCard.css'; import { bytesToSize } from '../../utils/common'; @@ -29,7 +29,7 @@ export const UploadCard = forwardRef {bottom}
- ) + ), ); type UploadCardProgressProps = { diff --git a/src/app/components/url-preview/GiphyEmbed.tsx b/src/app/components/url-preview/GiphyEmbed.tsx index ddb6fcb1..0dd2d263 100644 --- a/src/app/components/url-preview/GiphyEmbed.tsx +++ b/src/app/components/url-preview/GiphyEmbed.tsx @@ -51,14 +51,7 @@ export const GiphyEmbed = as<'div', GiphyEmbedProps>(({ url, ...props }, ref) => return (
-
); }); diff --git a/src/app/components/url-preview/TikTokEmbed.tsx b/src/app/components/url-preview/TikTokEmbed.tsx index e691f0d9..d102d507 100644 --- a/src/app/components/url-preview/TikTokEmbed.tsx +++ b/src/app/components/url-preview/TikTokEmbed.tsx @@ -62,7 +62,7 @@ async function fetchTikTokOEmbed(url: string): Promise<{ videoId: string | null; } | null> { try { - const electron = (window as any).electron; + const { electron } = window as any; let data; if (electron?.tiktok?.getOEmbed) { data = await electron.tiktok.getOEmbed(url); diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx index 18a0e86e..b2b32e53 100644 --- a/src/app/components/url-preview/UrlPreviewCard.tsx +++ b/src/app/components/url-preview/UrlPreviewCard.tsx @@ -22,7 +22,7 @@ const linkStyles = { color: color.Success.Main }; * Click handler for external links - uses Tauri shell on desktop/mobile */ const handleExternalLinkClick = (e: MouseEvent) => { - const href = e.currentTarget.href; + const { href } = e.currentTarget; if (href && (href.startsWith('http://') || href.startsWith('https://'))) { e.preventDefault(); openExternalUrl(href); @@ -32,21 +32,21 @@ const handleExternalLinkClick = (e: MouseEvent) => { /** * Preview image component with authentication support */ -const AuthenticatedUrlPreviewImg = ({ +function AuthenticatedUrlPreviewImg({ src, useAuthentication, ...props -}: React.ComponentProps & { useAuthentication: boolean }) => { +}: React.ComponentProps & { useAuthentication: boolean }) { const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication); return ; -}; +} export const UrlPreviewCard = as<'div', { url: string; ts: number }>( ({ url, ts, ...props }, ref) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [previewStatus, loadPreview] = useAsyncCallback( - useCallback(() => mx.getUrlPreview(url, ts), [url, ts, mx]) + useCallback(() => mx.getUrlPreview(url, ts), [url, ts, mx]), ); useEffect(() => { @@ -74,8 +74,7 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number }>( // SVGs can't be thumbnailed by Matrix servers, load them directly // Also check og:image:type if available const isSvg = - ogImage.toLowerCase().endsWith('.svg') || - prev['og:image:type'] === 'image/svg+xml'; + ogImage.toLowerCase().endsWith('.svg') || prev['og:image:type'] === 'image/svg+xml'; const imgUrl = isSvg ? mxcUrlToHttp(mx, ogImage, useAuthentication) : mxcUrlToHttp(mx, ogImage, useAuthentication, 256, 256, 'scale', false); @@ -128,7 +127,7 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number }>( )} ); - } + }, ); export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => { @@ -156,8 +155,8 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => { root: scrollRef.current, rootMargin: '10px', }), - [] - ) + [], + ), ); useEffect(() => { diff --git a/src/app/components/url-preview/YouTubeEmbed.tsx b/src/app/components/url-preview/YouTubeEmbed.tsx index 67613bcb..13cbec1f 100644 --- a/src/app/components/url-preview/YouTubeEmbed.tsx +++ b/src/app/components/url-preview/YouTubeEmbed.tsx @@ -112,7 +112,7 @@ const handleExternalLinkClick = (e: MouseEvent) => { } }; -type PlayerState = +type PlayerState = | { status: 'thumbnail' } | { status: 'loading' } | { status: 'playing'; videoUrl: string; title: string } @@ -135,7 +135,7 @@ export const YouTubeEmbed = as<'div', YouTubeEmbedProps>(({ url, ...props }, ref // Fetch video title on mount useEffect(() => { let cancelled = false; - + fetchYouTubeTitle(url).then((title) => { if (!cancelled) { setVideoTitle(title); @@ -199,17 +199,13 @@ export const YouTubeEmbed = as<'div', YouTubeEmbedProps>(({ url, ...props }, ref return ( {renderHeader(getHeaderLabel())} - )} - + {/* Additional Chips if needed */} {userId !== myUserId && ( @@ -173,43 +181,43 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) { )} {hasBottomContent && ( - - {ignored && } - {member && membership === Membership.Ban && ( - - )} - {member && - membership === Membership.Leave && - member.events.member && - member.events.member.getSender() !== userId && ( - + {ignored && } + {member && membership === Membership.Ban && ( + )} - {member && membership === Membership.Invite && ( - + )} + {member && membership === Membership.Invite && ( + + )} + - )} - - + )}
); diff --git a/src/app/components/video-viewer/VideoViewer.tsx b/src/app/components/video-viewer/VideoViewer.tsx index 99a31762..90675331 100644 --- a/src/app/components/video-viewer/VideoViewer.tsx +++ b/src/app/components/video-viewer/VideoViewer.tsx @@ -60,15 +60,9 @@ export const VideoViewer = as<'div', VideoViewerProps>( justifyContent="Center" alignItems="Center" > -
); - } + }, ); diff --git a/src/app/components/virtualizer/VirtualTile.tsx b/src/app/components/virtualizer/VirtualTile.tsx index f70c168c..d531fbba 100644 --- a/src/app/components/virtualizer/VirtualTile.tsx +++ b/src/app/components/virtualizer/VirtualTile.tsx @@ -16,5 +16,5 @@ export const VirtualTile = as<'div', VirtualTileProps>( {...props} ref={ref} /> - ) + ), ); diff --git a/src/app/cs-api.ts b/src/app/cs-api.ts index b9aac06a..e04cbfba 100644 --- a/src/app/cs-api.ts +++ b/src/app/cs-api.ts @@ -24,7 +24,7 @@ export type AutoDiscoveryInfo = Record & { export const autoDiscovery = async ( request: typeof fetch, - server: string + server: string, ): Promise<[AutoDiscoveryError, undefined] | [undefined, AutoDiscoveryInfo]> => { const host = /^https?:\/\//.test(server) ? trimTrailingSlash(server) : `https://${server}`; const autoDiscoveryUrl = `${host}/.well-known/matrix/client`; @@ -89,7 +89,7 @@ export const autoDiscovery = async ( content['m.homeserver'].base_url = trimTrailingSlash(baseUrl); if (content['m.identity_server']) { content['m.identity_server'].base_url = trimTrailingSlash( - content['m.identity_server'].base_url + content['m.identity_server'].base_url, ); } @@ -102,7 +102,7 @@ export type SpecVersions = { }; export const specVersions = async ( request: typeof fetch, - baseUrl: string + baseUrl: string, ): Promise => { const res = await request(`${trimTrailingSlash(baseUrl)}/_matrix/client/versions`); diff --git a/src/app/data/updateNotes.ts b/src/app/data/updateNotes.ts index 7a0a9810..1ac44710 100644 --- a/src/app/data/updateNotes.ts +++ b/src/app/data/updateNotes.ts @@ -14,8 +14,7 @@ const bundledImageByFile = import.meta.glob('../../../public/update/images/*', { function getUpdateBaseUrl(): string { const basePath = trimTrailingSlash(import.meta.env.BASE_URL || './'); - const relative = - basePath === '.' || basePath === '' ? 'update/' : `${basePath}/update/`; + const relative = basePath === '.' || basePath === '' ? 'update/' : `${basePath}/update/`; return new URL(relative, window.location.href).href.replace(/\/$/, ''); } @@ -87,7 +86,7 @@ function loadBundledManifest(): UpdateManifest { function loadBundledDocument(file: string): ParsedUpdateDoc | null { const safeFile = file.replace(/^\/+/, ''); const entry = Object.entries(bundledMarkdownByFile).find(([path]) => - path.endsWith(`/${safeFile}`) + path.endsWith(`/${safeFile}`), ); if (!entry) return null; return parseUpdateMarkdown(safeFile, entry[1]); @@ -99,7 +98,9 @@ function resolveBundledImageUrl(normalizedPath: string): string | undefined { const entry = Object.entries(bundledImageByFile).find(([path]) => { const normalized = path.replace(/\\/g, '/'); - return normalized.endsWith(`/${needle}`) || normalized.endsWith(`/${needle.split('/').pop() ?? ''}`); + return ( + normalized.endsWith(`/${needle}`) || normalized.endsWith(`/${needle.split('/').pop() ?? ''}`) + ); }); return entry?.[1]; diff --git a/src/app/features/ShareRoomPicker.tsx b/src/app/features/ShareRoomPicker.tsx index 03ddfb02..8e2bd5d6 100644 --- a/src/app/features/ShareRoomPicker.tsx +++ b/src/app/features/ShareRoomPicker.tsx @@ -2,7 +2,22 @@ import { useAtomValue } from 'jotai'; import React, { ChangeEventHandler, useCallback, useMemo, useRef, useState } from 'react'; import { useVirtualizer } from '@tanstack/react-virtual'; import FocusTrap from 'focus-trap-react'; -import { Avatar, Box, Button, Header, IconButton, Input, MenuItem, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text, config } from 'folds'; +import { + Avatar, + Box, + Button, + Header, + IconButton, + Input, + MenuItem, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Scroll, + Text, + config, +} from 'folds'; import { Icon, Icons } from '../components/icons'; import { useMatrixClient } from '../hooks/useMatrixClient'; import { useAllJoinedRoomsSet, useGetRoom } from '../hooks/useGetRoom'; @@ -57,18 +72,18 @@ export function ShareRoomPicker({ share, onPick, onDismiss }: ShareRoomPickerPro const allItems = useMemo( () => [...rooms, ...directs].sort(factoryRoomIdByActivity(mx)), - [mx, rooms, directs] + [mx, rooms, directs], ); const getRoomNameStr: SearchItemStrGetter = useCallback( (rId) => getRoom(rId)?.name ?? rId, - [getRoom] + [getRoom], ); const [searchResult, searchRoom, resetSearch] = useAsyncSearch( allItems, getRoomNameStr, - SEARCH_OPTS + SEARCH_OPTS, ); const items = searchResult ? searchResult.items : allItems; @@ -113,188 +128,182 @@ export function ShareRoomPicker({ share, onPick, onDismiss }: ShareRoomPickerPro return ( <> - - -
- - Share to Room - {(previewText || fileCount > 0) && ( - - {previewText - ? `"${previewText}${(share.text?.length ?? 0) > 80 ? '…' : ''}"` - : `${fileCount} file${fileCount !== 1 ? 's' : ''}`} - - )} - - - - - - -
- - } - placeholder="Search rooms…" - size="400" - variant="Background" - outlined - autoFocus - style={{ width: '100%' }} - /> - - - - - {vItems.length === 0 && ( - - - {searchResult ? 'No Match Found' : 'No Rooms'} +
+ + Share to Room + {(previewText || fileCount > 0) && ( + + {previewText + ? `"${previewText}${(share.text?.length ?? 0) > 80 ? '…' : ''}"` + : `${fileCount} file${fileCount !== 1 ? 's' : ''}`} - - {searchResult - ? `No rooms found for "${searchResult.query}".` - : 'You have no rooms to share into.'} - - - )} - - {vItems.map((vItem) => { - const roomId = items[vItem.index]; - const room = getRoom(roomId); - if (!room) return null; - const isDm = mDirects.has(roomId); - - const avatarSrc = isDm - ? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) - : getRoomAvatarUrl(mx, room, 96, useAuthentication); - - return ( - - - {avatarSrc ? ( - ( - - {nameInitials(room.name)} - - )} - /> - ) : ( - - )} - - } - > - - - {room.name} - - - - - ); - })} + )} - - - - - + + + + + +
- {confirmRoomId && (() => { - const room = getRoom(confirmRoomId); - const roomName = room?.name ?? confirmRoomId; - const isDm = mDirects.has(confirmRoomId); - return ( - }> - - - - - - Share to {isDm ? 'Person' : 'Room'}? - - Send to {roomName}? + } + placeholder="Search rooms…" + size="400" + variant="Background" + outlined + autoFocus + style={{ width: '100%' }} + /> + + + + + {vItems.length === 0 && ( + + + {searchResult ? 'No Match Found' : 'No Rooms'} + + + {searchResult + ? `No rooms found for "${searchResult.query}".` + : 'You have no rooms to share into.'} - - - - + )} + + {vItems.map((vItem) => { + const roomId = items[vItem.index]; + const room = getRoom(roomId); + if (!room) return null; + const isDm = mDirects.has(roomId); + + const avatarSrc = isDm + ? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) + : getRoomAvatarUrl(mx, room, 96, useAuthentication); + + return ( + + + {avatarSrc ? ( + ( + + {nameInitials(room.name)} + + )} + /> + ) : ( + + )} + + } + > + + + {room.name} + + + + + ); + })} - - - - - ); - })()} +
+
+
+
+
+ + {confirmRoomId && + (() => { + const room = getRoom(confirmRoomId); + const roomName = room?.name ?? confirmRoomId; + const isDm = mDirects.has(confirmRoomId); + return ( + }> + + + + + + Share to {isDm ? 'Person' : 'Room'}? + + Send to {roomName}? + + + + + + + + + + + + ); + })()} ); } diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx index 9bcfcee8..5a5f5bc2 100644 --- a/src/app/features/add-existing/AddExisting.tsx +++ b/src/app/features/add-existing/AddExisting.tsx @@ -1,6 +1,22 @@ import FocusTrap from 'focus-trap-react'; -import { Avatar, Box, Button, config, Header, IconButton, Input, Menu, MenuItem, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Spinner, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Avatar, + Box, + Button, + config, + Header, + IconButton, + Input, + Menu, + MenuItem, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Scroll, + Spinner, + Text, +} from 'folds'; import React, { ChangeEventHandler, MouseEventHandler, @@ -12,6 +28,7 @@ import React, { import { useAtomValue } from 'jotai'; import { useVirtualizer } from '@tanstack/react-virtual'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../components/icons'; import { stopPropagation } from '../../utils/keyboard'; import { useDirects, useRooms, useSpaces } from '../../state/hooks/roomList'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -79,13 +96,13 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM const getRoomNameStr: SearchItemStrGetter = useCallback( (rId) => getRoom(rId)?.name ?? rId, - [getRoom] + [getRoom], ); const [searchResult, searchRoom, resetSearch] = useAsyncSearch( allItems, getRoomNameStr, - SEARCH_OPTS + SEARCH_OPTS, ); const queryHighlighRegex = searchResult?.query ? makeHighlightRegex(searchResult.query.split(' ')) @@ -124,12 +141,12 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM suggested: false, via, }, - room.roomId + room.roomId, ); }); }, - [mx, parentId] - ) + [mx, parentId], + ), ); const applyingChanges = applyState.status === AsyncStatus.Loading; diff --git a/src/app/features/call/CallOverlay.tsx b/src/app/features/call/CallOverlay.tsx index 68728c2d..ecbc0868 100644 --- a/src/app/features/call/CallOverlay.tsx +++ b/src/app/features/call/CallOverlay.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Box, IconButton, Text, Tooltip, TooltipProvider, color } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useCall } from './useCall'; import { useRoomCallMembers } from './useRoomCallMembers'; import { CallState, CallType } from './types'; @@ -42,13 +42,15 @@ function useDraggable( onUndockRequest?: () => void, isDocked?: boolean, pendingDrag?: PendingDragState | null, - clearPendingDrag?: () => void + clearPendingDrag?: () => void, ) { const [position, setPosition] = useState({ x: 0, y: 0 }); const [isDragging, setIsDragging] = useState(false); const [nearDockZone, setNearDockZone] = useState('none'); const dragRef = useRef(null); - const dragStartRef = useRef<{ x: number; y: number; startX: number; startY: number } | null>(null); + const dragStartRef = useRef<{ x: number; y: number; startX: number; startY: number } | null>( + null, + ); // Check for pending drag state from undocking useEffect(() => { @@ -57,31 +59,31 @@ function useDraggable( // so the mouse is at the same relative position as when dragging started const panelWidth = dragRef.current?.offsetWidth ?? 400; const panelHeight = dragRef.current?.offsetHeight ?? 300; - + // The floating panel renders centered (transform: translate(-50%, -50%)) // from right: 20px, bottom: 20px by default (CSS position) // We need to calculate the position offset to put the panel under the mouse // at the same offset as when the drag started - + // Target: mouse should be at offsetX from left edge, offsetY from top edge // Panel default position: right: 20px, bottom: 20px (centered via transform) // Default center: (window.innerWidth - 20 - panelWidth/2, window.innerHeight - 20 - panelHeight/2) - + const defaultCenterX = window.innerWidth - 20 - panelWidth / 2; const defaultCenterY = window.innerHeight - 20 - panelHeight / 2; - + // Where we want the panel's top-left corner to be: const targetLeft = pendingDrag.startX - pendingDrag.offsetX; const targetTop = pendingDrag.startY - pendingDrag.offsetY; - + // Where the panel's top-left corner would be by default: const defaultLeft = defaultCenterX - panelWidth / 2; const defaultTop = defaultCenterY - panelHeight / 2; - + // Calculate the offset needed const offsetX = targetLeft - defaultLeft; const offsetY = targetTop - defaultTop; - + setPosition({ x: offsetX, y: offsetY }); setIsDragging(true); dragStartRef.current = { @@ -94,28 +96,31 @@ function useDraggable( } }, [pendingDrag, clearPendingDrag]); - const handleMouseDown = useCallback((e: React.MouseEvent) => { - if ((e.target as HTMLElement).closest('button')) return; - e.preventDefault(); - setIsDragging(true); - dragStartRef.current = { - x: position.x, - y: position.y, - startX: e.clientX, - startY: e.clientY, - }; - }, [position]); + const handleMouseDown = useCallback( + (e: React.MouseEvent) => { + if ((e.target as HTMLElement).closest('button')) return; + e.preventDefault(); + setIsDragging(true); + dragStartRef.current = { + x: position.x, + y: position.y, + startX: e.clientX, + startY: e.clientY, + }; + }, + [position], + ); // Clamp position to viewport bounds const clampToViewport = useCallback(() => { if (!dragRef.current) return; const rect = dragRef.current.getBoundingClientRect(); const padding = 16; - + let newX = position.x; let newY = position.y; let needsUpdate = false; - + if (rect.left < padding) { newX = position.x + (padding - rect.left); needsUpdate = true; @@ -132,7 +137,7 @@ function useDraggable( newY = position.y - (rect.bottom - window.innerHeight + padding); needsUpdate = true; } - + if (needsUpdate) { setPosition({ x: newX, y: newY }); } @@ -151,12 +156,12 @@ function useDraggable( const handleMouseMove = (e: MouseEvent) => { if (!dragStartRef.current || !dragRef.current) return; - + // Check dock zones const nearRightEdge = e.clientX > window.innerWidth - DOCK_THRESHOLD; - const nearSidebarZone = e.clientX < ROOM_LIST_EDGE + DOCK_THRESHOLD && - e.clientY > window.innerHeight - 150; - + const nearSidebarZone = + e.clientX < ROOM_LIST_EDGE + DOCK_THRESHOLD && e.clientY > window.innerHeight - 150; + if (!isDocked) { if (nearSidebarZone) { setNearDockZone('sidebar'); @@ -166,7 +171,7 @@ function useDraggable( setNearDockZone('none'); } } - + // If docked and dragging away from edge, trigger undock if (isDocked) { const dragDistance = Math.abs(e.clientX - dragStartRef.current.startX); @@ -177,21 +182,21 @@ function useDraggable( return; } } - + const deltaX = e.clientX - dragStartRef.current.startX; const deltaY = e.clientY - dragStartRef.current.startY; - + const rect = dragRef.current.getBoundingClientRect(); const padding = 16; - + let newX = dragStartRef.current.x + deltaX; let newY = dragStartRef.current.y + deltaY; - + const newLeft = rect.left - position.x + newX; const newRight = rect.right - position.x + newX; const newTop = rect.top - position.y + newY; const newBottom = rect.bottom - position.y + newY; - + if (newLeft < padding) { newX += padding - newLeft; } @@ -204,16 +209,16 @@ function useDraggable( if (newBottom > window.innerHeight - padding) { newY -= newBottom - window.innerHeight + padding; } - + setPosition({ x: newX, y: newY }); }; const handleMouseUp = (e: MouseEvent) => { // Check which dock zone to use const nearRightEdge = e.clientX > window.innerWidth - DOCK_THRESHOLD; - const nearSidebarZone = e.clientX < ROOM_LIST_EDGE + DOCK_THRESHOLD && - e.clientY > window.innerHeight - 150; - + const nearSidebarZone = + e.clientX < ROOM_LIST_EDGE + DOCK_THRESHOLD && e.clientY > window.innerHeight - 150; + if (!isDocked) { if (nearSidebarZone) { onDockSidebar?.(); @@ -390,11 +395,11 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { const popoutWindow = window.open( '', '_blank', - 'width=1200,height=800,frame=false,titleBarStyle=hidden' + 'width=1200,height=800,frame=false,titleBarStyle=hidden', ); - + if (!popoutWindow) return; - + popoutWindow.document.write(` @@ -523,12 +528,12 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { `); popoutWindow.document.close(); - + // Wait for document to be ready, attach video FIRST (while still attached to main), THEN hide main setTimeout(() => { const videoContainer = popoutWindow.document.getElementById('videoContainer'); if (!videoContainer) return; - + // For local screenshare, create new video with the MediaStream if (share.isLocal && share.stream) { const videoEl = popoutWindow.document.createElement('video'); @@ -538,11 +543,11 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { videoEl.srcObject = share.stream; videoContainer.appendChild(videoEl); videoEl.play().catch(() => {}); - + // Now that pop-out has the stream, hide main window setIsPoppedOut(true); } - + // For remote screenshare, use LiveKit track's attach method (creates fresh video) if (!share.isLocal && share.track) { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -559,13 +564,13 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { // @ts-expect-error webkit property videoEl.style.webkitAppRegion = 'drag'; videoContainer.appendChild(videoEl); - + // Now that pop-out has the track, hide main window (which will detach from main) setIsPoppedOut(true); } } }, 100); - + // Show preview again when pop-out window is closed popoutWindow.addEventListener('beforeunload', () => { // For remote tracks, detach from pop-out @@ -586,37 +591,44 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { }); }, [share.isLocal, share.stream, share.track]); - const handleMouseMoveWrapper = useCallback((e: React.MouseEvent) => { - // Clear any pending hide timeout - if (hideTimeoutRef.current) { - clearTimeout(hideTimeoutRef.current); - hideTimeoutRef.current = null; - } - setShowControls(true); - handleMouseMove(e); - }, [handleMouseMove]); + const handleMouseMoveWrapper = useCallback( + (e: React.MouseEvent) => { + // Clear any pending hide timeout + if (hideTimeoutRef.current) { + clearTimeout(hideTimeoutRef.current); + hideTimeoutRef.current = null; + } + setShowControls(true); + handleMouseMove(e); + }, + [handleMouseMove], + ); - const handleMouseLeaveWrapper = useCallback((e: React.MouseEvent) => { - // Delay hiding controls to prevent flickering - hideTimeoutRef.current = setTimeout(() => { - setShowControls(false); - }, 300); - handleMouseLeave(e); - }, [handleMouseLeave]); + const handleMouseLeaveWrapper = useCallback( + (e: React.MouseEvent) => { + // Delay hiding controls to prevent flickering + hideTimeoutRef.current = setTimeout(() => { + setShowControls(false); + }, 300); + handleMouseLeave(e); + }, + [handleMouseLeave], + ); // Cleanup timeout on unmount - useEffect(() => { - return () => { + useEffect( + () => () => { if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); } - }; - }, []); + }, + [], + ); return ( -
- {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */} -
- + {/* Control buttons overlay */} {showControls && ( - )} - +
); @@ -696,7 +708,8 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) { * Component that displays active call controls and video streams */ export function CallOverlay() { - const { activeCall, endCall, toggleMute, toggleDeafen, toggleVideo, toggleScreenShare } = useCall(); + const { activeCall, endCall, toggleMute, toggleDeafen, toggleVideo, toggleScreenShare } = + useCall(); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const selectedRoomId = useSelectedRoom(); @@ -710,44 +723,44 @@ export function CallOverlay() { const remoteVideoRef = useRef(null); const containerRef = useRef(null); const { navigateRoom } = useRoomNavigate(); - + // Docking state const [isDocked, setIsDocked] = useSetting(settingsAtom, 'isCallPanelDocked'); const [, setDockPosition] = useSetting(settingsAtom, 'callPanelDockPosition'); - + // Pending drag state from undocking const [pendingDrag, setPendingDrag] = useAtom(pendingUndockDragAtom); - + const clearPendingDrag = useCallback(() => { setPendingDrag(null); }, [setPendingDrag]); - + const handleDockRight = useCallback(() => { setDockPosition('right'); setIsDocked(true); }, [setIsDocked, setDockPosition]); - + const handleDockSidebar = useCallback(() => { setDockPosition('sidebar'); setIsDocked(true); }, [setIsDocked, setDockPosition]); - + const handleUndockRequest = useCallback(() => { setIsDocked(false); }, [setIsDocked]); - + const { position, isDragging, nearDockZone, handleMouseDown, dragRef } = useDraggable( handleDockRight, handleDockSidebar, handleUndockRequest, isDocked, pendingDrag, - clearPendingDrag + clearPendingDrag, ); - + // Get unread notifications for the call room const unread = useRoomUnread(activeCall?.roomId ?? '', roomToUnreadAtom); - + // Get call members from Matrix state events (provides real Matrix user IDs) const { callMembers } = useRoomCallMembers(activeCall?.roomId ?? ''); const myUserId = mx.getUserId() ?? ''; @@ -755,7 +768,7 @@ export function CallOverlay() { // Memoize the screenshare list to prevent re-renders causing flickering const allScreenShares = useMemo((): ScreenShareEntry[] => { const shares: ScreenShareEntry[] = []; - + // Add local screenshare first if active if (activeCall?.isScreenSharing && activeCall?.localScreenStream) { shares.push({ @@ -766,22 +779,23 @@ export function CallOverlay() { stream: activeCall.localScreenStream, }); } - + // Add remote screenshares - const remoteScreenTracks = activeCall?.remoteScreenTracks + const remoteScreenTracks = activeCall?.remoteScreenTracks ? Array.from(activeCall.remoteScreenTracks.values()) : []; - + remoteScreenTracks.forEach((trackInfo) => { // Try to extract deviceId from LiveKit identity (format: "deviceId_timestamp") const livekitId = trackInfo.participantId; const underscoreIndex = livekitId.lastIndexOf('_'); - const possibleDeviceId = underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId; - + const possibleDeviceId = + underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId; + // Look up Matrix user ID by matching device ID from call members const matchingMember = callMembers.find((m) => m.deviceId === possibleDeviceId); const matrixUserId = matchingMember?.userId ?? livekitId; - + shares.push({ id: livekitId, isLocal: false, @@ -792,9 +806,16 @@ export function CallOverlay() { stream: trackInfo.stream, }); }); - + return shares; - }, [activeCall?.isScreenSharing, activeCall?.localScreenStream, activeCall?.remoteScreenTracks, activeCall?.roomId, callMembers, myUserId]); + }, [ + activeCall?.isScreenSharing, + activeCall?.localScreenStream, + activeCall?.remoteScreenTracks, + activeCall?.roomId, + callMembers, + myUserId, + ]); useEffect(() => { if (!activeCall || activeCall.state !== CallState.Connected) { @@ -832,7 +853,7 @@ export function CallOverlay() { // Fullscreen toggle handler const handleToggleFullscreen = useCallback(async () => { if (!containerRef.current) return; - + try { if (!isFullscreen) { await containerRef.current.requestFullscreen(); @@ -850,19 +871,19 @@ export function CallOverlay() { // Pop-out window handler const handlePopOut = useCallback(() => { if (!activeCall) return; - + // Get room inside callback to avoid initialization order issues const callRoom = mx.getRoom(activeCall.roomId); - + const popoutWindow = window.open( '', '_blank', - 'width=1200,height=800,menubar=no,toolbar=no,location=no,status=no' + 'width=1200,height=800,menubar=no,toolbar=no,location=no,status=no', ); - + if (popoutWindow && activeCall.remoteStreams.size > 0) { const [firstStream] = activeCall.remoteStreams.values(); - + popoutWindow.document.write(` @@ -898,7 +919,7 @@ export function CallOverlay() { `); popoutWindow.document.close(); - + // Wait for window to load, then set the video stream setTimeout(() => { const videoEl = popoutWindow.document.getElementById('remoteVideo'); @@ -913,7 +934,7 @@ export function CallOverlay() { const handleTogglePip = useCallback(async () => { const videoEl = remoteVideoRef.current; if (!videoEl) return; - + try { if (!isPip && document.pictureInPictureEnabled) { await videoEl.requestPictureInPicture(); @@ -942,13 +963,13 @@ export function CallOverlay() { useEffect(() => { const videoEl = remoteVideoRef.current; if (!videoEl) return undefined; - + const handlePipEnter = () => setIsPip(true); const handlePipLeave = () => setIsPip(false); - + videoEl.addEventListener('enterpictureinpicture', handlePipEnter); videoEl.addEventListener('leavepictureinpicture', handlePipLeave); - + return () => { videoEl.removeEventListener('enterpictureinpicture', handlePipEnter); videoEl.removeEventListener('leavepictureinpicture', handlePipLeave); @@ -956,10 +977,13 @@ export function CallOverlay() { }, [activeCall]); // Assign both refs to the container - must be before early return - const setContainerRef = useCallback((el: HTMLDivElement | null) => { - (containerRef as React.MutableRefObject).current = el; - (dragRef as React.MutableRefObject).current = el; - }, [dragRef]); + const setContainerRef = useCallback( + (el: HTMLDivElement | null) => { + (containerRef as React.MutableRefObject).current = el; + (dragRef as React.MutableRefObject).current = el; + }, + [dragRef], + ); if (!activeCall || activeCall.state === CallState.Idle || activeCall.state === CallState.Ended) { return null; @@ -996,7 +1020,9 @@ export function CallOverlay() { */ const getParticipantName = (participantId: string): string => { if (!room) return getMxIdLocalPart(participantId) ?? participantId; - return getMemberDisplayName(room, participantId) ?? getMxIdLocalPart(participantId) ?? participantId; + return ( + getMemberDisplayName(room, participantId) ?? getMxIdLocalPart(participantId) ?? participantId + ); }; /** @@ -1005,15 +1031,15 @@ export function CallOverlay() { */ const isParticipantSpeaking = (userId: string): boolean => { if (!activeCall) return false; - + // Direct check for Matrix user ID (works for local user) if (activeCall.activeSpeakers.has(userId)) return true; - + // For remote users, activeSpeakers contains LiveKit identities (deviceId_timestamp) // We need to find the deviceId for this user and check if any matching identity is speaking const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + // Check if any active speaker has this user's deviceId return Array.from(activeCall.activeSpeakers).some((speakerId) => { const underscoreIndex = speakerId.lastIndexOf('_'); @@ -1028,15 +1054,15 @@ export function CallOverlay() { */ const isParticipantMuted = (userId: string): boolean => { if (!activeCall) return false; - + // For local user, check activeCall.isMuted if (userId === myUserId) return activeCall.isMuted; - + // For remote users, mutedParticipants contains LiveKit identities (deviceId_timestamp) // We need to find the deviceId for this user and check if any matching identity is muted const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + // Check if any muted participant has this user's deviceId return Array.from(activeCall.mutedParticipants).some((mutedId) => { const underscoreIndex = mutedId.lastIndexOf('_'); @@ -1077,7 +1103,9 @@ export function CallOverlay() { isFullscreen && css.CallOverlayFullscreen, isDocked && !isFullscreen && css.CallOverlayDocked, isDragging && css.CallOverlayDragging, - ].filter(Boolean).join(' '); + ] + .filter(Boolean) + .join(' '); return ( <> @@ -1087,145 +1115,198 @@ export function CallOverlay() {
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */} -
- - - - {isConnecting ? 'Connecting...' : `In Call - ${room?.name ?? 'Unknown Room'}`} - {selectedRoomId === activeCall.roomId && ( +
+ + + + {isConnecting ? 'Connecting...' : `In Call - ${room?.name ?? 'Unknown Room'}`} + {selectedRoomId === activeCall.roomId && ( + + Current Room + + } + > + {(triggerRef) => ( + + )} + + )} + + {unread && unread.total > 0 && ( + 0} count={unread.total} /> + )} + {selectedRoomId !== activeCall.roomId && ( Current Room} + tooltip={ + + Go to Room + + } > {(triggerRef) => ( - + onClick={() => navigateRoom(activeCall.roomId)} + variant="Secondary" + size="300" + style={{ padding: '2px', marginLeft: '4px' }} + > + + )} )} - - {unread && unread.total > 0 && ( - 0} count={unread.total} /> - )} - {selectedRoomId !== activeCall.roomId && ( - Go to Room} - > - {(triggerRef) => ( - navigateRoom(activeCall.roomId)} - variant="Secondary" - size="300" - style={{ padding: '2px', marginLeft: '4px' }} - > - - - )} - - )} - - - - {formatDuration(duration)} - - {isVideoCall && ( - <> - Pop Out} - > - {(triggerRef) => ( - - - - )} - - {isPip ? 'Exit PiP' : 'Picture-in-Picture'}} - > - {(triggerRef) => ( - - - - - - )} - - {isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'}} - > - {(triggerRef) => ( - - - {isFullscreen ? : } - - - )} - - - )} - -
- - {/* Participants Section */} -
- - {showParticipants && ( -
- {allParticipants.map((participantId) => { - const isMe = participantId === myUserId; - const displayName = getParticipantName(participantId); - const avatarUrl = getParticipantAvatar(participantId); - const isSpeaking = isParticipantSpeaking(participantId); - const isMuted = isParticipantMuted(participantId); - // Get screenshares for this participant - const participantScreenShares = allScreenShares.filter( - (share) => share.participantId === participantId - ); - - return ( -
-
+ + + {formatDuration(duration)} + + {isVideoCall && ( + <> + + Pop Out + + } + > + {(triggerRef) => ( + + + + )} + + + {isPip ? 'Exit PiP' : 'Picture-in-Picture'} + + } + > + {(triggerRef) => ( + + + + + + )} + + + {isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'} + + } + > + {(triggerRef) => ( + + + {isFullscreen ? : } + + + )} + + + )} + +
+ + {/* Participants Section */} +
+ + {showParticipants && ( +
+ {allParticipants.map((participantId) => { + const isMe = participantId === myUserId; + const displayName = getParticipantName(participantId); + const avatarUrl = getParticipantAvatar(participantId); + const isSpeaking = isParticipantSpeaking(participantId); + const isMuted = isParticipantMuted(participantId); + // Get screenshares for this participant + const participantScreenShares = allScreenShares.filter( + (share) => share.participantId === participantId, + ); + + return ( +
+
{collapsedScreenShares.has(participantScreenShares[0].id) ? 'Show Screen' : 'Hide Screen'}} + tooltip={ + + + {collapsedScreenShares.has(participantScreenShares[0].id) + ? 'Show Screen' + : 'Hide Screen'} + + + } > {(triggerRef) => ( - { setCollapsedScreenShares((prev) => { const next = new Set(prev); @@ -1273,7 +1362,7 @@ export function CallOverlay() { return next; }); }} - variant="Secondary" + variant="Secondary" size="300" style={{ padding: '2px' }} > @@ -1283,168 +1372,161 @@ export function CallOverlay() { )}
- ); - })} -
- )} -
+ ); + })} +
+ )} +
- {/* Screen shares rendered outside participant list */} - {allScreenShares - .filter((share) => !collapsedScreenShares.has(share.id)) - .map((share) => ( - - ))} + {/* Screen shares rendered outside participant list */} + {allScreenShares + .filter((share) => !collapsedScreenShares.has(share.id)) + .map((share) => ( + + ))} - {isVideoCall && ( -
- {/* eslint-disable-next-line jsx-a11y/media-has-caption */} -
); } diff --git a/src/app/features/call/CallService.ts b/src/app/features/call/CallService.ts index 6a1b28f6..4fd913d1 100644 --- a/src/app/features/call/CallService.ts +++ b/src/app/features/call/CallService.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -/* eslint-disable import/no-extraneous-dependencies */ + import { Room, RoomEvent, @@ -23,16 +23,22 @@ import { LiveKitJWTResponse, CallMemberEventContent, } from './types'; -import { - fetchLiveKitJWT, - fetchWellKnownWithRTC, - getLiveKitFocus, +import { + fetchLiveKitJWT, + fetchWellKnownWithRTC, + getLiveKitFocus, requestOpenIdToken, fetchLiveKitJWTFromServers, getLiveKitHomeserverPriority, } from './useRtcConfig'; import { getActiveCallMembers } from './useRoomCallMembers'; -import { getAudioCaptureOptions, getAudioSettings, AUDIO_SETTINGS_CHANGED_EVENT, SCREEN_SHARE_RESOLUTIONS, SCREEN_SHARE_BITRATES } from '../settings/audio/Audio'; +import { + getAudioCaptureOptions, + getAudioSettings, + AUDIO_SETTINGS_CHANGED_EVENT, + SCREEN_SHARE_RESOLUTIONS, + SCREEN_SHARE_BITRATES, +} from '../settings/audio/Audio'; import { getCallSounds, CallSoundType } from './CallSounds'; type CallEventListener = (event: CallEvent) => void; @@ -61,19 +67,26 @@ function checkWebRTCSupport(): { supported: boolean; details: Record { const stateKey = this.config.userId; @@ -193,15 +206,19 @@ export class CallService { if (room) { const powerLevelsEvent = room.currentState.getStateEvents('m.room.power_levels', ''); const powerLevelsContent = powerLevelsEvent?.getContent() || {}; - - const myPower = powerLevelsContent.users?.[this.config.userId] ?? powerLevelsContent.users_default ?? 0; - const requiredPower = powerLevelsContent.events?.[CALL_MEMBER_EVENT_TYPE] ?? powerLevelsContent.state_default ?? 50; - + + const myPower = + powerLevelsContent.users?.[this.config.userId] ?? powerLevelsContent.users_default ?? 0; + const requiredPower = + powerLevelsContent.events?.[CALL_MEMBER_EVENT_TYPE] ?? + powerLevelsContent.state_default ?? + 50; + if (myPower < requiredPower) { console.warn( `Cannot send call member event: insufficient permissions. ` + - `User power level (${myPower}) < required power level (${requiredPower}). ` + - `Call will work locally but room members won't see your call status.` + `User power level (${myPower}) < required power level (${requiredPower}). ` + + `Call will work locally but room members won't see your call status.`, ); return; } @@ -217,9 +234,7 @@ export class CallService { device_id: this.config.deviceId, session_id: callId, expires_ts: Date.now() + MEMBERSHIP_EXPIRY_MS, - feeds: [ - { purpose: 'usermedia' }, - ], + feeds: [{ purpose: 'usermedia' }], }, ], }, @@ -231,7 +246,7 @@ export class CallService { roomId, CALL_MEMBER_EVENT_TYPE, content, - stateKey + stateKey, ); } else { // Clear the call membership by sending empty calls array @@ -244,7 +259,7 @@ export class CallService { roomId, CALL_MEMBER_EVENT_TYPE, content, - stateKey + stateKey, ); } } @@ -335,7 +350,7 @@ export class CallService { // Check if there's already an active call const activeCallMembers = getActiveCallMembers(room); const isJoiningExistingCall = activeCallMembers.length > 0; - + if (isJoiningExistingCall) { console.log(`Joining existing call with ${activeCallMembers.length} participant(s)`); } else { @@ -345,7 +360,7 @@ export class CallService { const homeserverPriority = getLiveKitHomeserverPriority( room, this.config.homeserverBaseUrl, - this.config.userId + this.config.userId, ); console.log('Trying homeservers in order:', homeserverPriority); @@ -357,7 +372,7 @@ export class CallService { roomId, this.config.userId, this.config.deviceId, - this.config.accessToken + this.config.accessToken, ); if (!result) { @@ -365,15 +380,13 @@ export class CallService { } this.livekitJwt = result.jwt; - + // Track if using remote homeserver const userHomeserverDomain = this.config.homeserverBaseUrl .replace('https://', '') .replace('http://', ''); - const usedHomeserverDomain = result.homeserver - .replace('https://', '') - .replace('http://', ''); - + const usedHomeserverDomain = result.homeserver.replace('https://', '').replace('http://', ''); + if (usedHomeserverDomain !== userHomeserverDomain) { this.activeCall!.livekitHomeserver = result.homeserver; console.log(`Using remote homeserver for LiveKit: ${result.homeserver}`); @@ -385,7 +398,7 @@ export class CallService { // Check WebRTC support before attempting connection const webrtcCheck = checkWebRTCSupport(); console.log('WebRTC support check:', webrtcCheck); - + if (!webrtcCheck.supported) { console.warn('WebRTC may not be fully supported. Attempting connection anyway...'); console.warn('WebRTC details:', JSON.stringify(webrtcCheck.details, null, 2)); @@ -480,15 +493,24 @@ export class CallService { ( track: RemoteTrackPublication['track'], publication: RemoteTrackPublication, - participant: RemoteParticipant + participant: RemoteParticipant, ) => { if (!track || !this.activeCall) return; - const isScreenShare = publication.source === Track.Source.ScreenShare || - publication.source === Track.Source.ScreenShareAudio; - - console.log('Track subscribed:', track.kind, 'source:', publication.source, - 'isScreenShare:', isScreenShare, 'from', participant.identity); + const isScreenShare = + publication.source === Track.Source.ScreenShare || + publication.source === Track.Source.ScreenShareAudio; + + console.log( + 'Track subscribed:', + track.kind, + 'source:', + publication.source, + 'isScreenShare:', + isScreenShare, + 'from', + participant.identity, + ); console.log('Track mediaStreamTrack:', track.mediaStreamTrack); console.log('Track mediaStreamTrack readyState:', track.mediaStreamTrack?.readyState); console.log('Track mediaStreamTrack enabled:', track.mediaStreamTrack?.enabled); @@ -497,7 +519,7 @@ export class CallService { if (track.kind === 'audio') { const audioElement = track.attach() as HTMLAudioElement; audioElement.id = `audio-${participant.identity}-${publication.source}`; - + // Set the preferred output device if supported and selected const audioSettings = getAudioSettings(); if (audioSettings.speakerId && 'setSinkId' in audioElement) { @@ -506,35 +528,39 @@ export class CallService { .then(() => console.log('Speaker set to:', audioSettings.speakerId)) .catch((e) => console.warn('Could not set speaker device:', e)); } - + document.body.appendChild(audioElement); console.log('Audio element attached for', participant.identity); - + // If we're currently deafened, mute this new track so we don't hear them if (this.activeCall?.isDeafened) { track.setMuted(true); - console.log('Auto-muted new audio track from', participant.identity, 'due to deafen state'); + console.log( + 'Auto-muted new audio track from', + participant.identity, + 'due to deafen state', + ); } } // Handle screen share video tracks separately if (isScreenShare && track.kind === 'video') { const mediaStream = new MediaStream([track.mediaStreamTrack]); - + console.log('📺 Screen share received from', participant.identity); console.log('📺 Screen share track:', track); console.log('📺 Screen share MediaStream:', mediaStream); console.log('📺 Screen share MediaStream tracks:', mediaStream?.getTracks()); - + this.activeCall.remoteScreenStreams.set(participant.identity, mediaStream); - + // Store the actual track for proper attachment later this.activeCall.remoteScreenTracks.set(participant.identity, { participantId: participant.identity, track, stream: mediaStream, }); - + this.emit({ type: CallEventType.ScreenShareStarted, roomId: this.activeCall.roomId, @@ -547,7 +573,7 @@ export class CallService { } else if (track.kind === 'video') { const mediaStream = new MediaStream([track.mediaStreamTrack]); this.activeCall.remoteStreams.set(participant.identity, mediaStream); - + this.emit({ type: CallEventType.RemoteStreamAdded, roomId: this.activeCall.roomId, @@ -562,7 +588,7 @@ export class CallService { if (!this.activeCall.participants.includes(participant.identity)) { this.activeCall.participants.push(participant.identity); } - } + }, ); this.livekitRoom.on( @@ -570,19 +596,30 @@ export class CallService { ( track: RemoteTrackPublication['track'], publication: RemoteTrackPublication, - participant: RemoteParticipant + participant: RemoteParticipant, ) => { if (!this.activeCall) return; - const isScreenShare = publication.source === Track.Source.ScreenShare || - publication.source === Track.Source.ScreenShareAudio; + const isScreenShare = + publication.source === Track.Source.ScreenShare || + publication.source === Track.Source.ScreenShareAudio; - console.log('Track unsubscribed:', track?.kind, 'source:', publication.source, - 'isScreenShare:', isScreenShare, 'from', participant.identity); + console.log( + 'Track unsubscribed:', + track?.kind, + 'source:', + publication.source, + 'isScreenShare:', + isScreenShare, + 'from', + participant.identity, + ); // Remove audio element if it exists if (track?.kind === 'audio') { - const audioElement = document.getElementById(`audio-${participant.identity}-${publication.source}`); + const audioElement = document.getElementById( + `audio-${participant.identity}-${publication.source}`, + ); if (audioElement) { audioElement.remove(); console.log('Audio element removed for', participant.identity); @@ -597,7 +634,7 @@ export class CallService { this.activeCall.remoteScreenStreams.delete(participant.identity); this.activeCall.remoteScreenTracks.delete(participant.identity); console.log('📺 Screen share ended from', participant.identity); - + this.emit({ type: CallEventType.ScreenShareStopped, roomId: this.activeCall.roomId, @@ -605,18 +642,23 @@ export class CallService { }); } else if (track?.kind === 'video') { this.activeCall.remoteStreams.delete(participant.identity); - + this.emit({ type: CallEventType.RemoteStreamRemoved, roomId: this.activeCall.roomId, data: { participantId: participant.identity }, }); } - } + }, ); this.livekitRoom.on(RoomEvent.ParticipantConnected, (participant: RemoteParticipant) => { - console.log('Participant connected:', participant.identity, 'in Matrix room:', this.activeCall?.roomId); + console.log( + 'Participant connected:', + participant.identity, + 'in Matrix room:', + this.activeCall?.roomId, + ); console.log('Current LiveKit room name:', this.livekitRoom?.name); // Listen for this participant's speaking state @@ -630,10 +672,10 @@ export class CallService { if (this.activeCall && !this.activeCall.participants.includes(participant.identity)) { this.activeCall.participants.push(participant.identity); - + // Play join sound for remote participant getCallSounds().playSound(CallSoundType.CallJoined); - + this.emit({ type: CallEventType.ParticipantJoined, roomId: this.activeCall.roomId, @@ -647,7 +689,7 @@ export class CallService { if (this.activeCall) { this.activeCall.participants = this.activeCall.participants.filter( - (p) => p !== participant.identity + (p) => p !== participant.identity, ); this.activeCall.remoteStreams.delete(participant.identity); @@ -677,15 +719,15 @@ export class CallService { if (!this.activeCall) return; if (participant.identity === this.livekitRoom?.localParticipant.identity) return; if (publication.kind !== 'audio') return; - + console.log(`🔇 ${participant.identity} muted their microphone`); - + // Track muted state this.activeCall.mutedParticipants.add(participant.identity); - + // Play mute sound for remote participant getCallSounds().playSound(CallSoundType.MicMute); - + this.emit({ type: CallEventType.RemoteMuteChanged, roomId: this.activeCall.roomId, @@ -698,15 +740,15 @@ export class CallService { if (!this.activeCall) return; if (participant.identity === this.livekitRoom?.localParticipant.identity) return; if (publication.kind !== 'audio') return; - + console.log(`🔊 ${participant.identity} unmuted their microphone`); - + // Track unmuted state this.activeCall.mutedParticipants.delete(participant.identity); - + // Play unmute sound for remote participant getCallSounds().playSound(CallSoundType.MicUnmute); - + this.emit({ type: CallEventType.RemoteMuteChanged, roomId: this.activeCall.roomId, @@ -719,30 +761,30 @@ export class CallService { // We preserve the existing activeSpeakers that may include local user this.livekitRoom.on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => { if (!this.activeCall) return; - + // Get remote speaker identities const remoteSpeakerIds = speakers .filter((s) => s.identity !== this.livekitRoom?.localParticipant.identity) .map((s) => s.identity); - + // Check if local participant is speaking (from LiveKit's list) const localSpeaking = speakers.some( - (s) => s.identity === this.livekitRoom?.localParticipant.identity + (s) => s.identity === this.livekitRoom?.localParticipant.identity, ); - + // Build new activeSpeakers set - use Matrix user ID for local const newSpeakers = new Set(remoteSpeakerIds); if (localSpeaking) { newSpeakers.add(this.config.userId); } - + this.activeCall.activeSpeakers = newSpeakers; - + if (speakers.length > 0) { const speakerNames = speakers.map((s) => s.identity).join(', '); console.log('🎤 Active speakers:', speakerNames); } - + this.emit({ type: CallEventType.SpeakersChanged, roomId: this.activeCall.roomId, @@ -751,46 +793,52 @@ export class CallService { }); // Listen for participant metadata changes (for deafen state) - this.livekitRoom.on(RoomEvent.ParticipantMetadataChanged, (prevMetadata: string | undefined, participant: Participant) => { - if (!this.activeCall) return; - if (participant.identity === this.livekitRoom?.localParticipant.identity) return; - - try { - const prevData = prevMetadata ? JSON.parse(prevMetadata) : {}; - const newData = participant.metadata ? JSON.parse(participant.metadata) : {}; - - const wasDeafened = prevData.isDeafened === true; - const isDeafened = newData.isDeafened === true; - - if (wasDeafened !== isDeafened) { - console.log(`🎧 ${participant.identity} ${isDeafened ? 'deafened' : 'undeafened'}`); - getCallSounds().playSound(isDeafened ? CallSoundType.Deafen : CallSoundType.Undeafen); + this.livekitRoom.on( + RoomEvent.ParticipantMetadataChanged, + (prevMetadata: string | undefined, participant: Participant) => { + if (!this.activeCall) return; + if (participant.identity === this.livekitRoom?.localParticipant.identity) return; + + try { + const prevData = prevMetadata ? JSON.parse(prevMetadata) : {}; + const newData = participant.metadata ? JSON.parse(participant.metadata) : {}; + + const wasDeafened = prevData.isDeafened === true; + const isDeafened = newData.isDeafened === true; + + if (wasDeafened !== isDeafened) { + console.log(`🎧 ${participant.identity} ${isDeafened ? 'deafened' : 'undeafened'}`); + getCallSounds().playSound(isDeafened ? CallSoundType.Deafen : CallSoundType.Undeafen); + } + } catch { + // Ignore metadata parse errors } - } catch { - // Ignore metadata parse errors - } - }); + }, + ); // Track local participant speaking state - use Matrix user ID for consistency - this.livekitRoom.localParticipant.on(ParticipantEvent.IsSpeakingChanged, (speaking: boolean) => { - if (!this.activeCall) return; - - const myUserId = this.config.userId; - - if (speaking) { - console.log('🎙️ You are speaking'); - this.activeCall.activeSpeakers.add(myUserId); - } else { - console.log('🔇 You stopped speaking'); - this.activeCall.activeSpeakers.delete(myUserId); - } - - this.emit({ - type: CallEventType.SpeakersChanged, - roomId: this.activeCall.roomId, - data: { speakers: this.activeCall.activeSpeakers }, - }); - }); + this.livekitRoom.localParticipant.on( + ParticipantEvent.IsSpeakingChanged, + (speaking: boolean) => { + if (!this.activeCall) return; + + const myUserId = this.config.userId; + + if (speaking) { + console.log('🎙️ You are speaking'); + this.activeCall.activeSpeakers.add(myUserId); + } else { + console.log('🔇 You stopped speaking'); + this.activeCall.activeSpeakers.delete(myUserId); + } + + this.emit({ + type: CallEventType.SpeakersChanged, + roomId: this.activeCall.roomId, + data: { speakers: this.activeCall.activeSpeakers }, + }); + }, + ); // Track audio level changes for local participant (more detailed) this.livekitRoom.localParticipant.on(ParticipantEvent.AudioStreamAcquired, () => { @@ -817,7 +865,7 @@ export class CallService { getCallSounds().playSound(CallSoundType.CallDepart); try { - // Clear Matrix call membership - this state event will be rendered + // Clear Matrix call membership - this state event will be rendered // in the timeline as a "left the call" notification await this.sendCallMemberEvent(roomId, '', false); } catch (error) { @@ -854,12 +902,12 @@ export class CallService { } const newMuteState = !this.activeCall.isMuted; - + // If unmuting while deafened, undeafen first if (!newMuteState && this.activeCall.isDeafened) { this.activeCall.isDeafened = false; getCallSounds().setDeafened(false); - + // Unmute all remote audio tracks this.livekitRoom.remoteParticipants.forEach((participant) => { participant.audioTrackPublications.forEach((publication) => { @@ -868,7 +916,7 @@ export class CallService { } }); }); - + // Broadcast undeafen state const metadata = JSON.stringify({ isDeafened: false }); this.livekitRoom.localParticipant.setMetadata(metadata).catch((err) => { @@ -878,17 +926,12 @@ export class CallService { // Play undeafen sound getCallSounds().playSound(CallSoundType.Undeafen); } - - this.livekitRoom.localParticipant.setMicrophoneEnabled( - !newMuteState, - getAudioCaptureOptions() - ); + + this.livekitRoom.localParticipant.setMicrophoneEnabled(!newMuteState, getAudioCaptureOptions()); this.activeCall.isMuted = newMuteState; // Play mute/unmute sound - getCallSounds().playSound( - newMuteState ? CallSoundType.MicMute : CallSoundType.MicUnmute - ); + getCallSounds().playSound(newMuteState ? CallSoundType.MicMute : CallSoundType.MicUnmute); return newMuteState; } @@ -921,7 +964,7 @@ export class CallService { if (newDeafenState) { // Remember if user was muted before deafening this.wasMutedBeforeDeafen = this.activeCall.isMuted; - + // Deafening - always mute mic if (!this.activeCall.isMuted) { this.livekitRoom.localParticipant.setMicrophoneEnabled(false); @@ -943,9 +986,7 @@ export class CallService { }); // Play deafen/undeafen sound (these always play for user feedback) - getCallSounds().playSound( - newDeafenState ? CallSoundType.Deafen : CallSoundType.Undeafen - ); + getCallSounds().playSound(newDeafenState ? CallSoundType.Deafen : CallSoundType.Undeafen); return newDeafenState; } @@ -1031,13 +1072,14 @@ export class CallService { // Note: audio here is for system/tab audio, not microphone const screenShareOptions = { audio: true, // Include system audio if available - resolution: audioSettings.screenShareResolution === 'source' - ? undefined - : { - width: resolution.width, - height: resolution.height, - frameRate: audioSettings.screenShareFrameRate, - }, + resolution: + audioSettings.screenShareResolution === 'source' + ? undefined + : { + width: resolution.width, + height: resolution.height, + frameRate: audioSettings.screenShareFrameRate, + }, }; // Enable screen share with the configured options @@ -1050,14 +1092,13 @@ export class CallService { // Set bitrate on the screen share track publication const screenSharePub = Array.from( - this.livekitRoom.localParticipant.trackPublications.values() - ).find( - (pub): pub is LocalTrackPublication => - pub.source === Track.Source.ScreenShare - ); + this.livekitRoom.localParticipant.trackPublications.values(), + ).find((pub): pub is LocalTrackPublication => pub.source === Track.Source.ScreenShare); if (screenSharePub?.track) { - console.log(`Screen share started with bitrate: ${SCREEN_SHARE_BITRATES[audioSettings.screenShareBitrate].bitrate}kbps`); + console.log( + `Screen share started with bitrate: ${SCREEN_SHARE_BITRATES[audioSettings.screenShareBitrate].bitrate}kbps`, + ); // Capture local screen stream for preview const mediaStream = new MediaStream([screenSharePub.track.mediaStreamTrack]); this.activeCall.localScreenStream = mediaStream; @@ -1145,7 +1186,7 @@ export class CallService { }; const publication = this.livekitRoom.localParticipant.getTrackPublication( - Track.Source.Microphone + Track.Source.Microphone, ); const track = publication?.track; if (!(track instanceof LocalAudioTrack)) return; diff --git a/src/app/features/call/CallSounds.ts b/src/app/features/call/CallSounds.ts index 10d5560f..6df6a88f 100644 --- a/src/app/features/call/CallSounds.ts +++ b/src/app/features/call/CallSounds.ts @@ -70,9 +70,11 @@ export class CallSounds { */ playSound(soundType: CallSoundType, loop = false): void { // Don't play sounds if deafened (except deafen/undeafen sounds for feedback) - if (this.isDeafened && - soundType !== CallSoundType.Deafen && - soundType !== CallSoundType.Undeafen) { + if ( + this.isDeafened && + soundType !== CallSoundType.Deafen && + soundType !== CallSoundType.Undeafen + ) { return; } diff --git a/src/app/features/call/DockedCallContent.tsx b/src/app/features/call/DockedCallContent.tsx index 0a4f5139..83950cd5 100644 --- a/src/app/features/call/DockedCallContent.tsx +++ b/src/app/features/call/DockedCallContent.tsx @@ -1,7 +1,7 @@ import React, { useEffect, useMemo, useState } from 'react'; import { Box, IconButton, Text, Tooltip, TooltipProvider, Scroll, color } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useCall } from './useCall'; import { ScreenShareItem, ScreenShareEntry } from './CallOverlay'; import { useRoomCallMembers } from './useRoomCallMembers'; @@ -69,7 +69,7 @@ export function DockedCallContent() { const { navigateRoom } = useRoomNavigate(); const [, setIsDocked] = useSetting(settingsAtom, 'isCallPanelDocked'); const setPendingDrag = useSetAtom(pendingUndockDragAtom); - + const unread = useRoomUnread(activeCall?.roomId ?? '', roomToUnreadAtom); const { callMembers } = useRoomCallMembers(activeCall?.roomId ?? ''); const myUserId = mx.getUserId() ?? ''; @@ -95,7 +95,8 @@ export function DockedCallContent() { remoteScreenTracks.forEach((trackInfo) => { const livekitId = trackInfo.participantId; const underscoreIndex = livekitId.lastIndexOf('_'); - const possibleDeviceId = underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId; + const possibleDeviceId = + underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId; const matchingMember = callMembers.find((m) => m.deviceId === possibleDeviceId); const matrixUserId = matchingMember?.userId ?? livekitId; @@ -111,7 +112,14 @@ export function DockedCallContent() { }); return shares; - }, [activeCall?.isScreenSharing, activeCall?.localScreenStream, activeCall?.remoteScreenTracks, activeCall?.roomId, callMembers, myUserId]); + }, [ + activeCall?.isScreenSharing, + activeCall?.localScreenStream, + activeCall?.remoteScreenTracks, + activeCall?.roomId, + callMembers, + myUserId, + ]); useEffect(() => { if (!activeCall || activeCall.state !== CallState.Connected) { @@ -137,10 +145,10 @@ export function DockedCallContent() { const isParticipantSpeaking = (userId: string): boolean => { if (!activeCall) return false; if (activeCall.activeSpeakers.has(userId)) return true; - + const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + return Array.from(activeCall.activeSpeakers).some((speakerId) => { const underscoreIndex = speakerId.lastIndexOf('_'); const deviceId = underscoreIndex > 0 ? speakerId.substring(0, underscoreIndex) : speakerId; @@ -154,10 +162,10 @@ export function DockedCallContent() { const isParticipantMuted = (userId: string): boolean => { if (!activeCall) return false; if (userId === myUserId) return activeCall.isMuted; - + const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + return Array.from(activeCall.mutedParticipants).some((mutedId) => { const underscoreIndex = mutedId.lastIndexOf('_'); const deviceId = underscoreIndex > 0 ? mutedId.substring(0, underscoreIndex) : mutedId; @@ -194,7 +202,7 @@ export function DockedCallContent() { const handleHeaderMouseDown = async (e: React.MouseEvent) => { // Don't start drag if clicking a button if ((e.target as HTMLElement).closest('button')) return; - + // Exit browser fullscreen if active before undocking if (document.fullscreenElement) { try { @@ -203,11 +211,11 @@ export function DockedCallContent() { // Fullscreen exit may fail } } - + // Get the header element to calculate offset const header = e.currentTarget as HTMLElement; const rect = header.getBoundingClientRect(); - + // Store the drag start position with mouse offset from panel edges setPendingDrag({ startX: e.clientX, @@ -216,7 +224,7 @@ export function DockedCallContent() { offsetY: e.clientY - rect.top, timestamp: Date.now(), }); - + // Undock immediately - the floating overlay will pick up the drag setIsDocked(false); }; @@ -235,30 +243,31 @@ export function DockedCallContent() {
{/* Header - drag to undock */} {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */} -
- + - {isConnecting ? 'Connecting...' : room?.name ?? 'Unknown Room'} + {isConnecting ? 'Connecting...' : (room?.name ?? 'Unknown Room')} {selectedRoomId === activeCall.roomId && ( Current Room} + tooltip={ + + Current Room + + } > {(triggerRef) => ( - )} @@ -276,13 +285,17 @@ export function DockedCallContent() { Go to Room} + tooltip={ + + Go to Room + + } > {(triggerRef) => ( - navigateRoom(activeCall.roomId)} - variant="Secondary" + navigateRoom(activeCall.roomId)} + variant="Secondary" size="300" > @@ -316,18 +329,19 @@ export function DockedCallContent() { {allParticipants.map((participantId) => { const avatarMxc = getMemberAvatarMxc(room, participantId); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined) : undefined; - const displayName = getMemberDisplayName(room, participantId) - ?? getMxIdLocalPart(participantId) - ?? participantId; + const displayName = + getMemberDisplayName(room, participantId) ?? + getMxIdLocalPart(participantId) ?? + participantId; const isMe = participantId === myUserId; const isMuted = isParticipantMuted(participantId); const isSpeaking = isParticipantSpeaking(participantId); - + return (
-
{isMuted && ( - + )}
); @@ -378,7 +388,11 @@ export function DockedCallContent() { {activeCall.isMuted ? 'Unmute' : 'Mute'}} + tooltip={ + + {activeCall.isMuted ? 'Unmute' : 'Mute'} + + } > {(triggerRef) => ( {activeCall.isDeafened ? 'Undeafen' : 'Deafen'}} + tooltip={ + + {activeCall.isDeafened ? 'Undeafen' : 'Deafen'} + + } > {(triggerRef) => ( {activeCall.isScreenSharing ? 'Stop Screen Share' : 'Share Screen'}} + tooltip={ + + {activeCall.isScreenSharing ? 'Stop Screen Share' : 'Share Screen'} + + } > {(triggerRef) => ( End Call} + tooltip={ + + End Call + + } > {(triggerRef) => ( - + )} diff --git a/src/app/features/call/DockedCallPanel.tsx b/src/app/features/call/DockedCallPanel.tsx index 0430b86f..7b511cc4 100644 --- a/src/app/features/call/DockedCallPanel.tsx +++ b/src/app/features/call/DockedCallPanel.tsx @@ -10,11 +10,11 @@ import * as css from './CallOverlay.css'; */ export function DockedCallPanel() { const isCallDockedRight = useIsCallDockedRight(); - + if (!isCallDockedRight) { return null; } - + return ( <> diff --git a/src/app/features/call/IncomingCallNotification.tsx b/src/app/features/call/IncomingCallNotification.tsx index 7a4a1341..4655369a 100644 --- a/src/app/features/call/IncomingCallNotification.tsx +++ b/src/app/features/call/IncomingCallNotification.tsx @@ -44,18 +44,21 @@ function isDirectOrSmallGroup(room: Room): boolean { * @param myUserId - The current user's ID * @returns Object with member IDs and earliest call start time */ -function getOtherCallMembersWithTime(room: Room, myUserId: string): { members: string[]; earliestTime: number } { +function getOtherCallMembersWithTime( + room: Room, + myUserId: string, +): { members: string[]; earliestTime: number } { const members: string[] = []; const now = Date.now(); let earliestTime = now; try { const stateEvents = room.currentState.getStateEvents(CALL_MEMBER_EVENT_TYPE); - + stateEvents.forEach((event) => { const content = event.getContent(); const userId = event.getStateKey(); - + if (!userId || userId === myUserId || !content['m.calls']) return; const calls = content['m.calls']; @@ -67,7 +70,7 @@ function getOtherCallMembersWithTime(room: Room, myUserId: string): { members: s devices.forEach((device) => { const expiresTs = device.expires_ts || 0; - + if (expiresTs > now && !members.includes(userId)) { members.push(userId); // Track event origin time to determine call age @@ -122,7 +125,7 @@ export function IncomingCallNotification() { const rooms = mx.getRooms(); const now = Date.now(); const MAX_CALL_AGE = 10000; // 10 seconds - + // Find the first room with an incoming call const incomingRoom = rooms.find((room) => { // Only monitor 1-1 DMs (exactly 2 members) @@ -131,11 +134,11 @@ export function IncomingCallNotification() { if (declinedRooms.has(room.roomId)) return false; const { members, earliestTime } = getOtherCallMembersWithTime(room, myUserId); if (members.length === 0) return false; - + // Skip if we've already seen this exact call session const lastSeenTime = seenCalls.get(room.roomId); if (lastSeenTime && lastSeenTime === earliestTime) return false; - + // Only show if the call is fresh (less than 10 seconds old) const callAge = now - earliestTime; return callAge < MAX_CALL_AGE; @@ -157,35 +160,38 @@ export function IncomingCallNotification() { /** * Handles state events for call member changes */ - const handleStateEvent = useCallback((event: MatrixEvent) => { - if (event.getType() === CALL_MEMBER_EVENT_TYPE) { - // Clear declined status and seen calls if call ended in that room - const roomId = event.getRoomId(); - if (roomId) { - const room = mx.getRoom(roomId); - if (room) { - const myUserId = mx.getUserId(); - if (myUserId) { - const members = getOtherCallMembers(room, myUserId); - if (members.length === 0) { - // Call ended, clear tracking - setDeclinedRooms((prev) => { - const newSet = new Set(prev); - newSet.delete(roomId); - return newSet; - }); - setSeenCalls((prev) => { - const newMap = new Map(prev); - newMap.delete(roomId); - return newMap; - }); + const handleStateEvent = useCallback( + (event: MatrixEvent) => { + if (event.getType() === CALL_MEMBER_EVENT_TYPE) { + // Clear declined status and seen calls if call ended in that room + const roomId = event.getRoomId(); + if (roomId) { + const room = mx.getRoom(roomId); + if (room) { + const myUserId = mx.getUserId(); + if (myUserId) { + const members = getOtherCallMembers(room, myUserId); + if (members.length === 0) { + // Call ended, clear tracking + setDeclinedRooms((prev) => { + const newSet = new Set(prev); + newSet.delete(roomId); + return newSet; + }); + setSeenCalls((prev) => { + const newMap = new Map(prev); + newMap.delete(roomId); + return newMap; + }); + } } } } + checkForIncomingCalls(); } - checkForIncomingCalls(); - } - }, [checkForIncomingCalls, declinedRooms, mx]); + }, + [checkForIncomingCalls, declinedRooms, mx], + ); // Set up event listeners useEffect(() => { @@ -205,15 +211,27 @@ export function IncomingCallNotification() { if (incomingCall) { // Mark this call as seen so we don't notify again setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime)); - + const callAge = Date.now() - incomingCall.startTime; const MAX_CALL_AGE_FOR_SOUND = 15000; // 15 seconds - + if (callAge < MAX_CALL_AGE_FOR_SOUND) { getCallSounds().playSound(CallSoundType.CallDialing, true); - console.log('🔔 Incoming call from room:', incomingCall.roomName, '(age:', Math.round(callAge / 1000), 's)'); + console.log( + '🔔 Incoming call from room:', + incomingCall.roomName, + '(age:', + Math.round(callAge / 1000), + 's)', + ); } else { - console.log('📞 Incoming call too old for sound:', incomingCall.roomName, '(age:', Math.round(callAge / 1000), 's)'); + console.log( + '📞 Incoming call too old for sound:', + incomingCall.roomName, + '(age:', + Math.round(callAge / 1000), + 's)', + ); getCallSounds().stopDialingLoop(); } } else { @@ -230,7 +248,7 @@ export function IncomingCallNotification() { */ const handleAccept = useCallback(async () => { if (!incomingCall) return; - + getCallSounds().stopDialingLoop(); setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime)); try { @@ -245,7 +263,7 @@ export function IncomingCallNotification() { */ const handleDecline = useCallback(() => { if (!incomingCall) return; - + getCallSounds().stopDialingLoop(); setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime)); setDeclinedRooms((prev) => new Set(prev).add(incomingCall.roomId)); @@ -260,7 +278,7 @@ export function IncomingCallNotification() { const room = mx.getRoom(incomingCall.roomId); const firstCaller = incomingCall.callerIds[0]; const isGroupCall = room ? room.getJoinedMemberCount() > 2 : false; - + /** * Gets the display name for a user */ @@ -320,18 +338,10 @@ export function IncomingCallNotification() {
- + - + diff --git a/src/app/features/call/RemoteCursorOverlay.tsx b/src/app/features/call/RemoteCursorOverlay.tsx index fb60c482..61117471 100644 --- a/src/app/features/call/RemoteCursorOverlay.tsx +++ b/src/app/features/call/RemoteCursorOverlay.tsx @@ -22,7 +22,7 @@ interface RemoteCursorOverlayProps { */ function resolveParticipantUserId( livekitIdentity: string, - callMembers: { userId: string; deviceId: string }[] + callMembers: { userId: string; deviceId: string }[], ): string { const underscoreIndex = livekitIdentity.lastIndexOf('_'); const possibleDeviceId = @@ -60,10 +60,7 @@ function CursorDot({ opacity: cursor.visible ? 1 : 0, }} /> -
+
{displayName}
@@ -100,7 +97,7 @@ export function RemoteCursorOverlay({ shareId, roomId }: RemoteCursorOverlayProp }); const remoteCursors = Array.from(cursors.entries()).filter( - ([participantId]) => participantId !== myIdentity + ([participantId]) => participantId !== myIdentity, ); if (remoteCursors.length === 0) return null; diff --git a/src/app/features/call/SidebarDockedCallPanel.tsx b/src/app/features/call/SidebarDockedCallPanel.tsx index 5f6d304b..ceea675e 100644 --- a/src/app/features/call/SidebarDockedCallPanel.tsx +++ b/src/app/features/call/SidebarDockedCallPanel.tsx @@ -1,7 +1,7 @@ import React, { useEffect, useState } from 'react'; import { Box, IconButton, Scroll, Text, Tooltip, TooltipProvider, color } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useCall } from './useCall'; import { useRoomCallMembers } from './useRoomCallMembers'; import { CallState } from './types'; @@ -69,10 +69,10 @@ export function SidebarDockedCallPanel() { const isParticipantSpeaking = (userId: string): boolean => { if (!activeCall) return false; if (activeCall.activeSpeakers.has(userId)) return true; - + const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + return Array.from(activeCall.activeSpeakers).some((speakerId) => { const underscoreIndex = speakerId.lastIndexOf('_'); const deviceId = underscoreIndex > 0 ? speakerId.substring(0, underscoreIndex) : speakerId; @@ -86,10 +86,10 @@ export function SidebarDockedCallPanel() { const isParticipantMuted = (userId: string): boolean => { if (!activeCall) return false; if (userId === myUserId) return activeCall.isMuted; - + const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + return Array.from(activeCall.mutedParticipants).some((mutedId) => { const underscoreIndex = mutedId.lastIndexOf('_'); const deviceId = underscoreIndex > 0 ? mutedId.substring(0, underscoreIndex) : mutedId; @@ -102,7 +102,7 @@ export function SidebarDockedCallPanel() { */ const handleHeaderMouseDown = async (e: React.MouseEvent) => { if ((e.target as HTMLElement).closest('button')) return; - + if (document.fullscreenElement) { try { await document.exitFullscreen(); @@ -110,10 +110,10 @@ export function SidebarDockedCallPanel() { // Ignore } } - + const header = e.currentTarget as HTMLElement; const rect = header.getBoundingClientRect(); - + setPendingDrag({ startX: e.clientX, startY: e.clientY, @@ -121,11 +121,16 @@ export function SidebarDockedCallPanel() { offsetY: e.clientY - rect.top, timestamp: Date.now(), }); - + setIsDocked(false); }; - if (!isCallDockedSidebar || !activeCall || activeCall.state === CallState.Idle || activeCall.state === CallState.Ended) { + if ( + !isCallDockedSidebar || + !activeCall || + activeCall.state === CallState.Idle || + activeCall.state === CallState.Ended + ) { return null; } @@ -138,14 +143,11 @@ export function SidebarDockedCallPanel() {
{/* Header - drag to undock */} {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */} -
+
- {isConnecting ? 'Connecting...' : room?.name ?? 'Call'} + {isConnecting ? 'Connecting...' : (room?.name ?? 'Call')} {selectedRoomId === activeCall.roomId && ( @@ -159,13 +161,17 @@ export function SidebarDockedCallPanel() { Go to Room} + tooltip={ + + Go to Room + + } > {(triggerRef) => ( - navigateRoom(activeCall.roomId)} - variant="Secondary" + navigateRoom(activeCall.roomId)} + variant="Secondary" size="300" > @@ -199,18 +205,19 @@ export function SidebarDockedCallPanel() { {allParticipants.map((participantId) => { const avatarMxc = getMemberAvatarMxc(room, participantId); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined) : undefined; - const displayName = getMemberDisplayName(room, participantId) - ?? getMxIdLocalPart(participantId) - ?? participantId; + const displayName = + getMemberDisplayName(room, participantId) ?? + getMxIdLocalPart(participantId) ?? + participantId; const isMe = participantId === myUserId; const isMuted = isParticipantMuted(participantId); const isSpeaking = isParticipantSpeaking(participantId); - + return (
-
(You)} - {isMuted && ( - - )} + {isMuted && }
); })} @@ -247,7 +252,11 @@ export function SidebarDockedCallPanel() { {activeCall.isMuted ? 'Unmute' : 'Mute'}} + tooltip={ + + {activeCall.isMuted ? 'Unmute' : 'Mute'} + + } > {(triggerRef) => ( {activeCall.isDeafened ? 'Undeafen' : 'Deafen'}} + tooltip={ + + {activeCall.isDeafened ? 'Undeafen' : 'Deafen'} + + } > {(triggerRef) => ( End Call} + tooltip={ + + End Call + + } > {(triggerRef) => ( - + )} diff --git a/src/app/features/call/useCall.ts b/src/app/features/call/useCall.ts index 6b0417d4..2fb5f440 100644 --- a/src/app/features/call/useCall.ts +++ b/src/app/features/call/useCall.ts @@ -2,7 +2,11 @@ import { createContext, useContext, useState, useCallback, useEffect, useMemo } import { useMatrixClient } from '../../hooks/useMatrixClient'; import { CallService } from './CallService'; import { ActiveCall, CallEvent, CallEventType, CallState, CallType } from './types'; -import { fetchWellKnownWithRTC, getLiveKitFocus, getLiveKitHomeserverPriority } from './useRtcConfig'; +import { + fetchWellKnownWithRTC, + getLiveKitFocus, + getLiveKitHomeserverPriority, +} from './useRtcConfig'; interface CallContextValue { callService: CallService | null; @@ -93,7 +97,7 @@ export function useCallService(): CallContextValue { userId, deviceId, }, - mx + mx, ); setCallService(service); @@ -105,14 +109,16 @@ export function useCallService(): CallContextValue { unsubscribe = service.on((event: CallEvent) => { // Update state for any event that might change the call state - if (event.type === CallEventType.StateChanged || - event.type === CallEventType.ScreenShareStarted || - event.type === CallEventType.ScreenShareStopped || - event.type === CallEventType.RemoteStreamAdded || - event.type === CallEventType.RemoteStreamRemoved || - event.type === CallEventType.ParticipantJoined || - event.type === CallEventType.ParticipantLeft || - event.type === CallEventType.SpeakersChanged) { + if ( + event.type === CallEventType.StateChanged || + event.type === CallEventType.ScreenShareStarted || + event.type === CallEventType.ScreenShareStopped || + event.type === CallEventType.RemoteStreamAdded || + event.type === CallEventType.RemoteStreamRemoved || + event.type === CallEventType.ParticipantJoined || + event.type === CallEventType.ParticipantLeft || + event.type === CallEventType.SpeakersChanged + ) { const newCall = service?.getActiveCall(); if (newCall) { // Deep copy Maps and Sets to ensure React detects changes @@ -152,7 +158,7 @@ export function useCallService(): CallContextValue { } await callService.startCall(roomId, callType); }, - [callService] + [callService], ); const endCall = useCallback(async () => { @@ -223,7 +229,18 @@ export function useCallService(): CallContextValue { toggleVideo, toggleScreenShare, }), - [callService, activeCall, callSupported, callSupportLoading, startCall, endCall, toggleMute, toggleDeafen, toggleVideo, toggleScreenShare] + [ + callService, + activeCall, + callSupported, + callSupportLoading, + startCall, + endCall, + toggleMute, + toggleDeafen, + toggleVideo, + toggleScreenShare, + ], ); } @@ -231,7 +248,14 @@ export function useCallService(): CallContextValue { * Hook to check if a call is active in a specific room */ export function useRoomCall(roomId: string) { - const { activeCall, startCall, endCall, callSupported: globalCallSupported, callSupportLoading: globalCallSupportLoading, callService } = useCall(); + const { + activeCall, + startCall, + endCall, + callSupported: globalCallSupported, + callSupportLoading: globalCallSupportLoading, + callService, + } = useCall(); const mx = useMatrixClient(); const [roomCallSupported, setRoomCallSupported] = useState(false); const [roomCallSupportLoading, setRoomCallSupportLoading] = useState(true); @@ -240,7 +264,7 @@ export function useRoomCall(roomId: string) { useEffect(() => { const checkRoomCallSupport = async () => { setRoomCallSupportLoading(true); - + const room = mx.getRoom(roomId); if (!room) { setRoomCallSupported(false); @@ -252,10 +276,13 @@ export function useRoomCall(roomId: string) { const homeserverPriority = getLiveKitHomeserverPriority( room, mx.getHomeserverUrl(), - mx.getSafeUserId() + mx.getSafeUserId(), ); - console.log(`Checking call support for room ${roomId}, homeserver priority:`, homeserverPriority); + console.log( + `Checking call support for room ${roomId}, homeserver priority:`, + homeserverPriority, + ); // Check each homeserver in priority order for (const homeserver of homeserverPriority) { @@ -263,10 +290,10 @@ export function useRoomCall(roomId: string) { console.log(`Fetching well-known from ${homeserver}...`); const wellKnown = await fetchWellKnownWithRTC(homeserver); console.log(`Well-known response from ${homeserver}:`, wellKnown); - + const livekitFocus = getLiveKitFocus(wellKnown); console.log(`LiveKit focus from ${homeserver}:`, livekitFocus); - + if (livekitFocus) { console.log(`Call support found for room ${roomId} on homeserver: ${homeserver}`); setRoomCallSupported(true); @@ -290,29 +317,32 @@ export function useRoomCall(roomId: string) { const isInCall = activeCall?.roomId === roomId; const callState = isInCall ? activeCall.state : CallState.Idle; - const isUsingRemoteHomeserver = isInCall ? callService?.isUsingRemoteHomeserver() ?? false : false; + const isUsingRemoteHomeserver = isInCall + ? (callService?.isUsingRemoteHomeserver() ?? false) + : false; // Check if a remote homeserver WOULD be used (pre-call check) const wouldUseRemoteHomeserver = useMemo(() => { if (isInCall) return isUsingRemoteHomeserver; - + const room = mx.getRoom(roomId); if (!room) return false; - + const homeserverPriority = getLiveKitHomeserverPriority( room, mx.getHomeserverUrl(), - mx.getSafeUserId() + mx.getSafeUserId(), ); - + // Check if first priority is different from user's homeserver - const userHomeserverDomain = mx.getHomeserverUrl() + const userHomeserverDomain = mx + .getHomeserverUrl() .replace('https://', '') .replace('http://', ''); const firstPriorityDomain = homeserverPriority[0] ?.replace('https://', '') .replace('http://', ''); - + return firstPriorityDomain !== userHomeserverDomain; }, [isInCall, isUsingRemoteHomeserver, mx, roomId]); diff --git a/src/app/features/call/useDockedCall.ts b/src/app/features/call/useDockedCall.ts index 8fe18e7d..9f05b0a2 100644 --- a/src/app/features/call/useDockedCall.ts +++ b/src/app/features/call/useDockedCall.ts @@ -10,10 +10,11 @@ import { CallState } from './types'; export function useIsCallDocked(): boolean { const { activeCall } = useCall(); const [isDocked] = useSetting(settingsAtom, 'isCallPanelDocked'); - - const hasActiveCall = activeCall && + + const hasActiveCall = + activeCall && (activeCall.state === CallState.Connecting || activeCall.state === CallState.Connected); - + return Boolean(hasActiveCall && isDocked); } @@ -23,7 +24,7 @@ export function useIsCallDocked(): boolean { export function useIsCallDockedRight(): boolean { const isCallDocked = useIsCallDocked(); const [dockPosition] = useSetting(settingsAtom, 'callPanelDockPosition'); - + return isCallDocked && dockPosition === 'right'; } @@ -33,7 +34,7 @@ export function useIsCallDockedRight(): boolean { export function useIsCallDockedSidebar(): boolean { const isCallDocked = useIsCallDocked(); const [dockPosition] = useSetting(settingsAtom, 'callPanelDockPosition'); - + return isCallDocked && dockPosition === 'sidebar'; } diff --git a/src/app/features/call/useRemoteCursor.ts b/src/app/features/call/useRemoteCursor.ts index bb61a30a..1db7c014 100644 --- a/src/app/features/call/useRemoteCursor.ts +++ b/src/app/features/call/useRemoteCursor.ts @@ -70,7 +70,7 @@ export function useSendCursor(shareId: string) { }); } }, - [callService] + [callService], ); /** @@ -87,7 +87,7 @@ export function useSendCursor(shareId: string) { sendCursorData({ x, y, visible: true, shareId }); }, - [showRemoteCursor, sendCursorData, shareId] + [showRemoteCursor, sendCursorData, shareId], ); /** @@ -127,7 +127,7 @@ export function useReceiveCursors(shareId: string): Map { if (!participant) return; // Only process cursor messages by topic diff --git a/src/app/features/call/useRoomCallMembers.ts b/src/app/features/call/useRoomCallMembers.ts index b6ffde36..5293db9d 100644 --- a/src/app/features/call/useRoomCallMembers.ts +++ b/src/app/features/call/useRoomCallMembers.ts @@ -25,11 +25,11 @@ export function getActiveCallMembers(room: Room): CallMember[] { try { const stateEvents = room.currentState.getStateEvents(CALL_MEMBER_EVENT_TYPE); - + stateEvents.forEach((event) => { const content = event.getContent(); const userId = event.getStateKey(); - + if (!userId || !content['m.calls']) return; const calls = content['m.calls']; @@ -41,7 +41,7 @@ export function getActiveCallMembers(room: Room): CallMember[] { devices.forEach((device) => { const expiresTs = device.expires_ts || 0; - + // Check if the call membership is still valid (not expired) if (expiresTs > now) { members.push({ diff --git a/src/app/features/call/useRtcConfig.ts b/src/app/features/call/useRtcConfig.ts index 84d74ced..4ac8bf61 100644 --- a/src/app/features/call/useRtcConfig.ts +++ b/src/app/features/call/useRtcConfig.ts @@ -2,8 +2,7 @@ import { useCallback } from 'react'; import { Room } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { LiveKitFocus, LiveKitJWTResponse, OpenIdToken, WellKnownWithRTC } from './types'; -import { getMxIdServer } from '../../utils/matrix'; -import { guessDmRoomUserId } from '../../utils/matrix'; +import { getMxIdServer, guessDmRoomUserId } from '../../utils/matrix'; import { getActiveCallMembers } from './useRoomCallMembers'; /** @@ -26,21 +25,23 @@ function getRoomServer(roomId: string): string | undefined { export function getLiveKitHomeserverPriority( room: Room, userHomeserver: string, - myUserId: string + myUserId: string, ): string[] { const servers: string[] = []; const memberCount = room.getMembers().length; const isDM = memberCount <= 2; - + console.log(`[getLiveKitHomeserverPriority] Room: ${room.roomId}`); console.log(`[getLiveKitHomeserverPriority] Member count: ${memberCount}, isDM: ${isDM}`); console.log(`[getLiveKitHomeserverPriority] User homeserver: ${userHomeserver}`); - + // Check for active call members const activeCallMembers = getActiveCallMembers(room); const hasActiveCall = activeCallMembers.length > 0; - console.log(`[getLiveKitHomeserverPriority] Active call members: ${activeCallMembers.length}, hasActiveCall: ${hasActiveCall}`); + console.log( + `[getLiveKitHomeserverPriority] Active call members: ${activeCallMembers.length}, hasActiveCall: ${hasActiveCall}`, + ); if (hasActiveCall) { // Joining existing call - prioritize room's homeserver (where call is hosted) @@ -49,13 +50,13 @@ export function getLiveKitHomeserverPriority( if (roomServer) { servers.push(`https://${roomServer}`); } - + // Add user's homeserver as fallback const userDomain = userHomeserver.replace('https://', '').replace('http://', ''); if (!roomServer || roomServer !== userDomain) { servers.push(userHomeserver); } - + // For DMs, also try other member's homeserver if (isDM) { const otherUserId = guessDmRoomUserId(room, myUserId); @@ -72,7 +73,7 @@ export function getLiveKitHomeserverPriority( console.log(`[getLiveKitHomeserverPriority] DM path - user homeserver first`); // For DMs: user's homeserver first, then other member's homeserver servers.push(userHomeserver); - + const otherUserId = guessDmRoomUserId(room, myUserId); console.log(`[getLiveKitHomeserverPriority] Other user ID: ${otherUserId}`); if (otherUserId && otherUserId !== myUserId) { @@ -91,10 +92,12 @@ export function getLiveKitHomeserverPriority( if (roomServer) { servers.push(`https://${roomServer}`); } - + // Fallback to user's homeserver if different const userDomain = userHomeserver.replace('https://', '').replace('http://', ''); - console.log(`[getLiveKitHomeserverPriority] User domain: ${userDomain}, room server: ${roomServer}`); + console.log( + `[getLiveKitHomeserverPriority] User domain: ${userDomain}, room server: ${roomServer}`, + ); if (!roomServer || roomServer !== userDomain) { servers.push(userHomeserver); } @@ -113,7 +116,7 @@ export function getLiveKitHomeserverPriority( export function getLiveKitFocus(wellKnown: WellKnownWithRTC): LiveKitFocus | undefined { const rtcFoci = wellKnown['org.matrix.msc4143.rtc_foci']; console.log(`[getLiveKitFocus] rtcFoci from well-known:`, rtcFoci); - + if (!rtcFoci || !Array.isArray(rtcFoci)) { console.log(`[getLiveKitFocus] No rtc_foci found or not an array`); return undefined; @@ -131,8 +134,9 @@ export function getLiveKitFocus(wellKnown: WellKnownWithRTC): LiveKitFocus | und */ export async function fetchWellKnownWithRTC(baseUrl: string): Promise { // In development mode (localhost), use CORS proxy to avoid CORS issues - const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; - + const isDev = + window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; + let wellKnownUrl: string; if (isDev) { // Extract hostname from baseUrl for proxy @@ -165,14 +169,18 @@ export async function fetchWellKnownWithRTC(baseUrl: string): Promise { // In development mode (localhost), use CORS proxy to avoid CORS issues - const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; - + const isDev = + window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; + let url: string; if (isDev) { - const hostname = homeserverBaseUrl.replace('https://', '').replace('http://', '').replace(/\/$/, ''); + const hostname = homeserverBaseUrl + .replace('https://', '') + .replace('http://', '') + .replace(/\/$/, ''); url = `/_matrix-cors-proxy/${hostname}/_matrix/client/v3/user/${encodeURIComponent(userId)}/openid/request_token`; } else { url = `${homeserverBaseUrl}/_matrix/client/v3/user/${encodeURIComponent(userId)}/openid/request_token`; @@ -209,7 +217,7 @@ export async function fetchLiveKitJWT( roomId: string, userId: string, deviceId: string, - openIdToken: OpenIdToken + openIdToken: OpenIdToken, ): Promise { // Generate a unique member ID for this participant (used for identity, not room assignment) const memberId = `${deviceId}_${Date.now()}`; @@ -220,14 +228,15 @@ export async function fetchLiveKitJWT( const slotId = 'm.call'; // In development mode (localhost), use CORS proxy to avoid CORS issues - const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; - + const isDev = + window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; + let url: string; if (isDev) { // Extract hostname and path from livekitServiceUrl const urlObj = new URL(livekitServiceUrl); - const hostname = urlObj.hostname; - const pathname = urlObj.pathname; + const { hostname } = urlObj; + const { pathname } = urlObj; url = `/_matrix-cors-proxy/${hostname}${pathname}`; } else { url = livekitServiceUrl; @@ -274,34 +283,34 @@ export async function fetchLiveKitJWTFromServers( roomId: string, userId: string, deviceId: string, - accessToken: string + accessToken: string, ): Promise<{ jwt: LiveKitJWTResponse; homeserver: string } | null> { for (const homeserver of homeservers) { try { console.log(`Trying LiveKit JWT from homeserver: ${homeserver}`); - + // Fetch well-known from this homeserver const wellKnown = await fetchWellKnownWithRTC(homeserver); const livekitFocus = getLiveKitFocus(wellKnown); - + if (!livekitFocus) { console.log(`No LiveKit config on ${homeserver}, trying next...`); continue; } - + // Always get OpenID token from user's own homeserver // (Can't use access token on remote homeserver) const openIdToken = await requestOpenIdToken(userHomeserver, userId, accessToken); - + // Exchange for LiveKit JWT const jwt = await fetchLiveKitJWT( livekitFocus.livekit_service_url, roomId, userId, deviceId, - openIdToken + openIdToken, ); - + console.log(`Successfully got LiveKit JWT from ${homeserver}`); return { jwt, homeserver }; } catch (error) { @@ -309,7 +318,7 @@ export async function fetchLiveKitJWTFromServers( // Continue to next homeserver } } - + console.error('Failed to get LiveKit JWT from any homeserver'); return null; } @@ -348,9 +357,15 @@ export function useRtcConfig() { const openIdToken = await requestOpenIdToken(baseUrl, userId, accessToken); // Exchange for LiveKit JWT - return fetchLiveKitJWT(livekitFocus.livekit_service_url, roomId, userId, deviceId, openIdToken); + return fetchLiveKitJWT( + livekitFocus.livekit_service_url, + roomId, + userId, + deviceId, + openIdToken, + ); }, - [mx] + [mx], ); const isCallSupported = useCallback(async (): Promise => { diff --git a/src/app/features/common-settings/developer-tools/DevelopTools.tsx b/src/app/features/common-settings/developer-tools/DevelopTools.tsx index c584befe..12e549c3 100644 --- a/src/app/features/common-settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/common-settings/developer-tools/DevelopTools.tsx @@ -1,7 +1,23 @@ import React, { useCallback, useMemo, useState } from 'react'; -import { Box, Text, IconButton, Scroll, Switch, Button, MenuItem, config, color, TextArea, Dialog, Overlay, OverlayBackdrop, OverlayCenter, Modal } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + IconButton, + Scroll, + Switch, + Button, + MenuItem, + config, + color, + TextArea, + Dialog, + Overlay, + OverlayBackdrop, + OverlayCenter, + Modal, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../styles.css'; @@ -54,7 +70,10 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { const newestEvent = liveEvents.length > 0 ? liveEvents[liveEvents.length - 1] : null; // Get power level tags - const powerLevelTagsEvent = room.currentState.getStateEvents('in.cinny.room.power_level_tags', ''); + const powerLevelTagsEvent = room.currentState.getStateEvents( + 'in.cinny.room.power_level_tags', + '', + ); const powerLevelTags = powerLevelTagsEvent?.getContent(); const info: any = { @@ -122,7 +141,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { async (type, content) => { await mx.setRoomAccountData(room.roomId, type, content); }, - [mx, room.roomId] + [mx, room.roomId], ); if (accountDataType !== undefined) { diff --git a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx index 23736659..b2d3a4f4 100644 --- a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx +++ b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx @@ -1,6 +1,17 @@ import React, { useCallback, useRef, useState, FormEventHandler, useEffect } from 'react'; import { MatrixError } from 'matrix-js-sdk'; -import { Box, Chip, IconButton, Text, config, Button, Spinner, color, TextArea, Input } from 'folds'; +import { + Box, + Chip, + IconButton, + Text, + config, + Button, + Spinner, + color, + TextArea, + Input, +} from 'folds'; import { Icon, Icons } from '../../../components/icons'; import { Page, PageHeader } from '../../../components/page'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; @@ -28,7 +39,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro const [jsonError, setJSONError] = useState(); const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor( textAreaRef, - EDITOR_INTENT_SPACE_COUNT + EDITOR_INTENT_SPACE_COUNT, ); const [submitState, submit] = useAsyncCallback< @@ -43,8 +54,8 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro } return mx.sendEvent(room.roomId, evtType as any, evtContent); }, - [mx, room] - ) + [mx, room], + ), ); const submitting = submitState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx index c0505e68..9e5ff0f7 100644 --- a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx +++ b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx @@ -1,7 +1,18 @@ import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Box, Text, IconButton, Chip, Scroll, config, TextArea, color, Spinner, Button } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + IconButton, + Chip, + Scroll, + config, + TextArea, + color, + Spinner, + Button, +} from 'folds'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageHeader } from '../../../components/page'; import { SequenceCard } from '../../../components/sequence-card'; import { TextViewerContent } from '../../../components/text-viewer'; @@ -35,21 +46,21 @@ function StateEventEdit({ type, stateKey, content, requestClose }: StateEventEdi const defaultContentStr = useMemo( () => JSON.stringify(content, undefined, EDITOR_INTENT_SPACE_COUNT), - [content] + [content], ); const textAreaRef = useRef(null); const [jsonError, setJSONError] = useState(); const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor( textAreaRef, - EDITOR_INTENT_SPACE_COUNT + EDITOR_INTENT_SPACE_COUNT, ); const [submitState, submit] = useAsyncCallback( useCallback( (c) => mx.sendStateEvent(room.roomId, type as any, c, stateKey), - [mx, room, type, stateKey] - ) + [mx, room, type, stateKey], + ), ); const submitting = submitState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx index 92c88a05..bb1df3d3 100644 --- a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx +++ b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx @@ -1,7 +1,20 @@ import React, { FormEventHandler, useCallback, useMemo, useState } from 'react'; -import { Box, Text, Button, Avatar, AvatarFallback, toRem, config, Input, Spinner, color, IconButton, Menu } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + Button, + Avatar, + AvatarFallback, + toRem, + config, + Input, + Spinner, + color, + IconButton, + Menu, +} from 'folds'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { ImagePack, @@ -45,8 +58,8 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) { }; await mx.sendStateEvent(roomId, StateEvent.PoniesRoomEmotes as any, content, stateKey); }, - [mx, roomId] - ) + [mx, roomId], + ), ); const creating = addState.status === AsyncStatus.Loading; @@ -152,7 +165,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) { // eslint-disable-next-line no-await-in-loop await mx.sendStateEvent(room.roomId, StateEvent.PoniesRoomEmotes as any, {}, addr.stateKey); } - }, [mx, room, removedPacks]) + }, [mx, room, removedPacks]), ); const applyingChanges = applyState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/general/EmbedFilters.tsx b/src/app/features/common-settings/general/EmbedFilters.tsx index 4d332be0..90797bd2 100644 --- a/src/app/features/common-settings/general/EmbedFilters.tsx +++ b/src/app/features/common-settings/general/EmbedFilters.tsx @@ -1,5 +1,16 @@ import React, { FormEventHandler, useCallback, useState } from 'react'; -import { Box, Button, Chip, color, config, Input, Spinner, Text, Tooltip, TooltipProvider } from 'folds'; +import { + Box, + Button, + Chip, + color, + config, + Input, + Spinner, + Text, + Tooltip, + TooltipProvider, +} from 'folds'; import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; @@ -181,8 +192,8 @@ export function PersonalEmbedFilters() { async (newFilters: EmbedFiltersContent) => { await setFilters(newFilters); }, - [setFilters] - ) + [setFilters], + ), ); const saving = saveState.status === AsyncStatus.Loading; @@ -243,8 +254,8 @@ export function RoomWideEmbedFilters() { async (newFilters: EmbedFiltersContent) => { await setRoomWideFilters(newFilters); }, - [setRoomWideFilters] - ) + [setRoomWideFilters], + ), ); const saving = saveState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/general/RoomAddress.tsx b/src/app/features/common-settings/general/RoomAddress.tsx index 2f0bcd60..9cee3839 100644 --- a/src/app/features/common-settings/general/RoomAddress.tsx +++ b/src/app/features/common-settings/general/RoomAddress.tsx @@ -1,7 +1,19 @@ import React, { FormEventHandler, useCallback, useState } from 'react'; -import { Badge, Box, Button, Checkbox, Chip, color, config, Input, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Badge, + Box, + Button, + Checkbox, + Chip, + color, + config, + Input, + Spinner, + Text, + toRem, +} from 'folds'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { SettingTile } from '../../../components/setting-tile'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; @@ -31,7 +43,7 @@ export function RoomPublishedAddresses({ permissions }: RoomPublishedAddressesPr const canEditCanonical = permissions.stateEvent( StateEvent.RoomCanonicalAlias, - mx.getSafeUserId() + mx.getSafeUserId(), ); const [canonicalAlias, publishedAliases] = usePublishedAliases(room); @@ -228,8 +240,8 @@ function LocalAddressesList({ await removeLocalAlias(alias); } }, - [removeLocalAlias] - ) + [removeLocalAlias], + ), ); const [publishState, publish] = useAsyncCallback(publishAliases); const [unpublishState, unpublish] = useAsyncCallback(unpublishAliases); @@ -352,7 +364,7 @@ export function RoomLocalAddresses({ permissions }: { permissions: RoomPermissio const canEditCanonical = permissions.stateEvent( StateEvent.RoomCanonicalAlias, - mx.getSafeUserId() + mx.getSafeUserId(), ); const [expand, setExpand] = useState(false); diff --git a/src/app/features/common-settings/general/RoomEncryption.tsx b/src/app/features/common-settings/general/RoomEncryption.tsx index 219a30d9..224cf6a0 100644 --- a/src/app/features/common-settings/general/RoomEncryption.tsx +++ b/src/app/features/common-settings/general/RoomEncryption.tsx @@ -1,8 +1,22 @@ -import { Badge, Box, Button, color, config, Dialog, Header, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Badge, + Box, + Button, + color, + config, + Dialog, + Header, + IconButton, + Overlay, + OverlayBackdrop, + OverlayCenter, + Spinner, + Text, +} from 'folds'; import React, { useCallback, useState } from 'react'; import { MatrixError } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; import { SettingTile } from '../../../components/setting-tile'; @@ -34,7 +48,7 @@ export function RoomEncryption({ permissions }: RoomEncryptionProps) { await mx.sendStateEvent(room.roomId, StateEvent.RoomEncryption as any, { algorithm: ROOM_ENC_ALGO, }); - }, [mx, room.roomId]) + }, [mx, room.roomId]), ); const enabling = enableState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/general/RoomHistoryVisibility.tsx b/src/app/features/common-settings/general/RoomHistoryVisibility.tsx index 766fdc9b..d27456d6 100644 --- a/src/app/features/common-settings/general/RoomHistoryVisibility.tsx +++ b/src/app/features/common-settings/general/RoomHistoryVisibility.tsx @@ -1,9 +1,9 @@ import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react'; import { Button, color, config, Menu, MenuItem, PopOut, RectCords, Spinner, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { HistoryVisibility, MatrixError } from 'matrix-js-sdk'; import { RoomHistoryVisibilityEventContent } from 'matrix-js-sdk/lib/types'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; import { SettingTile } from '../../../components/setting-tile'; @@ -23,7 +23,7 @@ const useVisibilityStr = () => [HistoryVisibility.Shared]: 'All Messages', [HistoryVisibility.WorldReadable]: 'All Messages (Guests)', }), - [] + [], ); const useVisibilityMenu = () => @@ -34,7 +34,7 @@ const useVisibilityMenu = () => HistoryVisibility.Joined, HistoryVisibility.WorldReadable, ], - [] + [], ); type RoomHistoryVisibilityProps = { @@ -67,8 +67,8 @@ export function RoomHistoryVisibility({ permissions }: RoomHistoryVisibilityProp }; await mx.sendStateEvent(room.roomId, StateEvent.RoomHistoryVisibility as any, content); }, - [mx, room.roomId] - ) + [mx, room.roomId], + ), ); const submitting = submitState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/general/RoomJoinRules.tsx b/src/app/features/common-settings/general/RoomJoinRules.tsx index b9e75499..76ff51c9 100644 --- a/src/app/features/common-settings/general/RoomJoinRules.tsx +++ b/src/app/features/common-settings/general/RoomJoinRules.tsx @@ -115,8 +115,8 @@ export function RoomJoinRules({ permissions }: RoomJoinRulesProps) { if (allow.length > 0) c.allow = allow; await mx.sendStateEvent(room.roomId, StateEvent.RoomJoinRules as any, c); }, - [mx, room, space, subspaces, roomIdToParents] - ) + [mx, room, space, subspaces, roomIdToParents], + ), ); const submitting = submitState.status === AsyncStatus.Loading; diff --git a/src/app/features/common-settings/general/RoomProfile.tsx b/src/app/features/common-settings/general/RoomProfile.tsx index 406a191a..33146154 100644 --- a/src/app/features/common-settings/general/RoomProfile.tsx +++ b/src/app/features/common-settings/general/RoomProfile.tsx @@ -1,10 +1,10 @@ import { Avatar, Box, Button, Chip, color, Input, Spinner, Text, TextArea } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import React, { FormEventHandler, useCallback, useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import Linkify from 'linkify-react'; import classNames from 'classnames'; import { JoinRule, MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; import { useRoom } from '../../../hooks/useRoom'; @@ -56,7 +56,7 @@ export function RoomProfileEdit({ const [roomAvatar, setRoomAvatar] = useState(avatar); const avatarUrl = roomAvatar - ? mxcUrlToHttp(mx, roomAvatar, useAuthentication) ?? undefined + ? (mxcUrlToHttp(mx, roomAvatar, useAuthentication) ?? undefined) : undefined; const [imageFile, setImageFile] = useState(); @@ -93,8 +93,8 @@ export function RoomProfileEdit({ await mx.sendStateEvent(room.roomId, StateEvent.RoomTopic as any, { topic: roomTopic }); } }, - [mx, room.roomId] - ) + [mx, room.roomId], + ), ); const submitting = submitState.status === AsyncStatus.Loading; @@ -117,7 +117,7 @@ export function RoomProfileEdit({ submit( roomAvatar === avatar ? undefined : roomAvatar || null, roomName === name ? undefined : roomName, - roomTopic === topic ? undefined : roomTopic + roomTopic === topic ? undefined : roomTopic, ).then(() => { if (alive()) { onClose(); @@ -269,7 +269,7 @@ export function RoomProfile({ permissions }: RoomProfileProps) { const canEdit = canEditAvatar || canEditName || canEditTopic; const avatarUrl = avatar - ? mxcUrlToHttp(mx, avatar, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatar, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const [edit, setEdit] = useState(false); diff --git a/src/app/features/common-settings/general/RoomPublish.tsx b/src/app/features/common-settings/general/RoomPublish.tsx index ce014210..b38f515f 100644 --- a/src/app/features/common-settings/general/RoomPublish.tsx +++ b/src/app/features/common-settings/general/RoomPublish.tsx @@ -23,7 +23,7 @@ export function RoomPublish({ permissions }: RoomPublishProps) { const canEditCanonical = permissions.stateEvent( StateEvent.RoomCanonicalAlias, - mx.getSafeUserId() + mx.getSafeUserId(), ); const joinRuleEvent = useStateEvent(room, StateEvent.RoomJoinRules); const content = joinRuleEvent?.getContent(); diff --git a/src/app/features/common-settings/general/RoomUpgrade.tsx b/src/app/features/common-settings/general/RoomUpgrade.tsx index e23f5d17..1802a5ef 100644 --- a/src/app/features/common-settings/general/RoomUpgrade.tsx +++ b/src/app/features/common-settings/general/RoomUpgrade.tsx @@ -1,9 +1,22 @@ import React, { useCallback, useEffect, useState } from 'react'; -import { Button, color, Spinner, Text, Overlay, OverlayBackdrop, OverlayCenter, Dialog, Header, config, Box, IconButton } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Button, + color, + Spinner, + Text, + Overlay, + OverlayBackdrop, + OverlayCenter, + Dialog, + Header, + config, + Box, + IconButton, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { MatrixError, Method } from 'matrix-js-sdk'; import { RoomTombstoneEventContent } from 'matrix-js-sdk/lib/types'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../../room-settings/styles.css'; import { SettingTile } from '../../../components/setting-tile'; @@ -52,8 +65,8 @@ function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { additional_creators: newAdditionalCreators, }); }, - [mx, room] - ) + [mx, room], + ), ); const upgrading = upgradeState.status === AsyncStatus.Loading; @@ -154,14 +167,14 @@ export function RoomUpgrade({ permissions, requestClose }: RoomUpgradeProps) { const { navigateRoom, navigateSpace } = useRoomNavigate(); const createContent = useStateEvent( room, - StateEvent.RoomCreate + StateEvent.RoomCreate, )?.getContent(); const roomVersion = createContent?.room_version ?? '1'; const predecessorRoomId = createContent?.predecessor?.room_id; const tombstoneContent = useStateEvent( room, - StateEvent.RoomTombstone + StateEvent.RoomTombstone, )?.getContent(); const replacementRoom = tombstoneContent?.replacement_room; diff --git a/src/app/features/common-settings/members/Members.tsx b/src/app/features/common-settings/members/Members.tsx index c86dd15f..2adb09d1 100644 --- a/src/app/features/common-settings/members/Members.tsx +++ b/src/app/features/common-settings/members/Members.tsx @@ -6,10 +6,22 @@ import React, { useRef, useState, } from 'react'; -import { Box, Chip, config, IconButton, Input, PopOut, RectCords, Scroll, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Chip, + config, + IconButton, + Input, + PopOut, + RectCords, + Scroll, + Spinner, + Text, + toRem, +} from 'folds'; import { useVirtualizer } from '@tanstack/react-virtual'; import { RoomMember } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { useRoom } from '../../../hooks/useRoom'; import { useRoomMembers } from '../../../hooks/useRoomMembers'; @@ -92,13 +104,13 @@ export function Members({ requestClose }: MembersProps) { .filter(membershipFilter.filterFn) .sort(memberSort.sortFn) .sort(memberPowerSort), - [members, membershipFilter, memberSort, memberPowerSort] + [members, membershipFilter, memberSort, memberPowerSort], ); const [result, search, resetSearch] = useAsyncSearch( sortedMembers, getRoomMemberStr, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); if (!result && searchInputRef.current?.value) search(searchInputRef.current.value); @@ -117,9 +129,9 @@ export function Members({ requestClose }: MembersProps) { if (evt.target.value) search(evt.target.value); else resetSearch(); }, - [search, resetSearch] + [search, resetSearch], ), - { wait: 200 } + { wait: 200 }, ); const handleSearchReset = () => { @@ -212,7 +224,7 @@ export function Members({ requestClose }: MembersProps) { onClick={ ((evt) => setAnchor( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } variant="SurfaceVariant" @@ -244,7 +256,7 @@ export function Members({ requestClose }: MembersProps) { onClick={ ((evt) => setAnchor( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } variant="SurfaceVariant" diff --git a/src/app/features/common-settings/permissions/PermissionGroups.tsx b/src/app/features/common-settings/permissions/PermissionGroups.tsx index 841729a2..3de093d4 100644 --- a/src/app/features/common-settings/permissions/PermissionGroups.tsx +++ b/src/app/features/common-settings/permissions/PermissionGroups.tsx @@ -1,8 +1,8 @@ /* eslint-disable react/no-array-index-key */ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { Badge, Box, Button, Chip, config, Menu, Spinner, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { produce } from 'immer'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../styles.css'; import { SettingTile } from '../../../components/setting-tile'; @@ -43,7 +43,7 @@ export function PermissionGroups({ const maxPower = useMemo(() => Math.max(...getPowers(powerLevelTags)), [powerLevelTags]); const [permissionUpdate, setPermissionUpdate] = useState>( - new Map() + new Map(), ); useEffect(() => { @@ -55,7 +55,7 @@ export function PermissionGroups({ const handleChangePermission = ( location: PermissionLocation, newPower: number, - currentPower: number + currentPower: number, ) => { setPermissionUpdate((p) => { const up: typeof p = new Map(); @@ -78,16 +78,16 @@ export function PermissionGroups({ group.items.forEach((item) => { const power = getPermissionPower(powerLevels, item.location); applyPermissionPower(draftPowerLevels, item.location, power); - }) + }), ); permissionUpdate.forEach((power, location) => - applyPermissionPower(draftPowerLevels, location, power) + applyPermissionPower(draftPowerLevels, location, power), ); return draftPowerLevels; }); await mx.sendStateEvent(room.roomId, StateEvent.RoomPowerLevels as any, editedPowerLevels); - }, [mx, room, powerLevels, permissionUpdate, permissionGroups]) + }, [mx, room, powerLevels, permissionUpdate, permissionGroups]), ); const resetChanges = useCallback(() => { diff --git a/src/app/features/common-settings/permissions/PowersEditor.tsx b/src/app/features/common-settings/permissions/PowersEditor.tsx index a54421de..b2906ad6 100644 --- a/src/app/features/common-settings/permissions/PowersEditor.tsx +++ b/src/app/features/common-settings/permissions/PowersEditor.tsx @@ -1,8 +1,24 @@ import React, { FormEventHandler, MouseEventHandler, useCallback, useMemo, useState } from 'react'; -import { Box, Text, Chip, IconButton, Scroll, Button, Input, RectCords, PopOut, Menu, config, Spinner, toRem, TooltipProvider, Tooltip } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + Chip, + IconButton, + Scroll, + Button, + Input, + RectCords, + PopOut, + Menu, + config, + Spinner, + toRem, + TooltipProvider, + Tooltip, +} from 'folds'; import { HexColorPicker } from 'react-colorful'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { IPowerLevels } from '../../../hooks/usePowerLevels'; import { SequenceCard } from '../../../components/sequence-card'; @@ -211,7 +227,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) { onClick={ ((evt) => setCords( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } type="button" @@ -307,7 +323,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { return editedTags; }); }, - [powerLevelTags] + [powerLevelTags], ); const [applyState, applyChanges] = useAsyncCallback( @@ -317,7 +333,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { delete content[power]; }); await mx.sendStateEvent(room.roomId, StateEvent.PowerLevelTags as any, content); - }, [mx, room, powerLevelTags, editedPowerTags, deleted]) + }, [mx, room, powerLevelTags, editedPowerTags, deleted]), ); const resetChanges = useCallback(() => { diff --git a/src/app/features/create-chat/CreateChat.tsx b/src/app/features/create-chat/CreateChat.tsx index 95cebe49..546f464b 100644 --- a/src/app/features/create-chat/CreateChat.tsx +++ b/src/app/features/create-chat/CreateChat.tsx @@ -1,8 +1,8 @@ import { Box, Button, color, config, Input, Spinner, Switch, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import React, { FormEventHandler, useCallback, useState } from 'react'; import { ICreateRoomStateEvent, MatrixError, Preset, Visibility } from 'matrix-js-sdk'; import { useNavigate } from 'react-router-dom'; +import { Icon, Icons } from '../../components/icons'; import { SettingTile } from '../../components/setting-tile'; import { SequenceCard } from '../../components/sequence-card'; import { addRoomIdToMDirect, isUserId } from '../../utils/matrix'; @@ -46,8 +46,8 @@ export function CreateChat({ defaultUserId }: CreateChatProps) { return result.room_id; }, - [mx] - ) + [mx], + ), ); const loading = createState.status === AsyncStatus.Loading; const error = createState.status === AsyncStatus.Error ? createState.error : undefined; @@ -129,7 +129,7 @@ export function CreateChat({ defaultUserId }: CreateChatProps) { {error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED ? `Server rate-limited your request for ${millisecondsToMinutes( - (error.data.retry_after_ms as number | undefined) ?? 0 + (error.data.retry_after_ms as number | undefined) ?? 0, )} minutes!` : error.message} diff --git a/src/app/features/create-room/CreateRoom.tsx b/src/app/features/create-room/CreateRoom.tsx index 96a7d4fd..625d0730 100644 --- a/src/app/features/create-room/CreateRoom.tsx +++ b/src/app/features/create-room/CreateRoom.tsx @@ -54,7 +54,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP const allowRestricted = space && restrictedSupported(selectedRoomVersion); const [kind, setKind] = useState( - defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private + (defaultKind ?? allowRestricted) ? CreateRoomKind.Restricted : CreateRoomKind.Private, ); const allowAdditionalCreators = creatorsSupported(selectedRoomVersion); const { additionalCreators, addAdditionalCreator, removeAdditionalCreator } = @@ -77,7 +77,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP }; const [createState, create] = useAsyncCallback( - useCallback((data) => createRoom(mx, data), [mx]) + useCallback((data) => createRoom(mx, data), [mx]), ); const loading = createState.status === AsyncStatus.Loading; const error = createState.status === AsyncStatus.Error ? createState.error : undefined; @@ -292,7 +292,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP {error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED ? `Server rate-limited your request for ${millisecondsToMinutes( - (error.data.retry_after_ms as number | undefined) ?? 0 + (error.data.retry_after_ms as number | undefined) ?? 0, )} minutes!` : error.message} diff --git a/src/app/features/create-room/CreateRoomModal.tsx b/src/app/features/create-room/CreateRoomModal.tsx index 00f6c986..451bcd8c 100644 --- a/src/app/features/create-room/CreateRoomModal.tsx +++ b/src/app/features/create-room/CreateRoomModal.tsx @@ -1,8 +1,19 @@ import React, { useCallback } from 'react'; -import { Box, config, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + config, + Header, + IconButton, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Scroll, + Text, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom'; import { SpaceProvider } from '../../hooks/useSpace'; import { CreateRoomForm } from './CreateRoom'; @@ -49,7 +60,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { canonical: true, via: viaServers, }, - parentSubRoomId + parentSubRoomId, ); // Set m.space.child on the parent room pointing to this sub-room @@ -57,19 +68,17 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { parentSubRoomId, StateEvent.SpaceChild, { via: viaServers }, - newRoomId + newRoomId, ); // Copy parent's join_rules to the sub-room - const parentJoinRulesEvent = parentRoom.currentState.getStateEvents(StateEvent.RoomJoinRules, ''); + const parentJoinRulesEvent = parentRoom.currentState.getStateEvents( + StateEvent.RoomJoinRules, + '', + ); if (parentJoinRulesEvent) { const joinRulesContent = parentJoinRulesEvent.getContent(); - await mx.sendStateEvent( - newRoomId, - StateEvent.RoomJoinRules, - joinRulesContent, - '' - ); + await mx.sendStateEvent(newRoomId, StateEvent.RoomJoinRules, joinRulesContent, ''); } // Add new room to parent's sub-rooms list @@ -80,7 +89,12 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { children: [...currentChildren, newRoomId], }; // eslint-disable-next-line @typescript-eslint/no-explicit-any - await mx.sendStateEvent(parentSubRoomId, StateEvent.PaarrotSubRooms as any, newContent, ''); + await mx.sendStateEvent( + parentSubRoomId, + StateEvent.PaarrotSubRooms as any, + newContent, + '', + ); // Also add sub-room to parent's space(s) for joining/permissions // The UI will hide it from the top-level display and only show it nested @@ -101,14 +115,14 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { // eslint-disable-next-line @typescript-eslint/no-explicit-any StateEvent.SpaceChild as any, { via: spaceViaServers }, - newRoomId + newRoomId, ); } catch (spaceError) { // eslint-disable-next-line no-console console.warn(`Failed to add sub-room to space ${parentSpaceId}:`, spaceError); } } - }) + }), ); } } catch (error) { @@ -118,7 +132,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { } closeDialog(); }, - [mx, parentSubRoomId, parentRoom, roomToParents, closeDialog] + [mx, parentSubRoomId, parentRoom, roomToParents, closeDialog], ); const modalTitle = parentSubRoomId ? 'New Sub-Room' : 'New Room'; diff --git a/src/app/features/create-space/CreateSpace.tsx b/src/app/features/create-space/CreateSpace.tsx index ebb9a652..f9682b92 100644 --- a/src/app/features/create-space/CreateSpace.tsx +++ b/src/app/features/create-space/CreateSpace.tsx @@ -1,7 +1,28 @@ -import React, { FormEventHandler, MouseEventHandler, useCallback, useEffect, useState } from 'react'; +import React, { + FormEventHandler, + MouseEventHandler, + useCallback, + useEffect, + useState, +} from 'react'; import { MatrixError, Room } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; -import { Box, Button, Chip, color, config, Input, Menu, MenuItem, PopOut, RectCords, Spinner, Switch, Text, TextArea } from 'folds'; +import { + Box, + Button, + Chip, + color, + config, + Input, + Menu, + MenuItem, + PopOut, + RectCords, + Spinner, + Switch, + Text, + TextArea, +} from 'folds'; import { Icon, Icons } from '../../components/icons'; import { SettingTile } from '../../components/setting-tile'; import { SequenceCard } from '../../components/sequence-card'; @@ -62,7 +83,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor const allowRestricted = space && restrictedSupported(selectedRoomVersion); const [kind, setKind] = useState( - defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private + (defaultKind ?? allowRestricted) ? CreateRoomKind.Restricted : CreateRoomKind.Private, ); const allowAdditionalCreators = creatorsSupported(selectedRoomVersion); @@ -94,7 +115,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor }; const [createState, create] = useAsyncCallback( - useCallback((data) => createRoom(mx, data), [mx]) + useCallback((data) => createRoom(mx, data), [mx]), ); const loading = createState.status === AsyncStatus.Loading; const error = createState.status === AsyncStatus.Error ? createState.error : undefined; @@ -146,12 +167,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor }).then(async (roomId) => { if (spaceType === RoomType.Forum) { try { - await mx.sendStateEvent( - roomId, - StateEvent.PaarrotRoomKind, - { kind: 'forum_space' }, - '' - ); + await mx.sendStateEvent(roomId, StateEvent.PaarrotRoomKind, { kind: 'forum_space' }, ''); } catch (err) { // eslint-disable-next-line no-console console.warn('Failed to set forum space marker state event:', err); @@ -250,8 +266,8 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor )} {parentIsForum && ( - Creates a forum category (subspace). Add topics inside it with Add Topic after selecting the - category in the filter bar. + Creates a forum category (subspace). Add topics inside it with Add Topic after selecting + the category in the filter bar. )} @@ -362,7 +378,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor {error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED ? `Server rate-limited your request for ${millisecondsToMinutes( - (error.data.retry_after_ms as number | undefined) ?? 0 + (error.data.retry_after_ms as number | undefined) ?? 0, )} minutes!` : error.message} diff --git a/src/app/features/create-space/CreateSpaceModal.tsx b/src/app/features/create-space/CreateSpaceModal.tsx index 55e816b7..337e6916 100644 --- a/src/app/features/create-space/CreateSpaceModal.tsx +++ b/src/app/features/create-space/CreateSpaceModal.tsx @@ -1,7 +1,18 @@ import React from 'react'; -import { Box, config, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + config, + Header, + IconButton, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Scroll, + Text, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../components/icons'; import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom'; import { SpaceProvider } from '../../hooks/useSpace'; import { CreateSpaceForm } from './CreateSpace'; diff --git a/src/app/features/forum/ForumAuthorIdentity.tsx b/src/app/features/forum/ForumAuthorIdentity.tsx index 6734f5b5..a98de5fd 100644 --- a/src/app/features/forum/ForumAuthorIdentity.tsx +++ b/src/app/features/forum/ForumAuthorIdentity.tsx @@ -37,11 +37,13 @@ export function ForumAuthorIdentity({ const useAuthentication = useMediaAuthentication(); const mxc = room ? getMemberAvatarMxc(room, sender) : undefined; const avatarUrl = mxc - ? mxcUrlToHttp(mx, mxc, useAuthentication, compact ? 36 : 48, compact ? 36 : 48, 'crop') ?? - undefined + ? (mxcUrlToHttp(mx, mxc, useAuthentication, compact ? 36 : 48, compact ? 36 : 48, 'crop') ?? + undefined) : undefined; const name = - displayName || (room ? getMemberDisplayName(room, sender) : undefined) || matrixUserLocalpart(sender); + displayName || + (room ? getMemberDisplayName(room, sender) : undefined) || + matrixUserLocalpart(sender); const server = matrixUserServer(sender); const identityClass = compact @@ -57,9 +59,7 @@ export function ForumAuthorIdentity({ userId={sender} src={avatarUrl} alt={name} - renderFallback={() => ( - {name.slice(0, 1).toUpperCase()} - )} + renderFallback={() => {name.slice(0, 1).toUpperCase()}} /> diff --git a/src/app/features/forum/ForumBoardDetail.tsx b/src/app/features/forum/ForumBoardDetail.tsx index 658f09d1..e7b2788f 100644 --- a/src/app/features/forum/ForumBoardDetail.tsx +++ b/src/app/features/forum/ForumBoardDetail.tsx @@ -1,8 +1,8 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Scroll, Text, color } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import classNames from 'classnames'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { Page, PageContent } from '../../components/page'; import { ContainerColor } from '../../styles/ContainerColor.css'; @@ -31,7 +31,7 @@ export function ForumBoardDetail() { const topicSelected = Boolean(query.topic); const setActiveThreadId = useSetAtom( - activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId) + activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId), ); useEffect(() => { @@ -51,7 +51,7 @@ export function ForumBoardDetail() { const selectedThread = useMemo( () => threads.find((t) => t.eventId === selectedPostId), - [threads, selectedPostId] + [threads, selectedPostId], ); const handleReplySent = useCallback( @@ -60,12 +60,11 @@ export function ForumBoardDetail() { recordThreadReply(selectedPostId); } }, - [recordThreadReply, selectedPostId] + [recordThreadReply, selectedPostId], ); const showThread = Boolean(selectedPostId && activeTopicRoom); - const threadInitialPost = - optimisticPost?.eventId === selectedPostId ? optimisticPost : null; + const threadInitialPost = optimisticPost?.eventId === selectedPostId ? optimisticPost : null; const detailDropRef = useRef(null); return ( diff --git a/src/app/features/forum/ForumBoardView.tsx b/src/app/features/forum/ForumBoardView.tsx index 9cd9f86a..1f53c6c9 100644 --- a/src/app/features/forum/ForumBoardView.tsx +++ b/src/app/features/forum/ForumBoardView.tsx @@ -1,8 +1,8 @@ import React, { useCallback, useEffect, useRef } from 'react'; import { Box, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { Room } from 'matrix-js-sdk'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { Page, PageContent } from '../../components/page'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels'; @@ -48,7 +48,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) { const activeTopicRoom = activeTopicRoomId ? mx.getRoom(activeTopicRoomId) : null; const topicPowerLevels = usePowerLevels(activeTopicRoom ?? forumSpace); const setActiveThreadId = useSetAtom( - activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId) + activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId), ); const topicSelected = Boolean(query.topic || scope.topicRoomId); @@ -64,7 +64,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) { const getTopicRoom = useCallback( (roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null), - [mx] + [mx], ); const handlePostPublished = useCallback( @@ -73,7 +73,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) { selectPost(published.eventId, published.topicRoomId); detailScrollRef.current?.scrollIntoView({ behavior: 'smooth' }); }, - [insertThreadFromNewPost, selectPost] + [insertThreadFromNewPost, selectPost], ); const showComposer = Boolean(activeTopicRoom && (!selectedPostId || topicSelected)); @@ -129,7 +129,13 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) { ) : ( - + {topicSelected @@ -143,7 +149,10 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) { { @@ -126,7 +126,7 @@ export function ForumChatComposer({ anchor={ emojiBoardTab === undefined ? undefined - : emojiBtnRef.current?.getBoundingClientRect() ?? undefined + : (emojiBtnRef.current?.getBoundingClientRect() ?? undefined) } content={ { - setEmojiBoardTab((t) => { - if (t) { - if (!mobileOrTablet()) safeFocusEditor(editor); - return undefined; - } - return t; - }); - }} + requestClose={() => { + setEmojiBoardTab((t) => { + if (t) { + if (!mobileOrTablet()) safeFocusEditor(editor); + return undefined; + } + return t; + }); + }} /> } > diff --git a/src/app/features/forum/ForumEventContent.tsx b/src/app/features/forum/ForumEventContent.tsx index d317e43a..b2c5011c 100644 --- a/src/app/features/forum/ForumEventContent.tsx +++ b/src/app/features/forum/ForumEventContent.tsx @@ -33,8 +33,10 @@ export function ForumEventContent({ }, [event, eventId, timelineSet]); const getContent = useCallback( - () => editedEvent?.getContent()['m.new_content'] ?? event?.getContent() ?? { body, msgtype: 'm.text' }, - [editedEvent, event, body] + () => + editedEvent?.getContent()['m.new_content'] ?? + event?.getContent() ?? { body, msgtype: 'm.text' }, + [editedEvent, event, body], ); if (!event || event.getType() !== EventType.RoomMessage) { diff --git a/src/app/features/forum/ForumFeedSidebar.tsx b/src/app/features/forum/ForumFeedSidebar.tsx index e013a23a..720920bf 100644 --- a/src/app/features/forum/ForumFeedSidebar.tsx +++ b/src/app/features/forum/ForumFeedSidebar.tsx @@ -1,8 +1,7 @@ import React, { useCallback } from 'react'; import { Text, color } from 'folds'; import { useMatrixClient } from '../../hooks/useMatrixClient'; -import { usePowerLevels } from '../../hooks/usePowerLevels'; -import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels'; +import { usePowerLevels, PowerLevelsContextProvider } from '../../hooks/usePowerLevels'; import { useForumBoardContext } from './ForumBoardContext'; import { ForumFilterBar } from './ForumFilterBar'; import { ForumPostList } from './ForumPostList'; @@ -36,7 +35,7 @@ export function ForumFeedSidebar() { const getTopicRoom = useCallback( (roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null), - [mx] + [mx], ); const handlePostPublished = useCallback( @@ -44,7 +43,7 @@ export function ForumFeedSidebar() { insertThreadFromNewPost(published); selectPost(published.eventId, published.topicRoomId); }, - [insertThreadFromNewPost, selectPost] + [insertThreadFromNewPost, selectPost], ); return ( diff --git a/src/app/features/forum/ForumFilterBar.tsx b/src/app/features/forum/ForumFilterBar.tsx index 0da6ba32..07073718 100644 --- a/src/app/features/forum/ForumFilterBar.tsx +++ b/src/app/features/forum/ForumFilterBar.tsx @@ -36,7 +36,7 @@ export function ForumFilterBar({ onCategoryChange, }: ForumFilterBarProps) { const categoryTopics = query.category - ? sections.find((s) => s.title === query.category)?.topics ?? [] + ? (sections.find((s) => s.title === query.category)?.topics ?? []) : sections.flatMap((s) => s.topics); const [searchDraft, setSearchDraft] = useState(query.q || ''); @@ -47,7 +47,7 @@ export function ForumFilterBar({ const applySearch = useCallback(() => { const trimmed = searchDraft.trim(); - onQueryChange('q', trimmed ? trimmed : null); + onQueryChange('q', trimmed || null); }, [onQueryChange, searchDraft]); const handleSearchSubmit: FormEventHandler = (evt) => { diff --git a/src/app/features/forum/ForumMessageActions.tsx b/src/app/features/forum/ForumMessageActions.tsx index e43cf8d0..3811a067 100644 --- a/src/app/features/forum/ForumMessageActions.tsx +++ b/src/app/features/forum/ForumMessageActions.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, useEffect, useRef, useState } from 'react'; import { Box, IconButton, Menu, PopOut } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../components/icons'; import { EmojiBoard } from '../../components/emoji-board'; import { copyToClipboard } from '../../utils/dom'; import { PluginButtonSlot } from '../settings/plugins/PluginButtonSlot'; @@ -72,103 +72,103 @@ export function ForumMessageActions({ return ( - {canSendReaction && eventId && onReactionToggle && ( - { - onReactionToggle(eventId, key); - setEmojiBoardAnchor(undefined); - }} - onCustomEmojiSelect={(mxc, shortcode) => { - onReactionToggle(eventId, mxc, shortcode); - setEmojiBoardAnchor(undefined); - }} - requestClose={() => setEmojiBoardAnchor(undefined)} - /> - } + {canSendReaction && eventId && onReactionToggle && ( + { + onReactionToggle(eventId, key); + setEmojiBoardAnchor(undefined); + }} + onCustomEmojiSelect={(mxc, shortcode) => { + onReactionToggle(eventId, mxc, shortcode); + setEmojiBoardAnchor(undefined); + }} + requestClose={() => setEmojiBoardAnchor(undefined)} + /> + } + > + + + + + )} + + + + {canEdit && onEdit && ( - + - - )} - - - - {canEdit && onEdit && ( - - - - )} - {body && ( - copyToClipboard(body)} - variant="SurfaceVariant" - size="300" - radii="300" - aria-label="Copy raw text" - title="Copy raw text" - > - - - )} - {shiftHeld && canDelete && onDelete && ( - - - - )} - - {menu && ( - - - - )} + )} + {body && ( + copyToClipboard(body)} + variant="SurfaceVariant" + size="300" + radii="300" + aria-label="Copy raw text" + title="Copy raw text" + > + + + )} + {shiftHeld && canDelete && onDelete && ( + + + + )} + + {menu && ( + + + + )} ); diff --git a/src/app/features/forum/ForumMessageContextMenu.tsx b/src/app/features/forum/ForumMessageContextMenu.tsx index 37106cf4..52ff180e 100644 --- a/src/app/features/forum/ForumMessageContextMenu.tsx +++ b/src/app/features/forum/ForumMessageContextMenu.tsx @@ -1,15 +1,7 @@ import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react'; import FocusTrap from 'focus-trap-react'; import { MatrixEvent, Room } from 'matrix-js-sdk'; -import { - Box, - Line, - Menu, - MenuItem, - PopOut, - RectCords, - Text, -} from 'folds'; +import { Box, Line, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useSetting } from '../../state/hooks/settings'; @@ -94,7 +86,7 @@ export function ForumMessageContextMenu({ height: 0, }); }, - [disabled, mEvent] + [disabled, mEvent], ); const handleAddReactions: MouseEventHandler = useCallback(() => { diff --git a/src/app/features/forum/ForumNewPostModal.tsx b/src/app/features/forum/ForumNewPostModal.tsx index cf44f101..1cd3155a 100644 --- a/src/app/features/forum/ForumNewPostModal.tsx +++ b/src/app/features/forum/ForumNewPostModal.tsx @@ -1,7 +1,30 @@ -import React, { FormEventHandler, KeyboardEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import React, { + FormEventHandler, + KeyboardEventHandler, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; import { isKeyHotkey } from 'is-hotkey'; import FocusTrap from 'focus-trap-react'; -import { Box, Button, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Line, Scroll, Text, color, config, toRem } from 'folds'; +import { + Box, + Button, + Header, + IconButton, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + Line, + Scroll, + Text, + color, + config, + toRem, +} from 'folds'; import { Icon, Icons } from '../../components/icons'; import { CustomEditor, @@ -85,7 +108,7 @@ export function ForumNewPostModal({ const trimmedTitle = title.trim(); const plainText = toPlainText(editor.children, false).trim(); const formattedHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS) + toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS), ); const hasText = !isEmptyEditor(editor); @@ -165,7 +188,7 @@ export function ForumNewPostModal({ sending, title, topicRoomId, - ] + ], ); const handleEditorKeyDown: KeyboardEventHandler = useCallback( @@ -175,7 +198,7 @@ export function ForumNewPostModal({ evt.currentTarget.closest('form')?.requestSubmit(); } }, - [sending] + [sending], ); const handleCategoryChange = useCallback((next: string) => { @@ -215,7 +238,13 @@ export function ForumNewPostModal({ New post - + @@ -264,7 +293,11 @@ export function ForumNewPostModal({ bottom={
- +
{thread.totalReplies > 0 && ( - + {thread.totalReplies > 1 && ( {thread.totalReplies} diff --git a/src/app/features/forum/ForumPostUploadField.tsx b/src/app/features/forum/ForumPostUploadField.tsx index 63a7b1ea..7bfeaf3f 100644 --- a/src/app/features/forum/ForumPostUploadField.tsx +++ b/src/app/features/forum/ForumPostUploadField.tsx @@ -37,7 +37,7 @@ import { export async function buildContentsFromUploads( mx: MatrixClient, items: TUploadItem[], - uploads: UploadSuccess[] + uploads: UploadSuccess[], ): Promise { const contentsPromises = uploads.map(async (upload) => { const fileItem = items.find((f) => f.file === upload.file); @@ -75,7 +75,7 @@ export function ForumPostUploadField({ const [uploadBoard, setUploadBoard] = useState(true); const uploadFamilyObserverAtom = createUploadFamilyObserverAtom( roomUploadAtomFamily, - selectedFiles.map((f) => f.file) + selectedFiles.map((f) => f.file), ); const handleFiles = useCallback( @@ -93,7 +93,7 @@ export function ForumPostUploadField({ })), }); }, - [disabled, setSelectedFiles] + [disabled, setSelectedFiles], ); const pickFiles = useFilePicker(handleFiles, true); @@ -106,7 +106,7 @@ export function ForumPostUploadField({ replacement: { ...fileItem, metadata }, }); }, - [setSelectedFiles] + [setSelectedFiles], ); const handleRemoveUpload = useCallback( @@ -118,7 +118,7 @@ export function ForumPostUploadField({ }); uploads.forEach((u) => roomUploadAtomFamily.remove(u)); }, - [selectedFiles, setSelectedFiles] + [selectedFiles, setSelectedFiles], ); const handleCancelUpload = (uploads: Upload[]) => { @@ -227,7 +227,7 @@ export function useForumPostUploads(roomId: string) { uploadResolverRef.current = null; } }, - [mx, selectedFiles, setSelectedFiles] + [mx, selectedFiles, setSelectedFiles], ); const collectUploadContents = useCallback(async (): Promise => { diff --git a/src/app/features/forum/ForumRichReplyComposer.tsx b/src/app/features/forum/ForumRichReplyComposer.tsx index 5d73f148..6ad61a59 100644 --- a/src/app/features/forum/ForumRichReplyComposer.tsx +++ b/src/app/features/forum/ForumRichReplyComposer.tsx @@ -45,7 +45,7 @@ export function ForumRichReplyComposer({ const plainText = toPlainText(editor.children, false).trim(); const formattedHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS) + toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS), ); if (!plainText) return; @@ -62,7 +62,7 @@ export function ForumRichReplyComposer({ createForumReplyFromPayload(mx, roomId, eventId, replyToEventId, { plainText, formattedHtml, - }) + }), ); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to send reply'); @@ -70,7 +70,7 @@ export function ForumRichReplyComposer({ setSending(false); } }, - [editor, mx, onSent, replyToEventId, roomId, sending, threadRootId] + [editor, mx, onSent, replyToEventId, roomId, sending, threadRootId], ); const handleKeyDown: KeyboardEventHandler = useCallback( @@ -80,7 +80,7 @@ export function ForumRichReplyComposer({ evt.currentTarget.closest('form')?.requestSubmit(); } }, - [sending] + [sending], ); return ( @@ -106,11 +106,23 @@ export function ForumRichReplyComposer({ )}
{onCancel && ( - )} -
diff --git a/src/app/features/forum/ForumSpaceShell.tsx b/src/app/features/forum/ForumSpaceShell.tsx index a80389a7..3c36e9e1 100644 --- a/src/app/features/forum/ForumSpaceShell.tsx +++ b/src/app/features/forum/ForumSpaceShell.tsx @@ -1,11 +1,10 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Text, color, Scroll } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import classNames from 'classnames'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; -import { usePowerLevels } from '../../hooks/usePowerLevels'; -import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels'; +import { usePowerLevels, PowerLevelsContextProvider } from '../../hooks/usePowerLevels'; import { Page, PageContent } from '../../components/page'; import { ContainerColor } from '../../styles/ContainerColor.css'; import { LobbyHeader } from '../lobby/LobbyHeader'; @@ -48,7 +47,7 @@ export function ForumSpaceShell() { const topicSelected = Boolean(query.topic); const setActiveThreadId = useSetAtom( - activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId) + activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId), ); useEffect(() => { @@ -68,12 +67,12 @@ export function ForumSpaceShell() { const selectedThread = useMemo( () => threads.find((t) => t.eventId === selectedPostId), - [threads, selectedPostId] + [threads, selectedPostId], ); const getTopicRoom = useCallback( (roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null), - [mx] + [mx], ); const handlePostPublished = useCallback( @@ -84,7 +83,7 @@ export function ForumSpaceShell() { } selectPost(published.eventId, published.topicRoomId); }, - [insertThreadFromNewPost, selectPost] + [insertThreadFromNewPost, selectPost], ); const handleReplySent = useCallback( @@ -93,13 +92,12 @@ export function ForumSpaceShell() { recordThreadReply(selectedPostId); } }, - [recordThreadReply, selectedPostId] + [recordThreadReply, selectedPostId], ); const showThread = Boolean(selectedPostId && activeTopicRoom); - const threadInitialPost = - optimisticPost?.eventId === selectedPostId ? optimisticPost : null; + const threadInitialPost = optimisticPost?.eventId === selectedPostId ? optimisticPost : null; const detailDropRef = useRef(null); return ( @@ -123,7 +121,11 @@ export function ForumSpaceShell() {
{error && ( - + {error} )} diff --git a/src/app/features/forum/ForumThreadDetail.tsx b/src/app/features/forum/ForumThreadDetail.tsx index adc2295f..4a69de6a 100644 --- a/src/app/features/forum/ForumThreadDetail.tsx +++ b/src/app/features/forum/ForumThreadDetail.tsx @@ -1,5 +1,14 @@ // @refresh reset -import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode, type RefObject } from 'react'; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type MouseEvent, + type ReactNode, + type RefObject, +} from 'react'; import { useAtom, useAtomValue } from 'jotai'; import { Box, Scroll, Spinner, Text, config } from 'folds'; import { RelationType, Room } from 'matrix-js-sdk'; @@ -36,7 +45,7 @@ function forumBranchKey(eventId: string): string { function forumMessageSurfaceClass( baseClass: string, eventId: string, - replyTargetEventId?: string + replyTargetEventId?: string, ): string { if (replyTargetEventId && replyTargetEventId === eventId) { return `${baseClass} ${theme.ForumThreadReplyTarget}`; @@ -159,7 +168,7 @@ function ForumThreadMessage({ : false; const { canSendReaction, reactionRelations, handleReactionToggle } = useForumMessageReactions( room, - mEvent + mEvent, ); const handleDelete = useCallback(() => { @@ -186,11 +195,19 @@ function ForumThreadMessage({ onReply={() => onReplyTo(post.eventId)} onEdit={() => onEditEventId(post.eventId)} onDeleted={onDeleted} - className={forumMessageSurfaceClass(theme.ForumThreadReplyInner, post.eventId, replyTargetEventId)} + className={forumMessageSurfaceClass( + theme.ForumThreadReplyInner, + post.eventId, + replyTargetEventId, + )} >
- + @@ -318,7 +335,7 @@ function ForumThreadDetailBody({ resetEditor(editor); resetEditorHistory(editor); }, - [editor] + [editor], ); useEffect(() => { @@ -382,7 +399,7 @@ function ForumThreadDetailBody({ setContentRevision((revision) => revision + 1); void reloadThread(); }, - { threadRootId: rootEventId, wait: 150 } + { threadRootId: rootEventId, wait: 150 }, ); const rootEvent = room.findEventById(rootEventId); @@ -393,7 +410,7 @@ function ForumThreadDetailBody({ : false; const { canSendReaction, reactionRelations, handleReactionToggle } = useForumMessageReactions( room, - rootEvent + rootEvent, ); const handleDeleteRoot = useCallback(() => { @@ -447,7 +464,7 @@ function ForumThreadDetailBody({ if (!mobileOrTablet()) ReactEditor.focus(editor); }, 0); }, - [editor, rootEventId, room, setReplyDraft, timelineSet] + [editor, rootEventId, room, setReplyDraft, timelineSet], ); const rootBranchKey = forumBranchKey(rootEventId); @@ -472,105 +489,113 @@ function ForumThreadDetailBody({ visibility="Hover" >
-
-
-

{title}

-
- - · {formatForumTimeAgo(post.timestamp)} -
-
-
- handleReplyTo(post.eventId)} - onEdit={() => setEditEventId(rootEventId)} - onDeleted={handleDeleted} - className={forumMessageSurfaceClass(theme.ForumTopicDetailOp, post.eventId, replyTargetEventId)} - > - {rootEditing && rootEvent ? ( - +
+

{title}

+
+ + · {formatForumTimeAgo(post.timestamp)} +
+
+
+ - ) : ( - <> - - {reactionRelations && ( - + disabled={rootEditing} + canEdit={canEditRoot} + canDelete={canDeleteRoot} + onReply={() => handleReplyTo(post.eventId)} + onEdit={() => setEditEventId(rootEventId)} + onDeleted={handleDeleted} + className={forumMessageSurfaceClass( + theme.ForumTopicDetailOp, + post.eventId, + replyTargetEventId, )} - - )} - {!rootEditing && ( -
- handleReplyTo(post.eventId)} - replyActive={replyTargetEventId === post.eventId} - onEdit={() => setEditEventId(rootEventId)} - canEdit={canEditRoot} - onDelete={handleDeleteRoot} - canDelete={canDeleteRoot} - /> -
- )} -
- {post.replies.length > 0 && ( - toggleBranch(rootBranchKey)} - > - {!rootRepliesCollapsed && - post.replies.map((reply) => ( - + {rootEditing && rootEvent ? ( + { - void handleComposerSent(); - }} - onDeleted={handleDeleted} - onReplyTo={handleReplyTo} - replyTargetEventId={replyTargetEventId} - collapsedBranches={collapsedBranches} - onToggleBranch={toggleBranch} + mEvent={rootEvent} + imagePackRooms={imagePackRooms} + onCancel={handleEditRootClose} /> - ))} - - )} + ) : ( + <> + + {reactionRelations && ( + + )} + + )} + {!rootEditing && ( +
+ handleReplyTo(post.eventId)} + replyActive={replyTargetEventId === post.eventId} + onEdit={() => setEditEventId(rootEventId)} + canEdit={canEditRoot} + onDelete={handleDeleteRoot} + canDelete={canDeleteRoot} + /> +
+ )} + + {post.replies.length > 0 && ( + toggleBranch(rootBranchKey)} + > + {!rootRepliesCollapsed && + post.replies.map((reply) => ( + { + void handleComposerSent(); + }} + onDeleted={handleDeleted} + onReplyTo={handleReplyTo} + replyTargetEventId={replyTargetEventId} + collapsedBranches={collapsedBranches} + onToggleBranch={toggleBranch} + /> + ))} + + )}
diff --git a/src/app/features/forum/ForumTopicSearchInput.tsx b/src/app/features/forum/ForumTopicSearchInput.tsx index 0f274b01..e3ccdc8d 100644 --- a/src/app/features/forum/ForumTopicSearchInput.tsx +++ b/src/app/features/forum/ForumTopicSearchInput.tsx @@ -1,4 +1,11 @@ -import React, { KeyboardEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import React, { + KeyboardEventHandler, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; import classNames from 'classnames'; import { IconButton } from 'folds'; import { Icon, Icons } from '../../components/icons'; @@ -28,7 +35,11 @@ type ForumTopicSearchInputProps = { type SuggestionMode = 'qualifier' | 'author' | 'title'; -export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTopicSearchInputProps) { +export function ForumTopicSearchInput({ + value, + onChange, + threads = [], +}: ForumTopicSearchInputProps) { const inputRef = useRef(null); const mirrorRef = useRef(null); const pillsRef = useRef(null); @@ -48,15 +59,14 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo : TOPIC_SEARCH_QUALIFIERS; const authorMatches = useMemo( - () => - valueContext?.key === 'from' ? matchAuthorHints(valueContext.partial, authorHints) : [], - [authorHints, valueContext] + () => (valueContext?.key === 'from' ? matchAuthorHints(valueContext.partial, authorHints) : []), + [authorHints, valueContext], ); const titleMatches = useMemo( () => valueContext?.key === 'intitle' ? matchTitleHints(valueContext.partial, titleHints) : [], - [titleHints, valueContext] + [titleHints, valueContext], ); const suggestionMode: SuggestionMode | null = useMemo(() => { @@ -144,7 +154,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo positionFloatingPills(); }); }, - [onChange, positionFloatingPills] + [onChange, positionFloatingPills], ); const insertQualifier = useCallback( @@ -155,7 +165,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo const { value: nextValue, cursor } = insertTopicSearchQualifierAt(value, caretPos, qualifier); applyInputUpdate(nextValue, cursor); }, - [applyInputUpdate, value] + [applyInputUpdate, value], ); const insertValue = useCallback( @@ -166,7 +176,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo const { value: nextValue, cursor } = insertTopicSearchValueAt(value, caretPos, replacement); applyInputUpdate(nextValue, cursor); }, - [applyInputUpdate, value] + [applyInputUpdate, value], ); const selectAtIndex = useCallback( @@ -192,7 +202,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo } } }, - [authorMatches, insertQualifier, insertValue, qualifierMatches, suggestionMode, titleMatches] + [authorMatches, insertQualifier, insertValue, qualifierMatches, suggestionMode, titleMatches], ); const selectHighlighted = useCallback(() => { @@ -204,7 +214,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo if (!suggestionCount) return; setHighlightIndex((idx) => (idx + delta + suggestionCount) % suggestionCount); }, - [suggestionCount] + [suggestionCount], ); const handleKeyDown: KeyboardEventHandler = (event) => { @@ -259,8 +269,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo ? `title:${valueContext?.partial ?? ''}` : `qualifier:${qualifierPartial}`; - const nextIndex = - tabKey === tabPartial ? (highlightIndex + 1) % suggestionCount : 0; + const nextIndex = tabKey === tabPartial ? (highlightIndex + 1) % suggestionCount : 0; setTabPartial(tabKey); setHighlightIndex(nextIndex); selectAtIndex(nextIndex); diff --git a/src/app/features/forum/forumFeed.ts b/src/app/features/forum/forumFeed.ts index ea5a74f6..25e8f3b2 100644 --- a/src/app/features/forum/forumFeed.ts +++ b/src/app/features/forum/forumFeed.ts @@ -46,7 +46,7 @@ function isForumRootContent(content: Record): boolean { function syncForumRootContentAfterEdit( merged: Record, - baseContent: Record + baseContent: Record, ): Record { if (!isForumRootContent(baseContent)) return merged; @@ -77,7 +77,7 @@ function syncForumRootContentAfterEdit( function getLatestEditContent( event: IRoomEvent, - timelineEvents: IRoomEvent[] + timelineEvents: IRoomEvent[], ): Record { const baseContent = event.content as Record; const targetId = event.event_id; @@ -151,7 +151,7 @@ function sortRepliesRecursively(posts: ForumPost[]) { function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent[]): ForumPost[] { const redactedIds = new Set( - timelineEvents.filter((e) => e.unsigned?.redacted_because).map((e) => e.event_id) + timelineEvents.filter((e) => e.unsigned?.redacted_because).map((e) => e.event_id), ); const normalized = timelineEvents @@ -160,7 +160,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent event.type === EventType.RoomMessage && event.event_id && event.content && - !redactedIds.has(event.event_id) + !redactedIds.has(event.event_id), ) .map((event) => { const rawContent = event.content as Record; @@ -183,7 +183,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent }); const room = mx.getRoom(roomId); const displayName = room - ? getMemberDisplayName(room, event.sender || '') ?? event.sender + ? (getMemberDisplayName(room, event.sender || '') ?? event.sender) : event.sender; return { @@ -223,7 +223,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent const current = postsById.get(event.eventId); if (!current) continue; - const relation = event.relation; + const { relation } = event; let threadRootId: string | null = null; let parentEventId: string | null = null; @@ -271,7 +271,10 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent return roots.sort((a, b) => b.timestamp - a.timestamp); } -export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Promise { +export async function listForumTopics( + mx: MatrixClient, + spaceRoomId: string, +): Promise { const rooms: IHierarchyRoom[] = []; let nextBatch: string | undefined; for (let page = 0; page < 5; page += 1) { @@ -285,7 +288,8 @@ export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Pr for (const room of rooms) { if (!room?.room_id || !Array.isArray(room.children_state)) continue; for (const childState of room.children_state) { - if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string') continue; + if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string') + continue; parentByRoomId.set(childState.state_key, room.room_id); } } @@ -339,7 +343,7 @@ export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Pr export async function listTopicFeedPosts( mx: MatrixClient, roomId: string, - options: { from?: string; minRoots?: number } = {} + options: { from?: string; minRoots?: number } = {}, ): Promise<{ posts: ForumPost[]; nextBatch: string | null }> { const pageSize = 40; const minRoots = options.minRoots ?? 8; @@ -352,7 +356,7 @@ export async function listTopicFeedPosts( roomId, nextBatch ?? null, pageSize, - Direction.Backward + Direction.Backward, ); const chunk = [...(response.chunk || [])].reverse(); const pagePosts = buildPosts(mx, roomId, chunk); @@ -437,7 +441,7 @@ function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent { export function collectLocalThreadEvents( mx: MatrixClient, roomId: string, - rootEventId: string + rootEventId: string, ): IRoomEvent[] { const rootId = rootEventId.trim(); const room = mx.getRoom(roomId); @@ -524,7 +528,7 @@ function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] { export function loadPostThreadLocal( mx: MatrixClient, roomId: string, - rootEventId: string + rootEventId: string, ): ForumPost | null { const rootId = rootEventId.trim(); const events = collectLocalThreadEvents(mx, roomId, rootId); @@ -536,7 +540,7 @@ export function loadPostThreadLocal( async function fetchRootEvent( mx: MatrixClient, roomId: string, - rootEventId: string + rootEventId: string, ): Promise { const rootId = rootEventId.trim(); if (!rootId) return null; @@ -556,7 +560,7 @@ async function fetchRootEvent( export async function loadPostThread( mx: MatrixClient, roomId: string, - rootEventId: string + rootEventId: string, ): Promise { const rootId = rootEventId.trim(); const localEvents = collectLocalThreadEvents(mx, roomId, rootId); @@ -566,7 +570,7 @@ export async function loadPostThread( const collectRelations = async ( relationType: RelationType | null, - eventType: EventType | null + eventType: EventType | null, ) => { let from: string | undefined; for (let page = 0; page < 20; page += 1) { @@ -610,7 +614,7 @@ export async function loadPostThread( export async function loadAggregatedTopicFeed( mx: MatrixClient, - scopes: Array<{ roomId: string; sectionTitle?: string; topicName?: string }> + scopes: Array<{ roomId: string; sectionTitle?: string; topicName?: string }>, ): Promise { const allPosts: ForumPost[] = []; for (const scope of scopes) { @@ -639,7 +643,7 @@ export type ForumNewPostPayload = { export async function sendForumPost( mx: MatrixClient, roomId: string, - post: ForumNewPostPayload + post: ForumNewPostPayload, ): Promise { const title = post.title.trim(); const plainText = post.plainText.trim(); @@ -674,7 +678,7 @@ export async function sendForumMediaRoot( mx: MatrixClient, roomId: string, title: string, - content: IContent + content: IContent, ): Promise { const trimmedTitle = title.trim(); if (!trimmedTitle) { @@ -697,7 +701,7 @@ export async function sendForumThreadAttachment( roomId: string, threadRootId: string, content: IContent, - replyToEventId?: string + replyToEventId?: string, ): Promise { const rootId = threadRootId.trim(); const parentId = replyToEventId?.trim() || rootId; @@ -728,7 +732,7 @@ export function sendForumReply( roomId: string, threadRootId: string, replyToEventId: string, - message: string | ForumReplyPayload + message: string | ForumReplyPayload, ): Promise { const rootId = threadRootId.trim(); const parentId = replyToEventId.trim() || rootId; @@ -741,8 +745,7 @@ export function sendForumReply( throw new Error('Reply message is required.'); } - let formattedHtml = - typeof message === 'string' ? '' : String(message.formattedHtml || '').trim(); + let formattedHtml = typeof message === 'string' ? '' : String(message.formattedHtml || '').trim(); formattedHtml = formattedHtml.replace(/(\s*)+$/gi, ''); const content: Record = { @@ -769,13 +772,11 @@ export function createForumPostFromPayload( roomId: string, eventId: string, payload: ForumNewPostPayload, - meta: { topicRoomId?: string; sectionTitle?: string; topicName?: string } = {} + meta: { topicRoomId?: string; sectionTitle?: string; topicName?: string } = {}, ): ForumPost { const userId = mx.getUserId() || 'unknown'; const room = mx.getRoom(roomId); - const displayName = room - ? getMemberDisplayName(room, userId) ?? userId - : userId; + const displayName = room ? (getMemberDisplayName(room, userId) ?? userId) : userId; const title = payload.title.trim(); const plainText = payload.plainText.trim(); let formattedHtml = payload.formattedHtml.trim().replace(/(\s*)+$/gi, ''); @@ -792,7 +793,7 @@ export function createForumPostFromPayload( format: 'org.matrix.custom.html', formatted_body: `

${escapeHtml(title)}

${formattedHtml}`, }, - { stripTitleHeading: true } + { stripTitleHeading: true }, ), sender: userId, senderDisplayName: displayName, @@ -810,15 +811,15 @@ export function createForumReplyFromPayload( roomId: string, eventId: string, replyToEventId: string, - payload: ForumReplyPayload + payload: ForumReplyPayload, ): ForumPost { const userId = mx.getUserId() || 'unknown'; const room = mx.getRoom(roomId); - const displayName = room - ? getMemberDisplayName(room, userId) ?? userId - : userId; + const displayName = room ? (getMemberDisplayName(room, userId) ?? userId) : userId; const plainText = payload.plainText.trim(); - let formattedHtml = String(payload.formattedHtml || '').trim().replace(/(\s*)+$/gi, ''); + const formattedHtml = String(payload.formattedHtml || '') + .trim() + .replace(/(\s*)+$/gi, ''); const content: Record = { body: plainText }; if (formattedHtml) { diff --git a/src/app/features/forum/forumLucideIcons.tsx b/src/app/features/forum/forumLucideIcons.tsx index a52a71e6..99acdcd4 100644 --- a/src/app/features/forum/forumLucideIcons.tsx +++ b/src/app/features/forum/forumLucideIcons.tsx @@ -6,7 +6,12 @@ import type { IconSrc } from 'folds'; type SvgNode = [tag: string, attrs: Record]; const FLAME: SvgNode[] = [ - ['path', { d: 'M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4' }], + [ + 'path', + { + d: 'M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4', + }, + ], ]; const SPARKLES: SvgNode[] = [ @@ -32,23 +37,25 @@ const CROWN: SvgNode[] = [ ]; function lucideIcon(nodes: SvgNode): IconSrc { - return () => ( - - {nodes.map(([tag, attrs]) => - React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs }) - )} - - ); + return function () { + return ( + + {nodes.map(([tag, attrs]) => + React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs }), + )} + + ); + }; } /** hot → flame, new → sparkles, top → crown (matrixsso SORT_LUCIDE_ICONS) */ diff --git a/src/app/features/forum/forumRichText.ts b/src/app/features/forum/forumRichText.ts index a46f5987..8bfbfb85 100644 --- a/src/app/features/forum/forumRichText.ts +++ b/src/app/features/forum/forumRichText.ts @@ -21,7 +21,7 @@ export function stripLeadingTitleHeading(html: string): string { export function bodyHtmlFromMessageContent( content: Record, - options: { stripTitleHeading?: boolean } = {} + options: { stripTitleHeading?: boolean } = {}, ): string | undefined { if (content.format !== 'org.matrix.custom.html') return undefined; const raw = content.formatted_body; diff --git a/src/app/features/forum/forumTheme.css.ts b/src/app/features/forum/forumTheme.css.ts index 9f3a949e..aba3b163 100644 --- a/src/app/features/forum/forumTheme.css.ts +++ b/src/app/features/forum/forumTheme.css.ts @@ -180,10 +180,7 @@ export const ForumTopicPostDetailInner = style({ }); /** @deprecated use ForumTopicPostDetailScroll + ForumTopicPostDetailInner */ -export const ForumTopicPostDetail = style([ - ForumTopicPostDetailScroll, - ForumTopicPostDetailInner, -]); +export const ForumTopicPostDetail = style([ForumTopicPostDetailScroll, ForumTopicPostDetailInner]); export const ForumTopicPostDetailWithThread = style({}); @@ -1285,7 +1282,7 @@ globalStyle( `${ForumThreadReplyInner}:hover ${ForumMessageOptionsBase}, ${ForumThreadReplyInner}:focus-within ${ForumMessageOptionsBase}`, { pointerEvents: 'auto', - } + }, ); globalStyle( @@ -1293,12 +1290,15 @@ globalStyle( { opacity: 1, pointerEvents: 'auto', - } + }, ); -globalStyle(`${ForumThreadReplyInner}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`, { - display: 'none', -}); +globalStyle( + `${ForumThreadReplyInner}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`, + { + display: 'none', + }, +); globalStyle(`${ForumTopicDetailOp}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`, { display: 'none', @@ -1308,7 +1308,7 @@ globalStyle( `${ForumTopicDetailOp}:hover ${ForumMessageOptionsBase}, ${ForumTopicDetailOp}:focus-within ${ForumMessageOptionsBase}`, { pointerEvents: 'auto', - } + }, ); globalStyle( @@ -1316,21 +1316,21 @@ globalStyle( { opacity: 1, pointerEvents: 'auto', - } + }, ); globalStyle( `${ForumThread}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:hover)::before, ${ForumThread}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:focus-within)::before`, { background: threadLineActive, - } + }, ); globalStyle( `${ForumThreadChildren}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:hover)::before, ${ForumThreadChildren}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:focus-within)::before`, { background: threadLineActive, - } + }, ); globalStyle(`${ForumThreadChildren} ${ForumThreadChildren}::before`, { @@ -1342,18 +1342,27 @@ globalStyle(`${ForumAuthorAvatar} > *`, { width: '100%', }); -globalStyle(`${ForumThreadReplyInner} ${ForumMessageBody}, ${ForumThreadReplyInner} ${ForumMessageBodyRich}`, { - marginLeft: 0, - marginRight: 0, -}); +globalStyle( + `${ForumThreadReplyInner} ${ForumMessageBody}, ${ForumThreadReplyInner} ${ForumMessageBodyRich}`, + { + marginLeft: 0, + marginRight: 0, + }, +); -globalStyle(`${ForumTopicDetailRoot} ${ForumMessageBody}, ${ForumTopicDetailRoot} ${ForumMessageBodyRich}`, { - marginTop: toRem(5.6), -}); +globalStyle( + `${ForumTopicDetailRoot} ${ForumMessageBody}, ${ForumTopicDetailRoot} ${ForumMessageBodyRich}`, + { + marginTop: toRem(5.6), + }, +); -globalStyle(`${ForumTopicDetailOp} ${ForumMessageBody}, ${ForumTopicDetailOp} ${ForumMessageBodyRich}`, { - marginTop: toRem(5.6), -}); +globalStyle( + `${ForumTopicDetailOp} ${ForumMessageBody}, ${ForumTopicDetailOp} ${ForumMessageBodyRich}`, + { + marginTop: toRem(5.6), + }, +); // Legacy aliases export const ForumApp = ForumTopicLiveApp; diff --git a/src/app/features/forum/forumTopicHelpers.ts b/src/app/features/forum/forumTopicHelpers.ts index 2948da2e..34b067d1 100644 --- a/src/app/features/forum/forumTopicHelpers.ts +++ b/src/app/features/forum/forumTopicHelpers.ts @@ -1,9 +1,5 @@ import type { ForumPost, ForumSection, ForumThreadSummary, ForumTopic } from './types'; -import { - applyTopicStatusSort, - filterPostsBySearch, - parseTopicSearchQuery, -} from './topicSearch'; +import { applyTopicStatusSort, filterPostsBySearch, parseTopicSearchQuery } from './topicSearch'; export function countAllReplies(replies: ForumPost[] | undefined): number { let total = 0; @@ -45,7 +41,7 @@ export function buildThreadSummaries(posts: ForumPost[]): ForumThreadSummary[] { export function buildTopicThreads( posts: ForumPost[], - query: { q?: string; status?: string; sort?: string } = {} + query: { q?: string; status?: string; sort?: string } = {}, ): ForumThreadSummary[] { const parsed = parseTopicSearchQuery(query.q || ''); const filtered = filterPostsBySearch(posts, parsed); @@ -70,7 +66,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] { } const coveredTopicIds = new Set( - sections.flatMap((section) => section.topics.map((topic) => topic.roomId)) + sections.flatMap((section) => section.topics.map((topic) => topic.roomId)), ); const uncategorizedTopics = postableTopics.filter((topic) => !coveredTopicIds.has(topic.roomId)); if (uncategorizedTopics.length > 0) { @@ -88,7 +84,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] { export function appendReplyToThread( root: ForumPost, parentEventId: string, - reply: ForumPost + reply: ForumPost, ): ForumPost { const walk = (node: ForumPost): ForumPost => { if (node.eventId === parentEventId) { @@ -112,7 +108,7 @@ export function appendReplyToThread( export function annotatePostsWithRoomScope( posts: ForumPost[], roomId: string, - scope: { sectionTitle?: string; topicName?: string } | null = null + scope: { sectionTitle?: string; topicName?: string } | null = null, ): void { const sectionTitle = scope?.sectionTitle ? String(scope.sectionTitle) : ''; const topicName = scope?.topicName ? String(scope.topicName) : ''; diff --git a/src/app/features/forum/topicSearch.ts b/src/app/features/forum/topicSearch.ts index 0e729c44..1260257f 100644 --- a/src/app/features/forum/topicSearch.ts +++ b/src/app/features/forum/topicSearch.ts @@ -87,10 +87,13 @@ export function formatSearchValue(value: string): string { } /** Partial value typed after a qualifier token (e.g. `from:ali` or `intitle:"rel`). */ -export function readActiveQualifierValueAt(value: string, cursor: number): QualifierValueContext | null { +export function readActiveQualifierValueAt( + value: string, + cursor: number, +): QualifierValueContext | null { const before = String(value || '').slice(0, Math.max(0, cursor)); const match = before.match( - /(?:^|\s)(intitle|inpost|inbody|inthread|inreply|from):\s*(?:"([^"]*)"?|(\S*))$/i + /(?:^|\s)(intitle|inpost|inbody|inthread|inreply|from):\s*(?:"([^"]*)"?|(\S*))$/i, ); if (!match) { return null; @@ -117,7 +120,7 @@ export function readActiveQualifierValueAt(value: string, cursor: number): Quali export function insertTopicSearchValueAt( value: string, cursor: number, - replacement: string + replacement: string, ): { value: string; cursor: number } { const ctx = readActiveQualifierValueAt(value, cursor); if (!ctx) { @@ -135,7 +138,7 @@ export function insertTopicSearchValueAt( } export function collectAuthorHintsFromThreads( - threads: Array<{ sender: string; senderDisplayName?: string }> + threads: Array<{ sender: string; senderDisplayName?: string }>, ): TopicSearchAuthorHint[] { const map = new Map(); @@ -150,7 +153,7 @@ export function collectAuthorHintsFromThreads( } return [...map.values()].sort( - (a, b) => a.displayName.localeCompare(b.displayName) || a.localpart.localeCompare(b.localpart) + (a, b) => a.displayName.localeCompare(b.displayName) || a.localpart.localeCompare(b.localpart), ); } @@ -167,9 +170,11 @@ export function collectTitleHintsFromThreads(threads: Array<{ title: string }>): export function matchAuthorHints( partial: string, - hints: TopicSearchAuthorHint[] + hints: TopicSearchAuthorHint[], ): TopicSearchAuthorHint[] { - const prefix = String(partial || '').trim().toLowerCase(); + const prefix = String(partial || '') + .trim() + .toLowerCase(); return hints .filter((hint) => { if (!prefix) { @@ -185,16 +190,16 @@ export function matchAuthorHints( } export function matchTitleHints(partial: string, titles: string[]): string[] { - const prefix = String(partial || '').trim().toLowerCase(); - return titles - .filter((title) => !prefix || title.toLowerCase().includes(prefix)) - .slice(0, 12); + const prefix = String(partial || '') + .trim() + .toLowerCase(); + return titles.filter((title) => !prefix || title.toLowerCase().includes(prefix)).slice(0, 12); } export function insertTopicSearchQualifierAt( value: string, cursor: number, - qualifier: TopicSearchQualifier + qualifier: TopicSearchQualifier, ): { value: string; cursor: number } { const input = String(value || ''); const caret = Math.max(0, Math.min(cursor, input.length)); @@ -285,10 +290,10 @@ export function parseTopicSearchQuery(raw: string): ParsedTopicSearch { const terms = collectTerms(qualifiers, freeText); const isActive = Boolean( freeText || - qualifiers.intitle.length || - qualifiers.inpost.length || - qualifiers.inthread.length || - qualifiers.from.length + qualifiers.intitle.length || + qualifiers.inpost.length || + qualifiers.inthread.length || + qualifiers.from.length, ); return { isActive, qualifiers, freeText, terms }; @@ -377,11 +382,9 @@ export function filterPostsBySearch(posts: ForumPost[], parsed: ParsedTopicSearc return (posts || []).filter((post) => threadMatchesSearch(post, parsed)); } -export function applyTopicStatusSort( - threads: T[], - statusFilter: string, - sortBy: string -): T[] { +export function applyTopicStatusSort< + T extends { lastActivityTs: number; timestamp: number; totalReplies: number; eventId: string }, +>(threads: T[], statusFilter: string, sortBy: string): T[] { let filtered = threads || []; if (statusFilter === 'open') { @@ -396,7 +399,7 @@ export function applyTopicStatusSort b.totalReplies - a.totalReplies || b.lastActivityTs - a.lastActivityTs || - b.eventId.localeCompare(a.eventId) + b.eventId.localeCompare(a.eventId), ); } else if (sortBy === 'new') { sorted.sort((a, b) => b.timestamp - a.timestamp || b.eventId.localeCompare(a.eventId)); @@ -404,7 +407,9 @@ export function applyTopicStatusSort { const hotA = a.totalReplies * 4 + Math.floor((a.lastActivityTs - a.timestamp) / 3600000); const hotB = b.totalReplies * 4 + Math.floor((b.lastActivityTs - b.timestamp) / 3600000); - return hotB - hotA || b.lastActivityTs - a.lastActivityTs || b.eventId.localeCompare(a.eventId); + return ( + hotB - hotA || b.lastActivityTs - a.lastActivityTs || b.eventId.localeCompare(a.eventId) + ); }); } @@ -417,7 +422,7 @@ export function highlightSearchTerms(text: string, terms: string[]): string { } const usable = [...new Set(terms.map((term) => String(term || '').trim()).filter(Boolean))].sort( - (a, b) => b.length - a.length + (a, b) => b.length - a.length, ); let result = text; diff --git a/src/app/features/forum/useForumBoard.ts b/src/app/features/forum/useForumBoard.ts index 87c7f640..a8fe47e7 100644 --- a/src/app/features/forum/useForumBoard.ts +++ b/src/app/features/forum/useForumBoard.ts @@ -9,11 +9,7 @@ import { getSpaceLobbyPath } from '../../pages/pathUtils'; import { createRoomModalAtom } from '../../state/createRoomModal'; import { createSpaceModalAtom } from '../../state/createSpaceModal'; import { StateEvent } from '../../../types/matrix/room'; -import { - buildForumSections, - buildTopicThreads, - buildThreadSummaries, -} from './forumTopicHelpers'; +import { buildForumSections, buildTopicThreads, buildThreadSummaries } from './forumTopicHelpers'; import { applyTopicStatusSort } from './topicSearch'; import { createForumPostFromPayload, @@ -39,7 +35,7 @@ export type ForumBoardScope = { function scopesFromSelection( sections: ForumSection[], category?: string, - topic?: string + topic?: string, ): Array<{ roomId: string; sectionTitle?: string; topicName?: string }> { if (topic) { for (const section of sections) { @@ -66,7 +62,7 @@ function scopesFromSelection( roomId: t.roomId, sectionTitle: section.title, topicName: t.name, - })) + })), ); } @@ -76,10 +72,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { const navigate = useNavigate(); const selectedRoomId = useSelectedRoom(); - const searchParams = useMemo( - () => new URLSearchParams(location.search), - [location.search] - ); + const searchParams = useMemo(() => new URLSearchParams(location.search), [location.search]); const filterQuery: ForumBoardQuery = useMemo( () => ({ @@ -89,7 +82,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { status: (searchParams.get('status') as ForumBoardQuery['status']) || 'all', sort: (searchParams.get('sort') as ForumBoardQuery['sort']) || 'hot', }), - [searchParams] + [searchParams], ); const query: ForumBoardQuery = useMemo( @@ -98,7 +91,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { post: searchParams.get('post') || undefined, postRoom: searchParams.get('postRoom') || undefined, }), - [filterQuery, searchParams] + [filterQuery, searchParams], ); const [sections, setSections] = useState([]); @@ -115,8 +108,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { mutate(next); const search = next.toString(); - const onTopicRoomRoute = - Boolean(selectedRoomId) && selectedRoomId !== forumSpace.roomId; + const onTopicRoomRoute = Boolean(selectedRoomId) && selectedRoomId !== forumSpace.roomId; navigate( { @@ -125,10 +117,10 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { : location.pathname, search: search ? `?${search}` : '', }, - { replace: true } + { replace: true }, ); }, - [location.pathname, location.search, navigate, mx, forumSpace.roomId, selectedRoomId] + [location.pathname, location.search, navigate, mx, forumSpace.roomId, selectedRoomId], ); const setQueryParam = useCallback( @@ -142,7 +134,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { } }); }, - [applyForumSearchParams] + [applyForumSearchParams], ); const setCategory = useCallback( @@ -155,7 +147,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { next.delete('postRoom'); }); }, - [applyForumSearchParams] + [applyForumSearchParams], ); const loadSections = useCallback(async () => { @@ -171,39 +163,42 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { } }, [mx, scope.forumSpaceId]); - const refreshThreads = useCallback(async (options?: { silent?: boolean }) => { - if (!options?.silent) setLoadingThreads(true); - setError(null); - try { - const roomScopes = scopesFromSelection(sections, filterQuery.category, filterQuery.topic); - if (roomScopes.length === 0) { - setThreads([]); - return; - } + const refreshThreads = useCallback( + async (options?: { silent?: boolean }) => { + if (!options?.silent) setLoadingThreads(true); + setError(null); + try { + const roomScopes = scopesFromSelection(sections, filterQuery.category, filterQuery.topic); + if (roomScopes.length === 0) { + setThreads([]); + return; + } - let posts; - if (roomScopes.length === 1) { - const result = await listTopicFeedPosts(mx, roomScopes[0].roomId); - posts = result.posts; - setPostsNextBatch(result.nextBatch); - const scopeMeta = roomScopes[0]; - posts.forEach((post) => { - post.topicRoomId = scopeMeta.roomId; - if (scopeMeta.sectionTitle) post.sectionTitle = scopeMeta.sectionTitle; - if (scopeMeta.topicName) post.topicName = scopeMeta.topicName; - }); - } else { - posts = await loadAggregatedTopicFeed(mx, roomScopes); - setPostsNextBatch(null); - } + let posts; + if (roomScopes.length === 1) { + const result = await listTopicFeedPosts(mx, roomScopes[0].roomId); + posts = result.posts; + setPostsNextBatch(result.nextBatch); + const scopeMeta = roomScopes[0]; + posts.forEach((post) => { + post.topicRoomId = scopeMeta.roomId; + if (scopeMeta.sectionTitle) post.sectionTitle = scopeMeta.sectionTitle; + if (scopeMeta.topicName) post.topicName = scopeMeta.topicName; + }); + } else { + posts = await loadAggregatedTopicFeed(mx, roomScopes); + setPostsNextBatch(null); + } - setThreads(buildTopicThreads(posts, filterQuery)); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to load forum posts'); - } finally { - if (!options?.silent) setLoadingThreads(false); - } - }, [mx, sections, filterQuery]); + setThreads(buildTopicThreads(posts, filterQuery)); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load forum posts'); + } finally { + if (!options?.silent) setLoadingThreads(false); + } + }, + [mx, sections, filterQuery], + ); useEffect(() => { loadSections(); @@ -214,10 +209,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { if (event.getType() !== StateEvent.SpaceChild) return; const roomId = event.getRoomId(); if (!roomId) return; - if ( - roomId === forumSpace.roomId || - sections.some((section) => section.spaceId === roomId) - ) { + if (roomId === forumSpace.roomId || sections.some((section) => section.spaceId === roomId)) { loadSections(); } }; @@ -285,7 +277,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { } }); }, - [applyForumSearchParams] + [applyForumSearchParams], ); const insertThreadFromNewPost = useCallback( @@ -312,7 +304,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { topicRoomId: published.topicRoomId, sectionTitle: scopeMeta?.sectionTitle, topicName: scopeMeta?.topicName, - } + }, ); if (inScope) { @@ -321,14 +313,18 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { setThreads((prev) => { const without = prev.filter((t) => t.eventId !== summary.eventId); const merged = [summary, ...without]; - return applyTopicStatusSort(merged, filterQuery.status || 'all', filterQuery.sort || 'hot'); + return applyTopicStatusSort( + merged, + filterQuery.status || 'all', + filterQuery.sort || 'hot', + ); }); } } return post; }, - [mx, sections, filterQuery] + [mx, sections, filterQuery], ); const recordThreadReply = useCallback((rootEventId: string) => { @@ -340,8 +336,8 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { totalReplies: t.totalReplies + 1, lastActivityTs: Date.now(), } - : t - ) + : t, + ), ); }, []); @@ -367,7 +363,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) { setThreads((prev) => { const existingIds = new Set(prev.map((t) => t.eventId)); const added = buildTopicThreads(result.posts, filterQuery).filter( - (t) => !existingIds.has(t.eventId) + (t) => !existingIds.has(t.eventId), ); const merged = [...prev, ...added]; const sort = filterQuery.sort || 'hot'; diff --git a/src/app/features/forum/useForumMessageReactions.ts b/src/app/features/forum/useForumMessageReactions.ts index 0fae7e73..9e634857 100644 --- a/src/app/features/forum/useForumMessageReactions.ts +++ b/src/app/features/forum/useForumMessageReactions.ts @@ -1,11 +1,5 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; -import { - EventType, - MatrixEvent, - RelationType, - Room, - RoomEvent, -} from 'matrix-js-sdk'; +import { EventType, MatrixEvent, RelationType, Room, RoomEvent } from 'matrix-js-sdk'; import { RelationsEvent } from 'matrix-js-sdk/lib/models/relations'; import { MessageEvent } from '../../../types/matrix/room'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -115,13 +109,13 @@ export function useForumMessageReactions(room: Room, mEvent: MatrixEvent | undef mx.sendEvent( room.roomId, MessageEvent.Reaction as never, - getReactionContent(targetEventId, key, rShortcode) + getReactionContent(targetEventId, key, rShortcode), ).finally(() => { bumpRelations(); window.setTimeout(bumpRelations, 250); }); }, - [bumpRelations, mx, room.roomId, roomTimelineSet] + [bumpRelations, mx, room.roomId, roomTimelineSet], ); return { diff --git a/src/app/features/forum/useForumMessageRenderOptions.ts b/src/app/features/forum/useForumMessageRenderOptions.ts index 8997919a..23412cce 100644 --- a/src/app/features/forum/useForumMessageRenderOptions.ts +++ b/src/app/features/forum/useForumMessageRenderOptions.ts @@ -32,7 +32,7 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) { const roomWideEmbedFilters = useRoomWideEmbedFilters(room ?? undefined); const combinedEmbedFilters = useMemo( () => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters), - [personalEmbedFilters, roomWideEmbedFilters] + [personalEmbedFilters, roomWideEmbedFilters], ); const mentionClickHandler = useMentionClickHandler(room?.roomId ?? ''); @@ -42,10 +42,15 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) { () => ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room?.roomId ?? '', href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention( + mx, + room?.roomId ?? '', + href, + makeMentionCustomProps(mentionClickHandler), + ), ), }), - [mx, room?.roomId, mentionClickHandler] + [mx, room?.roomId, mentionClickHandler], ); const htmlReactParserOptions = useMemo( @@ -56,7 +61,7 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) { handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, }), - [mx, room?.roomId, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication] + [mx, room?.roomId, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication], ); return { diff --git a/src/app/features/forum/useForumRoomLiveUpdates.ts b/src/app/features/forum/useForumRoomLiveUpdates.ts index c7b4eaeb..b8840118 100644 --- a/src/app/features/forum/useForumRoomLiveUpdates.ts +++ b/src/app/features/forum/useForumRoomLiveUpdates.ts @@ -1,11 +1,5 @@ import { useEffect, useMemo, useRef } from 'react'; -import { - EventType, - MatrixEvent, - RelationType, - Room, - RoomEvent, -} from 'matrix-js-sdk'; +import { EventType, MatrixEvent, RelationType, Room, RoomEvent } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; type ForumRoomLiveOptions = { @@ -42,8 +36,7 @@ function isForumThreadEvent(mEvent: MatrixEvent, threadRootId: string): boolean function isSecondaryMatrixEvent(mEvent: MatrixEvent): boolean { const relation = mEvent.getRelation(); return ( - relation?.rel_type === RelationType.Replace || - relation?.rel_type === RelationType.Annotation + relation?.rel_type === RelationType.Replace || relation?.rel_type === RelationType.Annotation ); } @@ -69,7 +62,7 @@ function isRelevantEvent(mEvent: MatrixEvent, threadRootId?: string): boolean { export function useForumRoomLiveUpdates( rooms: Room[], onUpdate: () => void, - options: ForumRoomLiveOptions = {} + options: ForumRoomLiveOptions = {}, ) { const mx = useMatrixClient(); const { threadRootId, wait = 200 } = options; diff --git a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx index f43c80b8..11f45a39 100644 --- a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx +++ b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Box, IconButton, Scroll, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { RoomCard } from '../../components/room-card'; import { RoomTopicViewer } from '../../components/room-topic-viewer'; import { Page, PageHeader } from '../../components/page'; diff --git a/src/app/features/lobby/DnD.tsx b/src/app/features/lobby/DnD.tsx index b82f7aa3..b7e2a48f 100644 --- a/src/app/features/lobby/DnD.tsx +++ b/src/app/features/lobby/DnD.tsx @@ -22,7 +22,7 @@ export const useDraggableItem = ( item: HierarchyItem, targetRef: RefObject, onDragging: (item?: HierarchyItem) => void, - dragHandleRef?: RefObject + dragHandleRef?: RefObject, ): boolean => { const [dragging, setDragging] = useState(false); @@ -122,7 +122,7 @@ export function AfterItemDropTarget({ export const useDnDMonitor = ( scrollRef: RefObject, onDragging: (item?: HierarchyItem) => void, - onReorder: (item: HierarchyItem, container: DropContainerData) => void + onReorder: (item: HierarchyItem, container: DropContainerData) => void, ) => { useEffect(() => { const scrollElement = scrollRef.current; @@ -141,7 +141,7 @@ export const useDnDMonitor = ( }), autoScrollForElements({ element: scrollElement, - }) + }), ); }, [scrollRef, onDragging, onReorder]); }; diff --git a/src/app/features/lobby/HierarchyItemMenu.tsx b/src/app/features/lobby/HierarchyItemMenu.tsx index dc039dea..3001c10a 100644 --- a/src/app/features/lobby/HierarchyItemMenu.tsx +++ b/src/app/features/lobby/HierarchyItemMenu.tsx @@ -1,6 +1,18 @@ import React, { MouseEventHandler, useCallback, useEffect, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Box, IconButton, PopOut, Menu, MenuItem, Text, RectCords, config, Line, Spinner, toRem } from 'folds'; +import { + Box, + IconButton, + PopOut, + Menu, + MenuItem, + Text, + RectCords, + config, + Line, + Spinner, + toRem, +} from 'folds'; import { Icon, Icons } from '../../components/icons'; import { HierarchyItem } from '../../hooks/useSpaceHierarchy'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -36,7 +48,7 @@ function SuggestMenuItem({ useCallback(() => { const newContent: MSpaceChildContent = { ...content, suggested: !content.suggested }; return mx.sendStateEvent(parentId, StateEvent.SpaceChild as any, newContent, roomId); - }, [mx, parentId, roomId, content]) + }, [mx, parentId, roomId, content]), ); useEffect(() => { @@ -73,8 +85,8 @@ function RemoveMenuItem({ const [removeState, handleRemove] = useAsyncCallback( useCallback( () => mx.sendStateEvent(parentId, StateEvent.SpaceChild as any, {}, roomId), - [mx, parentId, roomId] - ) + [mx, parentId, roomId], + ), ); useEffect(() => { diff --git a/src/app/features/lobby/Lobby.tsx b/src/app/features/lobby/Lobby.tsx index d8de5f1a..e34a837f 100644 --- a/src/app/features/lobby/Lobby.tsx +++ b/src/app/features/lobby/Lobby.tsx @@ -1,6 +1,5 @@ import React, { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Chip, IconButton, Line, Scroll, Spinner, Text, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useAtom, useAtomValue } from 'jotai'; import { useNavigate } from 'react-router-dom'; @@ -8,6 +7,7 @@ import { JoinRule, RestrictedAllowType, Room } from 'matrix-js-sdk'; import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types'; import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces'; import { produce } from 'immer'; +import { Icon, Icons } from '../../components/icons'; import { useSpace } from '../../hooks/useSpace'; import { Page, PageContent, PageContentCenter, PageHeroSection } from '../../components/page'; import { @@ -64,7 +64,7 @@ import { joiningProgressAtom } from '../../state/joiningProgress'; const useCanDropLobbyItem = ( space: Room, roomsPowerLevels: Map, - getRoom: (roomId: string) => Room | undefined + getRoom: (roomId: string) => Room | undefined, ): CanDropCallback => { const mx = useMatrixClient(); @@ -91,7 +91,7 @@ const useCanDropLobbyItem = ( return true; }, - [space, roomsPowerLevels, getRoom, mx] + [space, roomsPowerLevels, getRoom, mx], ); const canDropRoom: CanDropCallback = useCallback( @@ -111,7 +111,7 @@ const useCanDropLobbyItem = ( const canChangeJoinRuleAllow = itemPermissions.stateEvent( StateEvent.RoomJoinRules, - mx.getSafeUserId() + mx.getSafeUserId(), ); if (!canChangeJoinRuleAllow) { return false; @@ -129,7 +129,7 @@ const useCanDropLobbyItem = ( } return true; }, - [mx, getRoom, roomsPowerLevels] + [mx, getRoom, roomsPowerLevels], ); const canDrop: CanDropCallback = useCallback( @@ -146,7 +146,7 @@ const useCanDropLobbyItem = ( return canDropRoom(item, container); }, - [canDropSpace, canDropRoom] + [canDropSpace, canDropRoom], ); return canDrop; @@ -179,7 +179,7 @@ function SpaceCardLobby() { const [onTop, setOnTop] = useState(true); const [closedCategories, setClosedCategories] = useAtom(useClosedLobbyCategoriesAtom()); const [sidebarItems] = useSidebarItems( - useOrphanSpaces(mx, allRoomsAtom, useAtomValue(roomToParentsAtom)) + useOrphanSpaces(mx, allRoomsAtom, useAtomValue(roomToParentsAtom)), ); const sidebarSpaces = useMemo(() => { const sideSpaces = sidebarItems.flatMap((item) => { @@ -205,7 +205,7 @@ function SpaceCardLobby() { setSpacesItem((current) => produce(current, (draft) => { all.forEach((r) => draft.set(r.room_id, r)); - }) + }), ); } catch { // hierarchy may be unavailable for some memberships @@ -218,7 +218,7 @@ function SpaceCardLobby() { useElementSizeObserver( useCallback(() => heroSectionRef.current, []), - useCallback((w, height) => setHeroSectionHeight(height), []) + useCallback((w, height) => setHeroSectionHeight(height), []), ); const getRoom = useGetRoom(allJoinedRooms); @@ -232,9 +232,9 @@ function SpaceCardLobby() { (childId) => closedCategories.has(makeLobbyCategoryId(space.roomId, childId)) || (draggingItem ? 'space' in draggingItem : false), - [closedCategories, space.roomId, draggingItem] + [closedCategories, space.roomId, draggingItem], ), - spacesItems + spacesItems, ); const virtualizer = useVirtualizer({ @@ -256,8 +256,8 @@ function SpaceCardLobby() { return [getRoom(i.space.roomId), ...childRooms]; }) .filter((r) => !!r) as Room[], - [hierarchy, getRoom] - ) + [hierarchy, getRoom], + ), ); const canDrop: CanDropCallback = useCanDropLobbyItem(space, roomsPowerLevels, getRoom); @@ -311,13 +311,13 @@ function SpaceCardLobby() { reorder.item.parentId, StateEvent.SpaceChild as any, { ...reorder.item.content, order: reorder.orderKey }, - reorder.item.roomId + reorder.item.roomId, ); }); } }, - [mx, hierarchy, lex, roomsPowerLevels] - ) + [mx, hierarchy, lex, roomsPowerLevels], + ), ); const reorderingSpace = reorderSpaceState.status === AsyncStatus.Loading; @@ -346,7 +346,7 @@ function SpaceCardLobby() { // restricted room from one space to another const joinRuleContent = getStateEvent( itemRoom, - StateEvent.RoomJoinRules + StateEvent.RoomJoinRules, )?.getContent(); if (joinRuleContent) { @@ -362,7 +362,7 @@ function SpaceCardLobby() { } const itemSpaces = Array.from( - hierarchy?.find((i) => i.space.roomId === containerParentId)?.rooms ?? [] + hierarchy?.find((i) => i.space.roomId === containerParentId)?.rooms ?? [], ); const beforeItem: HierarchyItem | undefined = @@ -398,13 +398,13 @@ function SpaceCardLobby() { containerParentId, StateEvent.SpaceChild as any, { ...reorder.item.content, order: reorder.orderKey }, - reorder.item.roomId + reorder.item.roomId, ); }); } }, - [mx, hierarchy, lex] - ) + [mx, hierarchy, lex], + ), ); const reorderingRoom = reorderRoomState.status === AsyncStatus.Loading; const reordering = reorderingRoom || reorderingSpace; @@ -423,8 +423,8 @@ function SpaceCardLobby() { reorderRoom(item, container.item); } }, - [reorderRoom, reorderSpace, canDrop] - ) + [reorderRoom, reorderSpace, canDrop], + ), ); const handleSpacesFound = useCallback( @@ -436,14 +436,14 @@ function SpaceCardLobby() { setSpacesItem((current) => produce(current, (draft) => { items.forEach((item) => draft.set(item.room_id, item)); - }) + }), ); }, - [setSpaceRooms] + [setSpaceRooms], ); const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => - closedCategories.has(categoryId) + closedCategories.has(categoryId), ); const handleOpenRoom: MouseEventHandler = (evt) => { @@ -462,7 +462,7 @@ function SpaceCardLobby() { const newSpacesContent = makeCinnySpacesContent(mx, newItems); mx.setAccountData(AccountDataEvent.CinnySpaces as any, newSpacesContent as any); }, - [mx, sidebarItems, sidebarSpaces] + [mx, sidebarItems, sidebarSpaces], ); return ( diff --git a/src/app/features/lobby/LobbyHeader.tsx b/src/app/features/lobby/LobbyHeader.tsx index 0a96a141..a4206d8b 100644 --- a/src/app/features/lobby/LobbyHeader.tsx +++ b/src/app/features/lobby/LobbyHeader.tsx @@ -1,7 +1,22 @@ import React, { MouseEventHandler, forwardRef, useEffect, useMemo, useRef, useState } from 'react'; -import { Avatar, Box, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Text, Tooltip, TooltipProvider, config, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Avatar, + Box, + IconButton, + Line, + Menu, + MenuItem, + PopOut, + RectCords, + Text, + Tooltip, + TooltipProvider, + config, + toRem, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { useNavigate } from 'react-router-dom'; +import { Icon, Icons } from '../../components/icons'; import { PageHeader } from '../../components/page'; import { useSetSetting } from '../../state/hooks/settings'; import { settingsAtom } from '../../state/settings'; @@ -18,7 +33,7 @@ import { RemoveInaccessiblePrompt } from '../../components/remove-inaccessible-p import { stopPropagation } from '../../utils/keyboard'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { useBackRoute } from '../../hooks/useBackRoute'; -import { mxcUrlToHttp } from '../../utils/matrix'; +import { mxcUrlToHttp, getCanonicalAliasOrRoomId } from '../../utils/matrix'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useOpenSpaceSettings } from '../../state/hooks/spaceSettings'; import { useRoomCreators } from '../../hooks/useRoomCreators'; @@ -28,8 +43,6 @@ import { AddExistingModal } from '../add-existing'; import { SpeechBubble } from '../../components/speech-bubble/SpeechBubble'; import { SpaceOptionsMenu, type OpenAddExistingOptions } from '../space/SpaceOptionsMenu'; import type { HierarchyItemSpace } from '../../hooks/useSpaceHierarchy'; -import { useNavigate } from 'react-router-dom'; -import { getCanonicalAliasOrRoomId } from '../../utils/matrix'; import { getSpaceFeedPath } from '../../pages/pathUtils'; import { shouldShowForumLobby } from '../../utils/room'; import { useForumBoardContextOptionally } from '../forum/ForumBoardContext'; @@ -176,7 +189,7 @@ const LobbyMenu = forwardRef( ); - } + }, ); type LobbyHeaderProps = { @@ -200,7 +213,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb const name = useRoomName(space); const avatarMxc = useRoomAvatar(space); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const forumBoard = useForumBoardContextOptionally(); @@ -228,11 +241,11 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb space: true, parentId: addParent.roomId === space.roomId ? undefined : space.roomId, }), - [addParent.roomId, space.roomId] + [addParent.roomId, space.roomId], ); const canEditChildren = Boolean( - spacePermissions.stateEvent(StateEvent.SpaceChild, mx.getSafeUserId()) + spacePermissions.stateEvent(StateEvent.SpaceChild, mx.getSafeUserId()), ); const handleOpenMenu: MouseEventHandler = (evt) => { @@ -259,7 +272,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb const isInside = (node: Node | null) => { if (!node) return false; return Boolean( - menuWrapperRef.current?.contains(node) || menuTriggerElRef.current?.contains(node) + menuWrapperRef.current?.contains(node) || menuTriggerElRef.current?.contains(node), ); }; @@ -299,99 +312,99 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb if (showSpaceToolbar) { return ( <> - - - {showInPageHeader && ( - - - - - - )} - - {nameInitials(name)}} - /> - - - {name} - - - - More Options - - } - > - {(triggerRef) => ( - - - + + + {showInPageHeader && ( + + + + + )} - - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > -
- - setMenuAnchor(undefined)} - onOpenAddExisting={(options) => { - setAddExisting(options); - setMenuAnchor(undefined); - }} - forumAdd={ - forumBoard && canEditChildren - ? { - item: addParentItem, - showAddSpace: addParent.showAddSpace, - } - : undefined - } - /> - -
- - } + + {nameInitials(name)}} + /> + + + {name} + + + + More Options + + } + > + {(triggerRef) => ( + + + + )} + + setMenuAnchor(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, + }} + > +
+ + setMenuAnchor(undefined)} + onOpenAddExisting={(options) => { + setAddExisting(options); + setMenuAnchor(undefined); + }} + forumAdd={ + forumBoard && canEditChildren + ? { + item: addParentItem, + showAddSpace: addParent.showAddSpace, + } + : undefined + } + /> + +
+ + } + /> +
+
+ {addExisting && ( + setAddExisting(null)} /> - - - {addExisting && ( - setAddExisting(null)} - /> - )} + )} ); } diff --git a/src/app/features/lobby/LobbyHero.tsx b/src/app/features/lobby/LobbyHero.tsx index 1cd0b8e2..6effcd8c 100644 --- a/src/app/features/lobby/LobbyHero.tsx +++ b/src/app/features/lobby/LobbyHero.tsx @@ -22,7 +22,9 @@ export function LobbyHero() { const name = useRoomName(space); const topic = useRoomTopic(space); const avatarMxc = useRoomAvatar(space); - const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined : undefined; + const avatarUrl = avatarMxc + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) + : undefined; return ( ( - useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]) + useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]), ); const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error; @@ -292,7 +308,7 @@ export const RoomItemCard = as<'div', RoomItemCardProps>( getRoom, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -383,8 +399,8 @@ export const RoomItemCard = as<'div', RoomItemCardProps>( topic={summary.topic} avatarUrl={ summary?.avatar_url - ? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ?? - undefined + ? (mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ?? + undefined) : undefined } memberCount={summary.num_joined_members} @@ -400,5 +416,5 @@ export const RoomItemCard = as<'div', RoomItemCardProps>( {after} ); - } + }, ); diff --git a/src/app/features/lobby/SpaceHierarchy.tsx b/src/app/features/lobby/SpaceHierarchy.tsx index e6cad7f5..3b501b25 100644 --- a/src/app/features/lobby/SpaceHierarchy.tsx +++ b/src/app/features/lobby/SpaceHierarchy.tsx @@ -67,7 +67,7 @@ export const SpaceHierarchy = forwardRef( onOpenRoom, onSpacesFound, }, - ref + ref, ) => { const mx = useMatrixClient(); @@ -132,7 +132,9 @@ export const SpaceHierarchy = forwardRef( return parentToSubRooms; }, [mx, roomItems]); - let childItems = roomItems?.filter((i) => !subspaces.has(i.roomId) && !globalSubRoomIds.has(i.roomId)); + let childItems = roomItems?.filter( + (i) => !subspaces.has(i.roomId) && !globalSubRoomIds.has(i.roomId), + ); // Only hide when we know the user cannot edit children. If power levels are // still loading (spacePermissions undefined), keep inaccessible rows visible // so admins can clean them up. @@ -196,7 +198,8 @@ export const SpaceHierarchy = forwardRef( {childItems && childItems.length > 0 ? ( {childItems.map((roomItem, index) => { - const roomSummary = rooms.get(roomItem.roomId) ?? hierarchySummaries.get(roomItem.roomId); + const roomSummary = + rooms.get(roomItem.roomId) ?? hierarchySummaries.get(roomItem.roomId); const roomPowerLevels = roomsPowerLevels.get(roomItem.roomId) ?? {}; @@ -249,7 +252,8 @@ export const SpaceHierarchy = forwardRef( {subRoomIds.map((subRoomId) => { const subRoom = mx.getRoom(subRoomId); - const subRoomSummary = rooms.get(subRoomId) ?? hierarchySummaries.get(subRoomId); + const subRoomSummary = + rooms.get(subRoomId) ?? hierarchySummaries.get(subRoomId); const subRoomPowerLevels = roomsPowerLevels.get(subRoomId) ?? {}; const subRoomItem: HierarchyItemRoom = { roomId: subRoomId, @@ -318,5 +322,5 @@ export const SpaceHierarchy = forwardRef( )} ); - } + }, ); diff --git a/src/app/features/lobby/SpaceItem.tsx b/src/app/features/lobby/SpaceItem.tsx index d0d15c31..7a104e85 100644 --- a/src/app/features/lobby/SpaceItem.tsx +++ b/src/app/features/lobby/SpaceItem.tsx @@ -1,10 +1,24 @@ import React, { MouseEventHandler, ReactNode, useCallback, useRef, useState } from 'react'; -import { Box, Avatar, Text, Chip, as, Badge, toRem, Spinner, PopOut, Menu, MenuItem, RectCords, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + Avatar, + Text, + Chip, + as, + Badge, + toRem, + Spinner, + PopOut, + Menu, + MenuItem, + RectCords, + config, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import classNames from 'classnames'; import { MatrixError, Room } from 'matrix-js-sdk'; import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces'; +import { Icon, Icons } from '../../components/icons'; import { HierarchyItem } from '../../hooks/useSpaceHierarchy'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { RoomAvatar } from '../../components/room-avatar'; @@ -94,7 +108,7 @@ function UnjoinedSpaceProfile({ const mx = useMatrixClient(); const [joinState, join] = useAsyncCallback( - useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]) + useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]), ); const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error; @@ -259,7 +273,7 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>( getRoom, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -320,8 +334,14 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>( name={summary.name || summary.canonical_alias || roomId} avatarUrl={ summary?.avatar_url - ? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ?? - undefined + ? (mxcUrlToHttp( + mx, + summary.avatar_url, + useAuthentication, + 96, + 96, + 'crop', + ) ?? undefined) : undefined } suggested={content.suggested} @@ -340,5 +360,5 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>( {after} ); - } + }, ); diff --git a/src/app/features/message-search/MessageSearch.tsx b/src/app/features/message-search/MessageSearch.tsx index 5193d6f2..fec49546 100644 --- a/src/app/features/message-search/MessageSearch.tsx +++ b/src/app/features/message-search/MessageSearch.tsx @@ -1,11 +1,11 @@ import React, { RefObject, useEffect, useMemo, useRef } from 'react'; import { Text, Box, config, Spinner, IconButton, Line, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { useAtomValue } from 'jotai'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useInfiniteQuery } from '@tanstack/react-query'; import { useSearchParams } from 'react-router-dom'; import { SearchOrderBy } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../components/icons'; import { PageHero, PageHeroEmpty, PageHeroSection } from '../../components/page'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { _SearchPathSearchParams } from '../../pages/paths'; @@ -34,7 +34,7 @@ const useSearchPathSearchParams = (searchParams: URLSearchParams): _SearchPathSe rooms: searchParams.get('rooms') ?? undefined, senders: searchParams.get('senders') ?? undefined, }), - [searchParams] + [searchParams], ); type MessageSearchProps = { @@ -58,7 +58,7 @@ export function MessageSearch({ // Include DMs — previously useRooms alone stripped them and broke DM search const allRooms = useMemo( () => [...nonDirectRooms, ...directRooms], - [nonDirectRooms, directRooms] + [nonDirectRooms, directRooms], ); const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); @@ -76,7 +76,7 @@ export function MessageSearch({ const searchParamRooms = useMemo(() => { if (searchPathSearchParams.rooms) { const joinedRoomIds = decodeSearchParamValueArray(searchPathSearchParams.rooms).filter( - (rId) => allRooms.includes(rId) + (rId) => allRooms.includes(rId), ); return joinedRoomIds; } diff --git a/src/app/features/message-search/SearchFilters.tsx b/src/app/features/message-search/SearchFilters.tsx index 49edccdc..195abf20 100644 --- a/src/app/features/message-search/SearchFilters.tsx +++ b/src/app/features/message-search/SearchFilters.tsx @@ -6,11 +6,27 @@ import React, { useRef, useState, } from 'react'; -import { Box, Chip, Text, Line, config, PopOut, Menu, MenuItem, Header, toRem, Scroll, Button, Input, Badge, RectCords } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + Chip, + Text, + Line, + config, + PopOut, + Menu, + MenuItem, + Header, + toRem, + Scroll, + Button, + Input, + Badge, + RectCords, +} from 'folds'; import { SearchOrderBy } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; import { useVirtualizer } from '@tanstack/react-virtual'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { joinRuleToIconSrc } from '../../utils/room'; import { factoryRoomIdByAtoZ } from '../../utils/sort'; @@ -117,13 +133,13 @@ function SelectRoomButton({ roomList, selectedRooms, onChange }: SelectRoomButto const getRoomNameStr: SearchItemStrGetter = useCallback( (rId) => mx.getRoom(rId)?.name ?? rId, - [mx] + [mx], ); const [searchResult, _searchRoom, resetSearch] = useAsyncSearch( roomList, getRoomNameStr, - SEARCH_OPTS + SEARCH_OPTS, ); const rooms = Array.from(searchResult?.items ?? roomList).sort(factoryRoomIdByAtoZ(mx)); diff --git a/src/app/features/message-search/SearchInput.tsx b/src/app/features/message-search/SearchInput.tsx index 5b9a93ac..f03eba12 100644 --- a/src/app/features/message-search/SearchInput.tsx +++ b/src/app/features/message-search/SearchInput.tsx @@ -2,6 +2,7 @@ import React, { FormEventHandler, RefObject } from 'react'; import { Box, Text, Input, Spinner, Chip, config } from 'folds'; import { Icon, Icons } from '../../components/icons'; + type SearchProps = { active?: boolean; loading?: boolean; diff --git a/src/app/features/message-search/SearchResultGroup.tsx b/src/app/features/message-search/SearchResultGroup.tsx index d4951aac..37cdf366 100644 --- a/src/app/features/message-search/SearchResultGroup.tsx +++ b/src/app/features/message-search/SearchResultGroup.tsx @@ -3,8 +3,8 @@ import React, { MouseEventHandler, useMemo } from 'react'; import { IEventWithRoomId, JoinRule, RelationType, Room } from 'matrix-js-sdk'; import { HTMLReactParserOptions } from 'html-react-parser'; import { Avatar, Box, Chip, Header, Text, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { Opts as LinkifyOpts } from 'linkifyjs'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { factoryRenderLinkifyWithMention, @@ -62,7 +62,9 @@ type SearchResultItemProps = { item: ResultItem; getMemberPowerTag: ReturnType; accessibleTagColors: Map | undefined; - renderMatrixEvent: ReturnType>; + renderMatrixEvent: ReturnType< + typeof useMatrixEventRenderer<[IEventWithRoomId, string, GetContentCallback]> + >; handleOpenClick: MouseEventHandler; legacyUsernameColor?: boolean; hour24Clock: boolean; @@ -88,21 +90,17 @@ function SearchResultItem({ const { event } = item; const displayName = - getMemberDisplayName(room, event.sender) ?? - getMxIdLocalPart(event.sender) ?? - event.sender; + getMemberDisplayName(room, event.sender) ?? getMxIdLocalPart(event.sender) ?? event.sender; const senderAvatarMxc = getMemberAvatarMxc(room, event.sender); const relation = event.content['m.relates_to']; const mainEventId = relation?.rel_type === RelationType.Replace ? relation.event_id : event.event_id; - const getContent = (() => - event.content['m.new_content'] ?? event.content) as GetContentCallback; + const getContent = (() => event.content['m.new_content'] ?? event.content) as GetContentCallback; const replyEventId = relation?.['m.in_reply_to']?.event_id; - const threadRootId = - relation?.rel_type === RelationType.Thread ? relation.event_id : undefined; + const threadRootId = relation?.rel_type === RelationType.Thread ? relation.event_id : undefined; // Get custom user color from avatar metadata const customUserColor = useOtherUserColor(event.sender, room); @@ -116,7 +114,8 @@ function SearchResultItem({ : undefined; // Priority: custom user color > tag color (non-legacy) > colorMXID (legacy) - const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor); + const usernameColor = + customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor); return ( ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)), ), }), - [mx, room, mentionClickHandler] + [mx, room, mentionClickHandler], ); const htmlReactParserOptions = useMemo( () => @@ -259,7 +252,7 @@ export function SearchResultGroup({ mentionClickHandler, spoilerClickHandler, useAuthentication, - ] + ], ); const renderMatrixEvent = useMatrixEventRenderer<[IEventWithRoomId, string, GetContentCallback]>( @@ -326,7 +319,7 @@ export function SearchResultGroup({ ); - } + }, ); const handleOpenClick: MouseEventHandler = (evt) => { diff --git a/src/app/features/message-search/useMessageSearch.ts b/src/app/features/message-search/useMessageSearch.ts index a8c586c7..d2759d7b 100644 --- a/src/app/features/message-search/useMessageSearch.ts +++ b/src/app/features/message-search/useMessageSearch.ts @@ -104,8 +104,7 @@ const getSearchableBody = (event: MatrixEvent): string | undefined => { } const body = typeof content.body === 'string' ? content.body : undefined; - const formatted = - typeof content.formatted_body === 'string' ? content.formatted_body : undefined; + const formatted = typeof content.formatted_body === 'string' ? content.formatted_body : undefined; return [body, formatted].filter(Boolean).join('\n') || undefined; }; @@ -233,7 +232,7 @@ export const useMessageSearch = (params: MessageSearchParams) => { return searchLocalRooms( mx, scopedRooms.filter((id) => isEncryptedRoom(mx, id)), - term + term, ); } @@ -245,7 +244,7 @@ export const useMessageSearch = (params: MessageSearchParams) => { throw new Error('Message search failed'); } }, - [mx, term, order, rooms, senders] + [mx, term, order, rooms, senders], ); return searchMessages; diff --git a/src/app/features/room-app/RoomAppSchema.tsx b/src/app/features/room-app/RoomAppSchema.tsx index 707cbbd7..3c4e8785 100644 --- a/src/app/features/room-app/RoomAppSchema.tsx +++ b/src/app/features/room-app/RoomAppSchema.tsx @@ -43,7 +43,7 @@ export function RoomAppSchema({ const scopedCss = useMemo( () => (content.css ? scopeRoomAppCss(content.css, SCOPE) : ''), - [content.css] + [content.css], ); const setField = useCallback((name: string, value: string) => { @@ -66,7 +66,7 @@ export function RoomAppSchema({ setSending(false); } }, - [onAction, sending, uiEventId, values] + [onAction, sending, uiEventId, values], ); const renderNode = (node: PaarrotUiNode): React.ReactNode => { @@ -174,7 +174,7 @@ export function RoomAppSchema({ case 'image': { if (!isAllowedRoomAppImageSrc(node.src)) return null; const httpSrc = node.src.startsWith('mxc://') - ? mxcUrlToHttp(mx, node.src, useAuthentication) ?? undefined + ? (mxcUrlToHttp(mx, node.src, useAuthentication) ?? undefined) : node.src; if (!httpSrc) return null; return ( diff --git a/src/app/features/room-app/RoomAppView.tsx b/src/app/features/room-app/RoomAppView.tsx index 253eb6fb..47f39b7e 100644 --- a/src/app/features/room-app/RoomAppView.tsx +++ b/src/app/features/room-app/RoomAppView.tsx @@ -6,11 +6,7 @@ import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useStateEvent } from '../../hooks/useStateEvent'; import { useRoomName } from '../../hooks/useRoomMeta'; -import { - MessageEvent, - PaarrotUiActionContent, - StateEvent, -} from '../../../types/matrix/room'; +import { MessageEvent, PaarrotUiActionContent, StateEvent } from '../../../types/matrix/room'; import { parsePaarrotUiContent } from '../../utils/room'; import { RoomAppSchema } from './RoomAppSchema'; import * as css from './RoomAppView.css'; @@ -32,7 +28,7 @@ export function RoomAppView({ room, onShowChat }: RoomAppViewProps) { async (payload: PaarrotUiActionContent) => { await mx.sendEvent(room.roomId, MessageEvent.PaarrotUiAction as any, payload); }, - [mx, room.roomId] + [mx, room.roomId], ); return ( diff --git a/src/app/features/room-app/sanitizeRoomAppCss.ts b/src/app/features/room-app/sanitizeRoomAppCss.ts index 70de5cfb..3b9643b9 100644 --- a/src/app/features/room-app/sanitizeRoomAppCss.ts +++ b/src/app/features/room-app/sanitizeRoomAppCss.ts @@ -84,8 +84,6 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string { export function isAllowedRoomAppImageSrc(src: string): boolean { const trimmed = src.trim(); return ( - trimmed.startsWith('mxc://') || - trimmed.startsWith('https://') || - trimmed.startsWith('http://') + trimmed.startsWith('mxc://') || trimmed.startsWith('https://') || trimmed.startsWith('http://') ); } diff --git a/src/app/features/room-nav/CallParticipantsIndicator.tsx b/src/app/features/room-nav/CallParticipantsIndicator.tsx index 95cbd3db..b45a6a1c 100644 --- a/src/app/features/room-nav/CallParticipantsIndicator.tsx +++ b/src/app/features/room-nav/CallParticipantsIndicator.tsx @@ -37,23 +37,22 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP return mxcUrlToHttp(mx, mxcUrl, useAuthentication, 48, 48, 'crop') ?? undefined; }; - const getParticipantName = (userId: string): string => { - return getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; - }; + const getParticipantName = (userId: string): string => + getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId; /** * Check if a participant is currently speaking */ const isParticipantSpeaking = (userId: string): boolean => { if (!activeCall) return false; - + // Direct check for Matrix user ID (works for local user) if (activeCall.activeSpeakers.has(userId)) return true; - + // For remote users, activeSpeakers contains LiveKit identities (deviceId_timestamp) const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + // Check if any active speaker has this user's deviceId return Array.from(activeCall.activeSpeakers).some((speakerId) => { const underscoreIndex = speakerId.lastIndexOf('_'); @@ -67,14 +66,14 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP */ const isParticipantMuted = (userId: string): boolean => { if (!activeCall) return false; - + // For local user, check activeCall.isMuted if (userId === myUserId) return activeCall.isMuted; - + // For remote users, mutedParticipants contains LiveKit identities (deviceId_timestamp) const member = callMembers.find((m) => m.userId === userId); if (!member) return false; - + // Check if any muted participant has this user's deviceId return Array.from(activeCall.mutedParticipants).some((mutedId) => { const underscoreIndex = mutedId.lastIndexOf('_'); @@ -115,7 +114,7 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP const isSpeaking = isParticipantSpeaking(member.userId); const isMuted = isParticipantMuted(member.userId); const isDeafened = isLocalUserDeafened(member.userId); - + return ( - @@ -148,13 +147,17 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP )} - {getParticipantName(member.userId)} diff --git a/src/app/features/room-nav/RoomNavCategoryButton.tsx b/src/app/features/room-nav/RoomNavCategoryButton.tsx index fd394a2d..25264d4a 100644 --- a/src/app/features/room-nav/RoomNavCategoryButton.tsx +++ b/src/app/features/room-nav/RoomNavCategoryButton.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { as, Chip, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import classNames from 'classnames'; +import { Icon, Icons } from '../../components/icons'; import * as css from './styles.css'; export const RoomNavCategoryButton = as<'button', { closed?: boolean }>( @@ -25,5 +25,5 @@ export const RoomNavCategoryButton = as<'button', { closed?: boolean }>( {children} - ) + ), ); diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index ae439e58..eb768326 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -2,15 +2,36 @@ import React, { MouseEventHandler, forwardRef, useState, useMemo } from 'react'; import { Room, EventTimeline } from 'matrix-js-sdk'; import { useAtomValue } from 'jotai'; import { useNavigate } from 'react-router-dom'; -import { Avatar, Box, IconButton, Text, Menu, MenuItem, config, PopOut, toRem, Line, RectCords, Badge, Spinner, Tooltip, TooltipProvider } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Avatar, + Box, + IconButton, + Text, + Menu, + MenuItem, + config, + PopOut, + toRem, + Line, + RectCords, + Badge, + Spinner, + Tooltip, + TooltipProvider, +} from 'folds'; import { useFocusWithin, useHover } from 'react-aria'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../components/icons'; import { NavItem, NavItemContent, NavItemOptions, NavLink } from '../../components/nav'; import * as css from '../../components/nav/styles.css'; import { UnreadBadge, UnreadBadgeCenter } from '../../components/unread-badge'; import { RoomAvatar, RoomIcon } from '../../components/room-avatar'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl, guessPerfectParent, getOrphanParents } from '../../utils/room'; +import { + getDirectRoomAvatarUrl, + getRoomAvatarUrl, + guessPerfectParent, + getOrphanParents, +} from '../../utils/room'; import { nameInitials } from '../../utils/common'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useRoomUnread } from '../../state/hooks/unread'; @@ -24,7 +45,12 @@ import { useRoomTypingMember } from '../../hooks/useRoomTypingMembers'; import { TypingIndicator } from '../../components/typing-indicator'; import { stopPropagation } from '../../utils/keyboard'; import { getMatrixToRoom } from '../../plugins/matrix-to'; -import { getCanonicalAliasOrRoomId, guessDmRoomUserId, isRoomAlias, mxcUrlToHttp } from '../../utils/matrix'; +import { + getCanonicalAliasOrRoomId, + guessDmRoomUserId, + isRoomAlias, + mxcUrlToHttp, +} from '../../utils/matrix'; import { getViaServers } from '../../plugins/via-servers'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useSetting } from '../../state/hooks/settings'; @@ -257,7 +283,7 @@ const RoomNavItemMenu = forwardRef( ); - } + }, ); type RoomNavItemProps = { @@ -296,10 +322,10 @@ export function RoomNavItem({ const isDirect = Boolean(direct || mDirects.has(room.roomId)); const dmUserId = isDirect ? guessDmRoomUserId(room, mx.getSafeUserId()) : undefined; const dmPresence = useUserPresence(dmUserId ?? ''); - + const shouldShowIcon = !hideIcon || (hideIcon && avatarUrl); const typingMember = useRoomTypingMember(room.roomId).filter( - (receipt) => receipt.userId !== mx.getUserId() + (receipt) => receipt.userId !== mx.getUserId(), ); const roomToParents = useAtomValue(roomToParentsAtom); @@ -311,7 +337,7 @@ export function RoomNavItem({ if (participatedThreads.length === 0) return undefined; const firstThread = participatedThreads[0]; - const rootEvent = firstThread.rootEvent; + const { rootEvent } = firstThread; if (!rootEvent) return undefined; const rootBody = rootEvent.getContent()?.body ?? ''; @@ -324,18 +350,24 @@ export function RoomNavItem({ // Get parent space for DMs const parentSpaceInfo = (() => { if (!isDirect || !mDirects.has(room.roomId)) return undefined; - + const orphanParents = getOrphanParents(roomToParents, room.roomId); if (orphanParents.length === 0) return undefined; - + const parentSpaceId = guessPerfectParent(mx, room.roomId, orphanParents) ?? orphanParents[0]; const parentSpace = mx.getRoom(parentSpaceId); if (!parentSpace) return undefined; - const avatarEvent = parentSpace.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(StateEvent.RoomAvatar, ''); + const avatarEvent = parentSpace + .getLiveTimeline() + .getState(EventTimeline.FORWARDS) + ?.getStateEvents(StateEvent.RoomAvatar, ''); const avatarContent = avatarEvent?.getContent(); - const avatarMxc = avatarContent && typeof avatarContent.url === 'string' ? avatarContent.url : undefined; - const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined : undefined; + const avatarMxc = + avatarContent && typeof avatarContent.url === 'string' ? avatarContent.url : undefined; + const avatarUrl = avatarMxc + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) + : undefined; return { name: parentSpace.name, @@ -360,11 +392,11 @@ export function RoomNavItem({ const handleRoomClick: MouseEventHandler = (evt) => { if (selected) { evt.preventDefault(); - - const shouldScroll = + + const shouldScroll = scrollToLatestBehavior === ScrollToLatestBehavior.Always || (scrollToLatestBehavior === ScrollToLatestBehavior.OnNewMessage && unread !== undefined); - + if (shouldScroll) { navigate(linkPath, { replace: true, state: { scrollToLatest: Date.now() } }); } @@ -388,13 +420,13 @@ export function RoomNavItem({ > - + {shouldShowIcon && (isDirect ? ( @@ -443,7 +475,12 @@ export function RoomNavItem({ )} ))} - + {room.name} @@ -469,76 +506,79 @@ export function RoomNavItem({ - {optionsVisible && ( - - - {parentSpaceInfo && ( - - Space: {parentSpaceInfo.name} - - } - > - {(triggerRef) => ( - - ( - - {nameInitials(parentSpaceInfo.name, 1)} - - )} - /> - - )} - - )} - {optionsVisible && ( - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > - setMenuAnchor(undefined)} - notificationMode={notificationMode} - /> - - } - > - + + {parentSpaceInfo && ( + + Space: {parentSpaceInfo.name} + + } > - - - - )} - - - )} + {(triggerRef) => ( + + ( + {nameInitials(parentSpaceInfo.name, 1)} + )} + /> + + )} + + )} + {optionsVisible && ( + setMenuAnchor(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, + }} + > + setMenuAnchor(undefined)} + notificationMode={notificationMode} + /> + + } + > + + + + + )} + + + )} diff --git a/src/app/features/room-nav/UnjoinedSubRoomItem.tsx b/src/app/features/room-nav/UnjoinedSubRoomItem.tsx index 99672380..b20d6e28 100644 --- a/src/app/features/room-nav/UnjoinedSubRoomItem.tsx +++ b/src/app/features/room-nav/UnjoinedSubRoomItem.tsx @@ -1,7 +1,7 @@ import React, { useCallback } from 'react'; import { Box, Chip, Spinner, Text, Tooltip, TooltipProvider, color, config, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { MatrixError, Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; @@ -28,12 +28,12 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS const viaServers = [getServerFromRoomId(roomId)].filter(Boolean); const [joinState, join] = useAsyncCallback( - useCallback(() => mx.joinRoom(roomId, { viaServers }), [mx, roomId, viaServers]) + useCallback(() => mx.joinRoom(roomId, { viaServers }), [mx, roomId, viaServers]), ); const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error; const paddingLeft = depth > 0 ? '30px' : undefined; - + let treeIcon = ''; if (depth > 0) { treeIcon = isLast ? '╰' : '├'; @@ -52,15 +52,17 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS gap="200" > {treeIcon && ( - + {treeIcon} )} @@ -96,7 +98,11 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS size="400" radii="Pill" before={ - canJoin ? : + canJoin ? ( + + ) : ( + + ) } onClick={join} disabled={!canJoin} diff --git a/src/app/features/room-settings/RoomSettings.tsx b/src/app/features/room-settings/RoomSettings.tsx index 42a3e9e6..76843a52 100644 --- a/src/app/features/room-settings/RoomSettings.tsx +++ b/src/app/features/room-settings/RoomSettings.tsx @@ -1,8 +1,8 @@ import React, { useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import { Avatar, Box, config, IconButton, MenuItem, Text } from 'folds'; -import { Icon, Icons, IconSrc } from '../../components/icons'; import { JoinRule } from 'matrix-js-sdk'; +import { Icon, Icons, IconSrc } from '../../components/icons'; import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -60,7 +60,7 @@ const useRoomSettingsMenuItems = (): RoomSettingsMenuItem[] => icon: Icons.Terminal, }, ], - [] + [], ); type RoomSettingsProps = { @@ -78,7 +78,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) { const joinRuleContent = useRoomJoinRule(room); const avatarUrl = roomAvatar - ? mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const screenSize = useScreenSizeContext(); @@ -168,9 +168,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) { {activePage === RoomSettingsPage.PermissionsPage && ( )} - {activePage === RoomSettingsPage.SubRoomsPage && ( - - )} + {activePage === RoomSettingsPage.SubRoomsPage && } {activePage === RoomSettingsPage.EmojisStickersPage && ( )} diff --git a/src/app/features/room-settings/sub-rooms/SubRooms.tsx b/src/app/features/room-settings/sub-rooms/SubRooms.tsx index 87bad3b3..d651e985 100644 --- a/src/app/features/room-settings/sub-rooms/SubRooms.tsx +++ b/src/app/features/room-settings/sub-rooms/SubRooms.tsx @@ -1,7 +1,7 @@ import React, { useState, useCallback } from 'react'; import { Box, Button, Text, config, IconButton, Chip, Line } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useRoom } from '../../../hooks/useRoom'; import { useRoomSubRooms, PaarrotSubRoomsContent } from '../../../hooks/useRoomSubRooms'; @@ -15,7 +15,15 @@ import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; import { roomToParentsAtom } from '../../../state/room/roomToParents'; import { isSpace } from '../../../utils/room'; -function SubRoomItem({ roomId, onRemove, canEdit }: { roomId: string; onRemove: (roomId: string) => void; canEdit: boolean }) { +function SubRoomItem({ + roomId, + onRemove, + canEdit, +}: { + roomId: string; + onRemove: (roomId: string) => void; + canEdit: boolean; +}) { const allJoinedRooms = useAllJoinedRoomsSet(); const getRoom = useGetRoom(allJoinedRooms); const room = getRoom(roomId); @@ -77,26 +85,26 @@ export function SubRooms() { // eslint-disable-next-line @typescript-eslint/no-explicit-any await mx.sendStateEvent(room.roomId, StateEvent.PaarrotSubRooms as any, content, ''); }, - [mx, room] - ) + [mx, room], + ), ); const handleRemoveSubRoom = useCallback( (roomId: string) => { - const newSubRooms = subRooms.filter(id => id !== roomId); + const newSubRooms = subRooms.filter((id) => id !== roomId); updateSubRooms(newSubRooms); }, - [subRooms, updateSubRooms] + [subRooms, updateSubRooms], ); const handleAddRoom = useCallback(async () => { const trimmedId = addRoomId.trim(); if (!trimmedId) return; - + // Try to resolve room - if it's already joined, use the actual room ID const targetRoom = mx.getRoom(trimmedId); const roomIdToAdd = targetRoom ? targetRoom.roomId : trimmedId; - + // Allow adding any room ID (even if not joined) if (!subRooms.includes(roomIdToAdd)) { const newSubRooms = [...subRooms, roomIdToAdd]; @@ -121,14 +129,14 @@ export function SubRooms() { // eslint-disable-next-line @typescript-eslint/no-explicit-any StateEvent.SpaceChild as any, { via: spaceViaServers }, - roomIdToAdd + roomIdToAdd, ); } catch (spaceError) { // eslint-disable-next-line no-console console.warn(`Failed to add sub-room to space ${parentSpaceId}:`, spaceError); } } - }) + }), ); } @@ -144,8 +152,8 @@ export function SubRooms() { Sub-Rooms - Sub-rooms are nested rooms that appear indented under this room in the room list. - They work like sub-spaces but for regular rooms. + Sub-rooms are nested rooms that appear indented under this room in the room list. They + work like sub-spaces but for regular rooms. @@ -217,14 +225,20 @@ export function SubRooms() { ) : ( {subRooms.map((roomId) => ( - + ))} )} {updateState.status === AsyncStatus.Error && ( - Failed to update sub-rooms: {String((updateState.error as Error)?.message || updateState.error)} + Failed to update sub-rooms:{' '} + {String((updateState.error as Error)?.message || updateState.error)} )} diff --git a/src/app/features/room/CommandAutocomplete.tsx b/src/app/features/room/CommandAutocomplete.tsx index dbf04db5..430bd9fa 100644 --- a/src/app/features/room/CommandAutocomplete.tsx +++ b/src/app/features/room/CommandAutocomplete.tsx @@ -39,18 +39,18 @@ export function CommandAutocomplete({ }: CommandAutocompleteProps) { const mx = useMatrixClient(); const commands = useCommands(mx, room); - + // Merge built-in commands with plugin commands const commandNames = useMemo(() => { const builtInCommands = Object.keys(commands) as Command[]; - const pluginCommands = pluginRegistry.getCommands().map(cmd => cmd.name); + const pluginCommands = pluginRegistry.getCommands().map((cmd) => cmd.name); return [...builtInCommands, ...pluginCommands]; }, [commands]); const [result, search, resetSearch] = useAsyncSearch( commandNames, useCallback((commandName: string) => commandName, []), - SEARCH_OPTIONS + SEARCH_OPTIONS, ); const autoCompleteNames = result ? result.items : commandNames; @@ -89,9 +89,9 @@ export function CommandAutocomplete({ {autoCompleteNames.map((commandName) => { // Get description from built-in commands or plugin commands const builtInCmd = commands[commandName as Command]; - const pluginCmd = pluginRegistry.getCommands().find(cmd => cmd.name === commandName); + const pluginCmd = pluginRegistry.getCommands().find((cmd) => cmd.name === commandName); const description = builtInCmd?.description || pluginCmd?.command.description || ''; - + return ( members.filter(membershipFilter.filterFn).sort(memberSort.sortFn).sort(memberPowerSort), - [members, membershipFilter, memberSort, memberPowerSort] + [members, membershipFilter, memberSort, memberPowerSort], ); const [result, search, resetSearch] = useAsyncSearch( filteredMembers, getRoomMemberStr, - SEARCH_OPTIONS + SEARCH_OPTIONS, ); if (!result && searchInputRef.current?.value) search(searchInputRef.current.value); @@ -214,9 +231,9 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { if (evt.target.value) search(evt.target.value); else resetSearch(); }, - [search, resetSearch] + [search, resetSearch], ), - { wait: 200 } + { wait: 200 }, ); const handleMemberClick: MouseEventHandler = (evt) => { @@ -257,7 +274,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { onClick={ ((evt) => setAnchor( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } variant="Background" @@ -289,7 +306,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { onClick={ ((evt) => setAnchor( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } variant="Background" @@ -402,7 +419,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { onClick={handleMemberClick} pressed={openProfileUserId === tagOrMember.userId} typing={typingMembers.some( - (receipt) => receipt.userId === tagOrMember.userId + (receipt) => receipt.userId === tagOrMember.userId, )} />
diff --git a/src/app/features/room/Room.tsx b/src/app/features/room/Room.tsx index c8d46bb8..2fae5ed5 100644 --- a/src/app/features/room/Room.tsx +++ b/src/app/features/room/Room.tsx @@ -1,9 +1,9 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { Box, Button, Line, Text, config } from 'folds'; -import { decodeRouteParam } from '../../pages/pathUtils'; import { useParams } from 'react-router-dom'; import { isKeyHotkey } from 'is-hotkey'; import { useAtom, useSetAtom } from 'jotai'; +import { decodeRouteParam } from '../../pages/pathUtils'; import { RoomView } from './RoomView'; import { MembersDrawer } from './MembersDrawer'; import { MediaDrawer } from './room-media-menu'; @@ -41,8 +41,7 @@ export function Room() { const forumRoom = isForum(room); const skinny = screenSize !== ScreenSize.Desktop; const showMediaSolo = skinny && isMediaDrawer; - const showRightDrawer = - !skinny && (isPeopleDrawer || isMediaDrawer); + const showRightDrawer = !skinny && (isPeopleDrawer || isMediaDrawer); const uiEvent = useStateEvent(room, StateEvent.PaarrotUi); const hasAppUi = useMemo(() => !!parsePaarrotUiContent(uiEvent?.getContent()), [uiEvent]); @@ -68,8 +67,8 @@ export function Room() { markAsRead(room.roomId, hideActivity); } }, - [markAsRead, room.roomId, hideActivity] - ) + [markAsRead, room.roomId, hideActivity], + ), ); return ( diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 8d6719e8..532af812 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -11,7 +11,21 @@ import { useAtom, useAtomValue } from 'jotai'; import { isKeyHotkey } from 'is-hotkey'; import { EventType, IContent, MsgType, RelationType, Room } from 'matrix-js-sdk'; import { Transforms, Editor } from 'slate'; -import { Box, Dialog, IconButton, Line, Overlay, OverlayBackdrop, OverlayCenter, PopOut, Scroll, Text, color, config, toRem } from 'folds'; +import { + Box, + Dialog, + IconButton, + Line, + Overlay, + OverlayBackdrop, + OverlayCenter, + PopOut, + Scroll, + Text, + color, + config, + toRem, +} from 'folds'; import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -43,12 +57,7 @@ import { } from '../../components/editor'; import { EmojiBoard, EmojiBoardTab } from '../../components/emoji-board'; import { UseStateProvider } from '../../components/UseStateProvider'; -import { - TUploadContent, - getImageInfo, - getMxIdLocalPart, - mxcUrlToHttp, -} from '../../utils/matrix'; +import { TUploadContent, getImageInfo, getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; import { useTypingStatusUpdater } from '../../hooks/useTypingStatusUpdater'; import { useFilePicker } from '../../hooks/useFilePicker'; import { useFilePasteHandler } from '../../hooks/useFilePasteHandler'; @@ -85,7 +94,12 @@ import { getImageMsgContent, getVideoMsgContent, } from './msgContent'; -import { getMemberDisplayName, getMentionContent, trimReplyFromBody } from '../../utils/room'; +import { + getMemberDisplayName, + getMentionContent, + trimReplyFromBody, + getMemberAvatarMxc, +} from '../../utils/room'; import { CommandAutocomplete } from './CommandAutocomplete'; import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '../../hooks/useCommands'; import { pluginRegistry } from '../settings/plugins/PluginAPI'; @@ -105,7 +119,6 @@ import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag'; import { usePowerLevelTags } from '../../hooks/usePowerLevelTags'; import { useComposingCheck } from '../../hooks/useComposingCheck'; import { useOtherUserColor } from '../../hooks/useUserColor'; -import { getMemberAvatarMxc } from '../../utils/room'; import { convertEmoticons, convertEmoticonsInHtml } from '../../utils/emoticonConverter'; import * as css from './RoomInput.css'; @@ -151,7 +164,7 @@ export const RoomInput = forwardRef( replyPreviewHighlightClassName, onMessageSent, }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -179,7 +192,7 @@ export const RoomInput = forwardRef( const accessibleTagColors = useAccessiblePowerTagColors( theme.kind, creatorsTag, - powerLevelTags + powerLevelTags, ); // Get custom user color from avatar metadata @@ -191,13 +204,14 @@ export const RoomInput = forwardRef( : undefined; // Priority: custom user color > legacy/direct colorMXID > tag color const replyUsernameColor = - replyCustomColor ?? (legacyUsernameColor || direct ? colorMXID(replyUserID ?? '') : replyPowerColor); + replyCustomColor ?? + (legacyUsernameColor || direct ? colorMXID(replyUserID ?? '') : replyPowerColor); const [uploadBoard, setUploadBoard] = useState(true); const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(roomId)); const uploadFamilyObserverAtom = createUploadFamilyObserverAtom( roomUploadAtomFamily, - selectedFiles.map((f) => f.file) + selectedFiles.map((f) => f.file), ); const uploadBoardHandlers = useRef(); const editorRef = useRef(null); @@ -218,7 +232,9 @@ export const RoomInput = forwardRef( useEffect(() => { setCommandValidator((commandName: string) => { const isBuiltInCommand = commands[commandName as Command]; - const isPluginCommand = pluginRegistry.getCommands().some(cmd => cmd.name === commandName); + const isPluginCommand = pluginRegistry + .getCommands() + .some((cmd) => cmd.name === commandName); return !!(isBuiltInCommand || isPluginCommand); }); }, [commands]); @@ -229,7 +245,7 @@ export const RoomInput = forwardRef( setUploadBoard(true); await enqueueFiles(files); }, - [enqueueFiles] + [enqueueFiles], ); const pickFile = useFilePicker(handleFiles, true); const handlePaste = useFilePasteHandler(handleFiles); @@ -252,7 +268,7 @@ export const RoomInput = forwardRef( resetEditor(editor); resetEditorHistory(editor); }, - [roomId, editor, setMsgDraft] + [roomId, editor, setMsgDraft], ); const handleFileMetadata = useCallback( @@ -263,7 +279,7 @@ export const RoomInput = forwardRef( replacement: { ...fileItem, metadata }, }); }, - [setSelectedFiles] + [setSelectedFiles], ); const handleRemoveUpload = useCallback( @@ -275,7 +291,7 @@ export const RoomInput = forwardRef( }); uploads.forEach((u) => roomUploadAtomFamily.remove(u)); }, - [setSelectedFiles, selectedFiles] + [setSelectedFiles, selectedFiles], ); const handleCancelUpload = (uploads: Upload[]) => { @@ -294,7 +310,7 @@ export const RoomInput = forwardRef( }); const carouselUuid = imageUploads.length > 1 ? createCarouselUuid() : undefined; const imageUploadIndexByFile = new Map( - imageUploads.map((upload, index) => [upload.file, index] as const) + imageUploads.map((upload, index) => [upload.file, index] as const), ); const contentsPromises = uploads.map(async (upload) => { @@ -314,7 +330,7 @@ export const RoomInput = forwardRef( index: imageIndex, total: imageUploads.length, } - : undefined + : undefined, ); } if (fileItem.file.type.startsWith('video')) { @@ -340,7 +356,7 @@ export const RoomInput = forwardRef( allowTextFormatting: true, allowBlockMarkdown: isMarkdown, allowInlineMarkdown: isMarkdown, - }) + }), ); let msgType = MsgType.Text; @@ -351,8 +367,10 @@ export const RoomInput = forwardRef( const potentialCommand = match[1]; // Check if it's a valid command (built-in or plugin) const isBuiltInCommand = commands[potentialCommand as Command]; - const isPluginCommand = pluginRegistry.getCommands().some(cmd => cmd.name === potentialCommand); - + const isPluginCommand = pluginRegistry + .getCommands() + .some((cmd) => cmd.name === potentialCommand); + if (isBuiltInCommand || isPluginCommand) { commandName = potentialCommand; } @@ -459,7 +477,7 @@ export const RoomInput = forwardRef( 'm.in_reply_to': { event_id: inReplyToEventId }, }; } - + // Process message through plugin interceptors try { const messageContext = { @@ -470,7 +488,7 @@ export const RoomInput = forwardRef( metadata: {}, }; const processedContext = await pluginRegistry.processBeforeSend(messageContext); - + // Update content with intercepted values content.body = processedContext.content; if (processedContext.formatted) { @@ -479,7 +497,7 @@ export const RoomInput = forwardRef( } catch (err) { console.error('[RoomInput] Plugin interceptor error:', err); } - + mx.sendMessage(roomId, content as any); resetEditor(editor); resetEditorHistory(editor); @@ -487,7 +505,20 @@ export const RoomInput = forwardRef( setCommandHint(undefined); sendTypingStatus(false); onMessageSent?.(); - }, [mx, roomId, threadRootId, threadReplyToEventId, editor, replyDraft, sendTypingStatus, setReplyDraft, isMarkdown, commands, autoConvertEmoticons, onMessageSent]); + }, [ + mx, + roomId, + threadRootId, + threadReplyToEventId, + editor, + replyDraft, + sendTypingStatus, + setReplyDraft, + isMarkdown, + commands, + autoConvertEmoticons, + onMessageSent, + ]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -511,7 +542,7 @@ export const RoomInput = forwardRef( setReplyDraft(undefined); } }, - [submit, setReplyDraft, enterForNewline, autocompleteQuery, isComposing, commandHint] + [submit, setReplyDraft, enterForNewline, autocompleteQuery, isComposing, commandHint], ); const handleKeyUp: KeyboardEventHandler = useCallback( @@ -534,12 +565,12 @@ export const RoomInput = forwardRef( // Check if user is typing a command and show hint const plainText = toPlainText(editor.children, false).trim(); const commandMatch = plainText.match(/^\/(\w+)(\s|$)/); - + if (commandMatch) { const commandName = commandMatch[1]; const builtInCmd = commands[commandName as Command]; - const pluginCmd = pluginRegistry.getCommands().find(cmd => cmd.name === commandName); - + const pluginCmd = pluginRegistry.getCommands().find((cmd) => cmd.name === commandName); + if (builtInCmd) { setCommandHint({ command: commandName, @@ -558,7 +589,7 @@ export const RoomInput = forwardRef( setCommandHint(undefined); } }, - [editor, sendTypingStatus, hideActivity, commands] + [editor, sendTypingStatus, hideActivity, commands], ); const handleCloseAutocomplete = useCallback(() => { @@ -577,7 +608,7 @@ export const RoomInput = forwardRef( const info = await getImageInfo( await loadImageElement(stickerUrl), - await getImageUrlBlob(stickerUrl) + await getImageUrlBlob(stickerUrl), ); mx.sendEvent(roomId, EventType.Sticker, { @@ -705,7 +736,10 @@ export const RoomInput = forwardRef( /{commandHint.command} {commandHint.args && commandHint.args.length > 0 && ( - {commandHint.args.map(arg => `[${arg}]`).join(' ')} + + {' '} + {commandHint.args.map((arg) => `[${arg}]`).join(' ')} + )} {commandHint.description && ( @@ -738,7 +772,9 @@ export const RoomInput = forwardRef( className={replyPreviewHighlightClassName} > {!hideReplyThreadIndicator && - replyDraft.relation?.rel_type === RelationType.Thread && } + replyDraft.relation?.rel_type === RelationType.Thread && ( + + )} ( anchor={ emojiBoardTab === undefined ? undefined - : emojiBtnRef.current?.getBoundingClientRect() ?? undefined + : (emojiBtnRef.current?.getBoundingClientRect() ?? undefined) } content={ ( />
); - } + }, ); diff --git a/src/app/features/room/RoomInputPlaceholder.tsx b/src/app/features/room/RoomInputPlaceholder.tsx index 77c7ccf3..45a6dc31 100644 --- a/src/app/features/room/RoomInputPlaceholder.tsx +++ b/src/app/features/room/RoomInputPlaceholder.tsx @@ -7,5 +7,5 @@ import * as css from './RoomInputPlaceholder.css'; export const RoomInputPlaceholder = as<'div', ComponentProps>( ({ className, ...props }, ref) => ( - ) + ), ); diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 57fd31e4..2d4c933c 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -30,12 +30,25 @@ import { ReactEditor } from 'slate-react'; import { Editor } from 'slate'; import to from 'await-to-js'; import { useAtomValue, useSetAtom } from 'jotai'; -import { Badge, Box, Chip, ContainerColor, IconButton, Line, Scroll, Text, as, color, config, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Badge, + Box, + Chip, + ContainerColor, + IconButton, + Line, + Scroll, + Text, + as, + color, + config, + toRem, +} from 'folds'; import { isKeyHotkey } from 'is-hotkey'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { useTranslation } from 'react-i18next'; import { useLocation } from 'react-router-dom'; +import { Icon, Icons } from '../../components/icons'; import { eventWithShortcode, factoryEventSentBy, getMxIdLocalPart } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useVirtualPaginator, ItemRange } from '../../hooks/useVirtualPaginator'; @@ -196,7 +209,7 @@ const TimelineFloat = as<'div', css.TimelineFloatVariants>( {...props} ref={ref} /> - ) + ), ); const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>( @@ -206,7 +219,7 @@ const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>( {children} - ) + ), ); type CarouselScrollerProps = { @@ -294,7 +307,7 @@ export const getEventTimeline = (room: Room, eventId: string): EventTimeline | u export const getFirstLinkedTimeline = ( timeline: EventTimeline, - direction: Direction + direction: Direction, ): EventTimeline => { const linkedTm = timeline.getNeighbouringTimeline(direction); if (!linkedTm) return timeline; @@ -324,7 +337,7 @@ export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => { export const getTimelineAndBaseIndex = ( timelines: EventTimeline[], - index: number + index: number, ): [EventTimeline | undefined, number] => { let uptoTimelineLen = 0; const timeline = timelines.find((t) => { @@ -345,7 +358,7 @@ export const getTimelineEvent = (timeline: EventTimeline, index: number): Matrix export const getEventIdAbsoluteIndex = ( timelines: EventTimeline[], eventTimeline: EventTimeline, - eventId: string + eventId: string, ): number | undefined => { const timelineIndex = timelines.findIndex((t) => t === eventTimeline); if (timelineIndex === -1) return undefined; @@ -375,12 +388,12 @@ const useEventTimelineLoader = ( mx: MatrixClient, room: Room, onLoad: (eventId: string, linkedTimelines: EventTimeline[], evtAbsIndex: number) => void, - onError: (err: Error | null) => void + onError: (err: Error | null) => void, ) => { const loadEventTimeline = useCallback( async (eventId: string) => { const [err, replyEvtTimeline] = await to( - mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId) + mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId), ); if (!replyEvtTimeline) { onError(err ?? null); @@ -396,7 +409,7 @@ const useEventTimelineLoader = ( onLoad(eventId, linkedTimelines, absIndex); }, - [mx, room, onLoad, onError] + [mx, room, onLoad, onError], ); return loadEventTimeline; @@ -406,7 +419,7 @@ const useTimelinePagination = ( mx: MatrixClient, timeline: Timeline, setTimeline: Dispatch>, - limit: number + limit: number, ) => { const timelineRef = useRef(timeline); timelineRef.current = timeline; @@ -418,7 +431,7 @@ const useTimelinePagination = ( const recalibratePagination = ( linkedTimelines: EventTimeline[], timelinesEventsCount: number[], - backwards: boolean + backwards: boolean, ) => { const topTimeline = linkedTimelines[0]; const timelineMatch = (mt: EventTimeline) => (t: EventTimeline) => t === mt; @@ -452,7 +465,7 @@ const useTimelinePagination = ( if (!timelineToPaginate) return; const paginationToken = timelineToPaginate.getPaginationToken( - backwards ? Direction.Backward : Direction.Forward + backwards ? Direction.Backward : Direction.Forward, ); if ( !paginationToken && @@ -468,7 +481,7 @@ const useTimelinePagination = ( mx.paginateEventTimeline(timelineToPaginate, { backwards, limit, - }) + }), ); if (err) { // TODO: handle pagination error. @@ -476,7 +489,7 @@ const useTimelinePagination = ( } const fetchedTimeline = timelineToPaginate.getNeighbouringTimeline( - backwards ? Direction.Backward : Direction.Forward + backwards ? Direction.Backward : Direction.Forward, ) ?? timelineToPaginate; // Decrypt all event ahead of render cycle const roomId = fetchedTimeline.getRoomId(); @@ -502,7 +515,7 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) eventRoom, toStartOfTimeline, removed, - data + data, ) => { if (eventRoom?.roomId !== room.roomId || !data.liveEvent) return; onArrive(mEvent); @@ -572,12 +585,12 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); const [legacyUsernameColor] = useSetting(settingsAtom, 'legacyUsernameColor'); const direct = useIsDirectRoom(); - const dmUserId = direct ? room.guessDMUserId() ?? undefined : undefined; + const dmUserId = direct ? (room.guessDMUserId() ?? undefined) : undefined; const [timelineHovered, setTimelineHovered] = useState(false); const { assetUrls: dmAssetUrls } = useOtherUserCollectibles(dmUserId ?? ''); const dmNameplateUrl = pickNameplateUrl(dmAssetUrls); const dmNameplateIsVideo = Boolean( - dmAssetUrls['nameplate:animated'] || dmAssetUrls['nameplate:asset.webm'] + dmAssetUrls['nameplate:animated'] || dmAssetUrls['nameplate:asset.webm'], ); const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents'); const [hideNickAvatarEvents] = useSetting(settingsAtom, 'hideNickAvatarEvents'); @@ -589,12 +602,15 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const roomWideEmbedFilters = useRoomWideEmbedFilters(room); const combinedEmbedFilters = useMemo( () => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters), - [personalEmbedFilters, roomWideEmbedFilters] + [personalEmbedFilters, roomWideEmbedFilters], ); const [showHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents'); const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); - const { bursts: emojiConfettiBursts, removeBurst: removeEmojiConfettiBurst, handleJumboEmojiClick } = - useJumboEmojiConfetti(room); + const { + bursts: emojiConfettiBursts, + removeBurst: removeEmojiConfettiBurst, + handleJumboEmojiClick, + } = useJumboEmojiConfetti(room); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); @@ -619,7 +635,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const accessiblePowerTagColors = useAccessiblePowerTagColors( theme.kind, creatorsTag, - powerLevelTags + powerLevelTags, ); const permissions = useRoomPermissions(creators, powerLevels); @@ -641,13 +657,13 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const scrollToLatest = (location.state as { scrollToLatest?: boolean } | null)?.scrollToLatest; const savedScrollRef = useRef( - eventId || scrollToLatest ? undefined : getRoomScrollState(room.roomId) + eventId || scrollToLatest ? undefined : getRoomScrollState(room.roomId), ); const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents); const [unreadInfo, setUnreadInfo] = useState(() => - getRoomUnreadInfo(room, scrollToLatestBehavior !== ScrollToLatestBehavior.Always) + getRoomUnreadInfo(room, scrollToLatestBehavior !== ScrollToLatestBehavior.Always), ); const readUptoEventIdRef = useRef(); if (unreadInfo) { @@ -655,9 +671,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli } const atBottomAnchorRef = useRef(null); - const [atBottom, setAtBottom] = useState( - () => savedScrollRef.current?.atBottom ?? true - ); + const [atBottom, setAtBottom] = useState(() => savedScrollRef.current?.atBottom ?? true); const atBottomRef = useRef(atBottom); atBottomRef.current = atBottom; @@ -666,7 +680,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli content: string; } | null>(null); const [returnToEventId, setReturnToEventIdState] = useState( - () => getRoomReturnAnchor(room.roomId) ?? null + () => getRoomReturnAnchor(room.roomId) ?? null, ); const setReturnToEventId = useCallback( @@ -675,7 +689,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli else clearRoomReturnAnchor(room.roomId); setReturnToEventIdState(eventId); }, - [room.roomId] + [room.roomId], ); const scrollRef = useRef(null); @@ -727,10 +741,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli () => ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)), ), }), - [mx, room, mentionClickHandler] + [mx, room, mentionClickHandler], ); const htmlReactParserOptions = useMemo( () => @@ -740,7 +754,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, }), - [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication] + [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication], ); const parseMemberEvent = useMemberEventParser(); @@ -776,15 +790,14 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const scrollEl = scrollRef.current; if (!scrollEl) return; - const distanceFromBottom = - scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight; + const distanceFromBottom = scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight; saveRoomScrollState(roomId, { top: scrollEl.scrollTop, atBottom: distanceFromBottom <= 50, range: timelineRef.current.range, }); }, - [eventId] + [eventId], ); const eventsLength = getTimelinesEventsCount(timeline.linkedTimelines); @@ -815,7 +828,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli mx, timeline, setTimeline, - PAGINATION_LIMIT + PAGINATION_LIMIT, ); const getScrollElement = useCallback(() => scrollRef.current, []); @@ -831,7 +844,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli (index: number) => (scrollRef.current?.querySelector(`[data-message-item="${index}"]`) as HTMLElement) ?? undefined, - [] + [], ), onEnd: handleTimelinePagination, }); @@ -857,7 +870,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli }, }); }, - [alive] + [alive], ), useCallback(() => { if (!alive()) return; @@ -865,7 +878,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli scrollToBottomRef.current.count += 1; scrollToBottomRef.current.smooth = false; scrollToBottomRef.current.force = true; - }, [alive, room]) + }, [alive, room]), ); useLiveEventArrive( @@ -890,7 +903,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli // Handle own messages and focus if (isOwnMessage) { setLatestUnreadMessage(null); - if (document.hasFocus() && (!unreadInfo)) { + if (document.hasFocus() && !unreadInfo) { const roomId = mEvt.getRoomId(); if (roomId) { requestAnimationFrame(() => markAsRead(roomId, hideActivity)); @@ -898,8 +911,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli } // Sending while scrolled up jumps to latest — offer return to previous spot if (wasAwayFromBottom && isBottomPinnedEvent) { - const anchorEventId = - eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId(); + const anchorEventId = eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId(); if (anchorEventId) { setReturnToEventId(anchorEventId); } @@ -930,15 +942,25 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli }); } }, - [mx, room, unreadInfo, hideActivity, markAsRead, eventId, getViewportAnchorEventId, getRangeCenterEventId, setReturnToEventId] - ) + [ + mx, + room, + unreadInfo, + hideActivity, + markAsRead, + eventId, + getViewportAnchorEventId, + getRangeCenterEventId, + setReturnToEventId, + ], + ), ); const handleOpenEvent = useCallback( async ( evtId: string, highlight = true, - onScroll: ((scrolled: boolean) => void) | undefined = undefined + onScroll: ((scrolled: boolean) => void) | undefined = undefined, ) => { const evtTimeline = getEventTimeline(room, evtId); const absoluteIndex = @@ -961,7 +983,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli loadEventTimeline(evtId); } }, - [room, timeline, scrollToItem, loadEventTimeline] + [room, timeline, scrollToItem, loadEventTimeline], ); useLiveTimelineRefresh( @@ -970,7 +992,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli if (liveTimelineLinked) { setTimeline(getInitialTimeline(room)); } - }, [room, liveTimelineLinked]) + }, [room, liveTimelineLinked]), ); // Stay at bottom when room editor resize @@ -995,41 +1017,48 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli } }; }, [getScrollElement, roomInputRef]), - useCallback(() => roomInputRef.current, [roomInputRef]) + useCallback(() => roomInputRef.current, [roomInputRef]), ); useResizeObserver( - useCallback((entries) => { - const timelineContent = timelineContentRef.current; - const scrollElement = getScrollElement(); - if (!timelineContent || !scrollElement) return; + useCallback( + (entries) => { + const timelineContent = timelineContentRef.current; + const scrollElement = getScrollElement(); + if (!timelineContent || !scrollElement) return; - const timelineEntry = getResizeObserverEntry(timelineContent, entries); - if (!timelineEntry) return; + const timelineEntry = getResizeObserverEntry(timelineContent, entries); + if (!timelineEntry) return; - const nextHeight = timelineEntry.contentRect.height; - const previousHeight = timelineContentHeightRef.current; - timelineContentHeightRef.current = nextHeight; + const nextHeight = timelineEntry.contentRect.height; + const previousHeight = timelineContentHeightRef.current; + timelineContentHeightRef.current = nextHeight; - if (restoringScrollRef.current) { - const saved = savedScrollRef.current; - if (saved) { - if (saved.atBottom) { - scrollElement.scrollTop = scrollElement.scrollHeight; - } else { - scrollElement.scrollTop = saved.top; + if (restoringScrollRef.current) { + const saved = savedScrollRef.current; + if (saved) { + if (saved.atBottom) { + scrollElement.scrollTop = scrollElement.scrollHeight; + } else { + scrollElement.scrollTop = saved.top; + } } + return; } - return; - } - if (previousHeight === 0 || nextHeight <= previousHeight || !isScrolledToBottom(scrollElement)) { - return; - } + if ( + previousHeight === 0 || + nextHeight <= previousHeight || + !isScrolledToBottom(scrollElement) + ) { + return; + } - autoScrollToBottom(scrollElement, false, true); - }, [getScrollElement]), - useCallback(() => timelineContentRef.current, []) + autoScrollToBottom(scrollElement, false, true); + }, + [getScrollElement], + ), + useCallback(() => timelineContentRef.current, []), ); const tryAutoMarkAsRead = useCallback(() => { @@ -1070,16 +1099,16 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli tryAutoMarkAsRead(); } }, - [tryAutoMarkAsRead] + [tryAutoMarkAsRead], ), useCallback( () => ({ root: getScrollElement(), rootMargin: '100px', }), - [getScrollElement] + [getScrollElement], ), - useCallback(() => atBottomAnchorRef.current, []) + useCallback(() => atBottomAnchorRef.current, []), ); useDocumentFocusChange( @@ -1099,8 +1128,8 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli tryAutoMarkAsRead(); } }, - [tryAutoMarkAsRead, unreadInfo, handleOpenEvent] - ) + [tryAutoMarkAsRead, unreadInfo, handleOpenEvent], + ), ); // Handle up arrow edit @@ -1115,7 +1144,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli isEmptyEditor(editor) ) { const editableEvt = getLatestEditableEvt(room.getLiveTimeline(), (mEvt) => - canEditEvent(mx, mEvt) + canEditEvent(mx, mEvt), ); const editableEvtId = editableEvt?.getId(); if (!editableEvtId) return; @@ -1123,8 +1152,8 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli evt.preventDefault(); } }, - [mx, room, editor] - ) + [mx, room, editor], + ), ); useEffect(() => { @@ -1154,7 +1183,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli // Remember scroll position when leaving a room (switch DM, nav away, etc.). useLayoutEffect(() => { - const roomId = room.roomId; + const { roomId } = room; return () => { persistTimelineScroll(roomId); }; @@ -1165,7 +1194,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const scrollEl = scrollRef.current; if (!scrollEl || eventId) return undefined; - const roomId = room.roomId; + const { roomId } = room; let raf = 0; const onScroll = () => { if (restoringScrollRef.current) return; @@ -1282,7 +1311,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli autoScrollToBottom( scrollEl, scrollToBottomRef.current.smooth, - scrollToBottomRef.current.force + scrollToBottomRef.current.force, ); if (atLiveEndRef.current) { setAtBottom(true); @@ -1322,10 +1351,11 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli if (!evtTimeline) return null; const mEvent = evtTimeline.getEvents().find((e) => e.getId() === eventId); if (!mEvent) return null; - const sender = getMemberDisplayName(room, mEvent.getSender() ?? '') - ?? getMxIdLocalPart(mEvent.getSender() ?? '') - ?? mEvent.getSender() - ?? 'Unknown'; + const sender = + getMemberDisplayName(room, mEvent.getSender() ?? '') ?? + getMxIdLocalPart(mEvent.getSender() ?? '') ?? + mEvent.getSender() ?? + 'Unknown'; const content = mEvent.getContent().body ?? ''; return { sender, @@ -1337,8 +1367,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli }, [room, hour24Clock]); const handleJumpToLatest = () => { - const anchorEventId = - eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId(); + const anchorEventId = eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId(); if (anchorEventId) { setReturnToEventId(anchorEventId); } @@ -1399,7 +1428,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli if (!targetId) return; handleOpenEvent(targetId); }, - [handleOpenEvent] + [handleOpenEvent], ); const handleUserClick: MouseEventHandler = useCallback( @@ -1415,10 +1444,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli room.roomId, space?.roomId, userId, - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), ); }, - [room, space, openUserRoomProfile] + [room, space, openUserRoomProfile], ); const handleUsernameClick: MouseEventHandler = useCallback( (evt) => { @@ -1433,13 +1462,13 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli createMentionElement( userId, name.startsWith('@') ? name : `@${name}`, - userId === mx.getUserId() - ) + userId === mx.getUserId(), + ), ); ReactEditor.focus(editor); moveCursor(editor); }, - [mx, room, editor] + [mx, room, editor], ); const handleReplyClick: MouseEventHandler = useCallback( @@ -1472,7 +1501,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli setActiveThreadId(replyId); } }, - [room, setReplyDraft, setActiveThreadId, editor] + [room, setReplyDraft, setActiveThreadId, editor], ); /** Opens the thread view for the given thread root event ID. */ @@ -1480,7 +1509,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli (threadRootId: string) => { setActiveThreadId(threadRootId); }, - [setActiveThreadId] + [setActiveThreadId], ); const handleReactionToggle = useCallback( @@ -1501,10 +1530,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli mx.sendEvent( room.roomId, MessageEvent.Reaction as any, - getReactionContent(targetEventId, key, rShortcode) + getReactionContent(targetEventId, key, rShortcode), ); }, - [mx, room] + [mx, room], ); const handleEdit = useCallback( (editEvtId?: string) => { @@ -1515,7 +1544,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli setEditId(undefined); ReactEditor.focus(editor); }, - [editor] + [editor], ); const { t } = useTranslation(); @@ -1984,23 +2013,29 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const senderName = getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId); const content = mEvent.getContent(); const prevContent = mEvent.getPrevContent(); - + // Check current content for active devices const calls = content['m.calls']; - const hasDevices = Array.isArray(calls) && calls.some((call: { 'm.devices'?: unknown[] }) => - Array.isArray(call['m.devices']) && call['m.devices'].length > 0 - ); - + const hasDevices = + Array.isArray(calls) && + calls.some( + (call: { 'm.devices'?: unknown[] }) => + Array.isArray(call['m.devices']) && call['m.devices'].length > 0, + ); + // Check previous content for active devices const prevCalls = prevContent['m.calls']; - const hadDevices = Array.isArray(prevCalls) && prevCalls.some((call: { 'm.devices'?: unknown[] }) => - Array.isArray(call['m.devices']) && call['m.devices'].length > 0 - ); - + const hadDevices = + Array.isArray(prevCalls) && + prevCalls.some( + (call: { 'm.devices'?: unknown[] }) => + Array.isArray(call['m.devices']) && call['m.devices'].length > 0, + ); + // Determine if this is a join or leave const isJoining = hasDevices && !hadDevices; const isLeaving = !hasDevices && hadDevices; - + // Skip if no change (refresh events or device updates within same call) if (!isJoining && !isLeaving) return null; @@ -2015,7 +2050,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli mEventId, mEvent, }); - + // Return special marker for call event (will be handled by eventRenderer) return 'CALL_EVENT_PENDING' as unknown as React.ReactNode; }, @@ -2117,7 +2152,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli /> ); - } + }, ); let prevEvent: MatrixEvent | undefined; @@ -2136,18 +2171,21 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli if (callEvents.length === 0) return null; // Group by user, tracking the sequence of actions to preserve order - const userActions = new Map(); - + const userActions = new Map< + string, + { + senderName: string; + firstAction: 'join' | 'leave'; + lastAction: 'join' | 'leave'; + joins: number; + leaves: number; + } + >(); + callEvents.forEach((evt) => { const existing = userActions.get(evt.senderId); const action = evt.isJoining ? 'join' : 'leave'; - + if (existing) { existing.lastAction = action; if (evt.isJoining) { @@ -2171,7 +2209,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli userActions.forEach((actions) => { const { joins, leaves, senderName, firstAction, lastAction } = actions; const total = joins + leaves; - + if (total === 1) { // Single action summaryParts.push(`${senderName} ${firstAction === 'join' ? 'joined' : 'left'}`); @@ -2180,14 +2218,18 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli const startedWith = firstAction === 'join' ? 'joined' : 'left'; const opposite = firstAction === 'join' ? 'left' : 'joined'; const cycles = Math.min(joins, leaves); - + if (firstAction === lastAction) { // Ended on same action as started (odd number of same action) // e.g., join-leave-join or leave-join-leave if (cycles === 1) { - summaryParts.push(`${senderName} ${startedWith}, ${opposite}, then ${startedWith} again`); + summaryParts.push( + `${senderName} ${startedWith}, ${opposite}, then ${startedWith} again`, + ); } else { - summaryParts.push(`${senderName} ${startedWith} and ${opposite} ${cycles} times, then ${startedWith}`); + summaryParts.push( + `${senderName} ${startedWith} and ${opposite} ${cycles} times, then ${startedWith}`, + ); } } else { // Ended on opposite action (equal joins/leaves or started-opposite pattern) @@ -2252,7 +2294,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli mEvent: MatrixEvent, item: number, timelineSet: EventTimelineSet, - collapse: boolean + collapse: boolean, ): React.ReactNode => { const reactionRelations = getEventReactions(timelineSet, mEventId); const reactions = reactionRelations && reactionRelations.getSortedAnnotationsByKey(); @@ -2390,7 +2432,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2; const getEventByItem = ( - timelineItem: number + timelineItem: number, ): { event: MatrixEvent; eventId: string } | undefined => { const [tm, bIndex] = getTimelineAndBaseIndex(timeline.linkedTimelines, timelineItem); if (!tm) return undefined; @@ -2443,7 +2485,14 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli if (!reactionOrEditEvent(mEvent)) { rawEventJSX = carouselEvents.length > 1 - ? renderImageCarouselMessage(carouselEvents, mEventId, mEvent, item, timelineSet, collapsed) + ? renderImageCarouselMessage( + carouselEvents, + mEventId, + mEvent, + item, + timelineSet, + collapsed, + ) : renderMatrixEvent( mEvent.getType(), typeof mEvent.getStateKey() === 'string', @@ -2451,28 +2500,29 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli mEvent, item, timelineSet, - collapsed + collapsed, ); } // Check if this is a call event that should be grouped const isCallEventPending = rawEventJSX === ('CALL_EVENT_PENDING' as unknown as React.ReactNode); - + // Determine if we need to flush pending call events // Flush when: we hit a non-call event, or this is the last item const isLastItem = index === allItems.length - 1; const pendingCallEvents = pendingCallEventsRef.current; - const shouldFlushCallEvents = pendingCallEvents.length > 0 && (!isCallEventPending || isLastItem); - + const shouldFlushCallEvents = + pendingCallEvents.length > 0 && (!isCallEventPending || isLastItem); + let callSummaryJSX: React.ReactNode = null; if (shouldFlushCallEvents) { callSummaryJSX = renderCallEventSummary([...pendingCallEvents]); pendingCallEventsRef.current = []; // Clear array } - + // If this was a call event marker, don't render it directly const eventJSX = isCallEventPending ? null : rawEventJSX; - + prevEvent = mEvent; isPrevRendered = !!eventJSX || !!callSummaryJSX; @@ -2534,8 +2584,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli return callSummaryJSX || eventJSX; }; - const showUnreadTop = - !!unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline; + const showUnreadTop = !!unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline; const atLiveBottom = atBottom && liveTimelineLinked && rangeAtEnd; return ( @@ -2728,11 +2777,15 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli border: `1px solid ${color.Surface.ContainerLine}`, }} > - + {latestUnreadMessage.sender}: {latestUnreadMessage.content} @@ -2749,7 +2802,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli )} - + ); } diff --git a/src/app/features/room/RoomTombstone.tsx b/src/app/features/room/RoomTombstone.tsx index 24f0b80e..94773563 100644 --- a/src/app/features/room/RoomTombstone.tsx +++ b/src/app/features/room/RoomTombstone.tsx @@ -21,7 +21,7 @@ export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstone return mx.joinRoom(replacementRoomId, { viaServers: via, }); - }, [mx, roomId, replacementRoomId]) + }, [mx, roomId, replacementRoomId]), ); const replacementRoom = mx.getRoom(replacementRoomId); diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 034754dd..1ecb359d 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -99,8 +99,8 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) { ReactEditor.focus(editor); } }, - [editor] - ) + [editor], + ), ); return ( diff --git a/src/app/features/room/RoomViewFollowing.tsx b/src/app/features/room/RoomViewFollowing.tsx index 8beabc7d..d79a4945 100644 --- a/src/app/features/room/RoomViewFollowing.tsx +++ b/src/app/features/room/RoomViewFollowing.tsx @@ -1,9 +1,9 @@ import React, { useState } from 'react'; import { Box, Modal, Overlay, OverlayBackdrop, OverlayCenter, Text, as, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { Room } from 'matrix-js-sdk'; import classNames from 'classnames'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../components/icons'; import { getMemberDisplayName } from '../../utils/room'; import { getMxIdLocalPart } from '../../utils/matrix'; @@ -33,7 +33,8 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( const names = latestEventReaders .filter((readerId) => readerId !== myUserId) .map( - (readerId) => getMemberDisplayName(room, readerId) ?? getMxIdLocalPart(readerId) ?? readerId + (readerId) => + getMemberDisplayName(room, readerId) ?? getMxIdLocalPart(readerId) ?? readerId, ); if (names.length === 0) { @@ -116,5 +117,5 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( ); - } + }, ); diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index 7399701d..85f5d7ef 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -1,10 +1,30 @@ import React, { MouseEventHandler, forwardRef, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Box, Avatar, Text, Overlay, OverlayCenter, OverlayBackdrop, IconButton, Tooltip, TooltipProvider, Menu, MenuItem, toRem, config, Line, PopOut, RectCords, Badge, Spinner, color } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + Avatar, + Text, + Overlay, + OverlayCenter, + OverlayBackdrop, + IconButton, + Tooltip, + TooltipProvider, + Menu, + MenuItem, + toRem, + config, + Line, + PopOut, + RectCords, + Badge, + Spinner, + color, +} from 'folds'; import { useNavigate } from 'react-router-dom'; import { JoinRule, Room } from 'matrix-js-sdk'; import { useAtom, useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { activeThreadIdAtomFamily } from '../../state/activeThread'; import { PageHeader } from '../../components/page'; @@ -16,8 +36,18 @@ import { useRoom } from '../../hooks/useRoom'; import { useSetting } from '../../state/hooks/settings'; import { settingsAtom } from '../../state/settings'; import { useSpaceOptionally } from '../../hooks/useSpace'; -import { getHomeSearchPath, getSpaceSearchPath, getDirectSearchPath, withSearchParam } from '../../pages/pathUtils'; -import { getCanonicalAliasOrRoomId, guessDmRoomUserId, isRoomAlias, mxcUrlToHttp } from '../../utils/matrix'; +import { + getHomeSearchPath, + getSpaceSearchPath, + getDirectSearchPath, + withSearchParam, +} from '../../pages/pathUtils'; +import { + getCanonicalAliasOrRoomId, + guessDmRoomUserId, + isRoomAlias, + mxcUrlToHttp, +} from '../../utils/matrix'; import colorMXID from '../../../util/colorMXID'; import { useOtherUserColor } from '../../hooks/useUserColor'; import { _SearchPathSearchParams } from '../../pages/paths'; @@ -307,7 +337,10 @@ function CallIndicator({ roomId }: CallIndicatorProps) { > {displayName} - + {member.userId} @@ -321,9 +354,7 @@ function CallIndicator({ roomId }: CallIndicatorProps) { src={avatarUrl} alt={displayName} renderFallback={() => ( - - {displayName.charAt(0).toUpperCase()} - + {displayName.charAt(0).toUpperCase()} )} /> @@ -417,12 +448,18 @@ function RoomCallButtons({ roomId }: RoomCallButtonsProps) { {isConnecting ? ( ) : ( - + )} )} @@ -443,12 +480,18 @@ function RoomCallButtons({ roomId }: RoomCallButtonsProps) { {isConnecting ? ( ) : ( - + )} )} @@ -482,7 +525,7 @@ export function RoomViewHeader({ forumLayout = false }: RoomViewHeaderProps) { const name = useRoomName(room); const topic = useRoomTopic(room); const avatarUrl = avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const dmUserId = isDirect ? guessDmRoomUserId(room, mx.getSafeUserId()) : undefined; @@ -740,7 +783,11 @@ export function RoomViewHeader({ forumLayout = false }: RoomViewHeaderProps) { onClick={() => setActiveThreadId(undefined)} aria-pressed={!!activeThreadId} > - + )} diff --git a/src/app/features/room/RoomViewTyping.tsx b/src/app/features/room/RoomViewTyping.tsx index 5e5664f7..516a0085 100644 --- a/src/app/features/room/RoomViewTyping.tsx +++ b/src/app/features/room/RoomViewTyping.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { Box, IconButton, Text, as } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import { Room } from 'matrix-js-sdk'; import classNames from 'classnames'; import { useSetAtom } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { roomIdToTypingMembersAtom } from '../../state/typingMembers'; import { TypingIndicator } from '../../components/typing-indicator'; import { getMemberDisplayName } from '../../utils/room'; @@ -66,7 +66,7 @@ export const RoomViewTyping = as<'div', RoomViewTypingProps>( type: 'DELETE', roomId: room.roomId, userId: receipt.userId, - }) + }), ); }; @@ -88,12 +88,12 @@ export const RoomViewTyping = as<'div', RoomViewTypingProps>( ))} {sharedSuffix} - {'...'} + ... ); - } + }, ); diff --git a/src/app/features/room/ThreadView.tsx b/src/app/features/room/ThreadView.tsx index 357544fe..e5484f2b 100644 --- a/src/app/features/room/ThreadView.tsx +++ b/src/app/features/room/ThreadView.tsx @@ -7,29 +7,29 @@ import React, { useRef, useState, } from 'react'; -import { - MatrixEvent, - RelationType, - Room, - RoomEvent, - ThreadEvent, -} from 'matrix-js-sdk'; +import { MatrixEvent, RelationType, Room, RoomEvent, ThreadEvent } from 'matrix-js-sdk'; import { useAtomValue, useSetAtom } from 'jotai'; -import { Badge, Box, IconButton, Line, Scroll, Text, Tooltip, TooltipProvider, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Badge, + Box, + IconButton, + Line, + Scroll, + Text, + Tooltip, + TooltipProvider, + config, +} from 'folds'; import { HTMLReactParserOptions } from 'html-react-parser'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { ReactEditor } from 'slate-react'; import { isKeyHotkey } from 'is-hotkey'; +import { Icon, Icons } from '../../components/icons'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useKeyDown } from '../../hooks/useKeyDown'; -import { editableActiveElement } from '../../utils/dom'; -import { - useEditor, - createMentionElement, - moveCursor, -} from '../../components/editor'; +import { editableActiveElement, autoScrollToBottom, scrollElementIntoView } from '../../utils/dom'; +import { useEditor, createMentionElement, moveCursor } from '../../components/editor'; import { useSetting } from '../../state/hooks/settings'; import { MessageLayout, settingsAtom } from '../../state/settings'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; @@ -44,10 +44,7 @@ import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile'; import { useTheme } from '../../hooks/useTheme'; import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag'; import { usePowerLevelTags } from '../../hooks/usePowerLevelTags'; -import { - useAccessiblePowerTagColors, - useGetMemberPowerTag, -} from '../../hooks/useMemberPowerTag'; +import { useAccessiblePowerTagColors, useGetMemberPowerTag } from '../../hooks/useMemberPowerTag'; import { combineEmbedFilters, useRoomEmbedFilters, @@ -81,14 +78,9 @@ import { getReactionContent, reactionOrEditEvent, } from '../../utils/room'; -import { - eventWithShortcode, - factoryEventSentBy, - getMxIdLocalPart, -} from '../../utils/matrix'; +import { eventWithShortcode, factoryEventSentBy, getMxIdLocalPart } from '../../utils/matrix'; import { GetContentCallback, MessageEvent } from '../../../types/matrix/room'; import { inSameDay, minuteDifference, timeDayMonthYear, today, yesterday } from '../../utils/time'; -import { autoScrollToBottom, scrollElementIntoView } from '../../utils/dom'; type ThreadViewProps = { room: Room; @@ -140,7 +132,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { console.log('[ThreadView] Component mount/render', { roomId: room.roomId, threadRootId, - allThreadsInRoom: room.getThreads().map(t => ({ + allThreadsInRoom: room.getThreads().map((t) => ({ id: t.id, rootEventId: t.rootEvent?.getId(), length: t.length, @@ -158,8 +150,11 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); - const { bursts: emojiConfettiBursts, removeBurst: removeEmojiConfettiBurst, handleJumboEmojiClick } = - useJumboEmojiConfetti(room); + const { + bursts: emojiConfettiBursts, + removeBurst: removeEmojiConfettiBurst, + handleJumboEmojiClick, + } = useJumboEmojiConfetti(room); const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; const direct = useIsDirectRoom(); @@ -173,7 +168,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { const accessiblePowerTagColors = useAccessiblePowerTagColors( theme.kind, creatorsTag, - powerLevelTags + powerLevelTags, ); const permissions = useRoomPermissions(creators, powerLevels); const canRedact = permissions.action('redact', mx.getSafeUserId()); @@ -191,7 +186,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { const roomWideEmbedFilters = useRoomWideEmbedFilters(room); const combinedEmbedFilters = useMemo( () => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters), - [personalEmbedFilters, roomWideEmbedFilters] + [personalEmbedFilters, roomWideEmbedFilters], ); const mentionClickHandler = useMentionClickHandler(room.roomId); @@ -201,10 +196,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { () => ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)), ), }), - [mx, room, mentionClickHandler] + [mx, room, mentionClickHandler], ); const htmlReactParserOptions = useMemo( @@ -215,7 +210,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, }), - [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication] + [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication], ); const thread = room.getThread(threadRootId); @@ -233,7 +228,11 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { rootEventFound: !!rootEvent, rootEventType: rootEvent?.getType(), rootEventThreadRootId: rootEvent?.threadRootId, - allEventIdsInTimeline: roomTimelineSet.getLiveTimeline().getEvents().slice(0, 20).map(e => e.getId()), + allEventIdsInTimeline: roomTimelineSet + .getLiveTimeline() + .getEvents() + .slice(0, 20) + .map((e) => e.getId()), }); } }, [thread, room, threadRootId, roomTimelineSet]); @@ -245,33 +244,33 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { console.log('[ThreadView] No thread found for ID:', threadRootId); // eslint-disable-next-line no-console console.log('[ThreadView] Attempting to find replies manually from room timeline'); - + // Fallback: search the room timeline for events that are replies to this thread const allEvents = roomTimelineSet.getLiveTimeline().getEvents(); - const threadReplies = allEvents.filter(event => { + const threadReplies = allEvents.filter((event) => { const relations = event.getRelation(); // Check if this event is a thread reply to our root event return relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId; }); - + // eslint-disable-next-line no-console console.log('[ThreadView] Manual search found', { totalEventsInTimeline: allEvents.length, repliesFound: threadReplies.length, - replies: threadReplies.map(e => ({ + replies: threadReplies.map((e) => ({ id: e.getId(), sender: e.getSender(), body: e.getContent()?.body?.substring(0, 50), })), }); - + return threadReplies; } - + // thread.events contains only replies, not the root event const replies = [...t.events]; const liveTimelineEvents = t.liveTimeline?.getEvents() || []; - + // eslint-disable-next-line no-console console.log('[ThreadView] getThreadEvents', { threadId: threadRootId, @@ -282,27 +281,27 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { initialEventsFetched: (t as any).initialEventsFetched, liveTimelineEventsCount: liveTimelineEvents.length, threadEventsMatch: replies.length === liveTimelineEvents.length, - allRepliesFromThreadEvents: replies.map(e => ({ - id: e.getId(), - type: e.getType(), + allRepliesFromThreadEvents: replies.map((e) => ({ + id: e.getId(), + type: e.getType(), sender: e.getSender(), content: e.getContent()?.body?.substring(0, 50), })), - allEventsFromLiveTimeline: liveTimelineEvents.map(e => ({ + allEventsFromLiveTimeline: liveTimelineEvents.map((e) => ({ id: e.getId(), type: e.getType(), sender: e.getSender(), content: e.getContent()?.body?.substring(0, 50), })), }); - + // Try using liveTimeline events if thread.events is empty but liveTimeline has events if (replies.length === 0 && liveTimelineEvents.length > 0) { // eslint-disable-next-line no-console console.log('[ThreadView] Using liveTimeline events instead of thread.events'); return [...liveTimelineEvents]; } - + return replies; }, [room, threadRootId, roomTimelineSet]); @@ -332,8 +331,8 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { ReactEditor.focus(editor); } }, - [editor] - ) + [editor], + ), ); // Subscribe to thread and room timeline events. @@ -364,7 +363,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { // Fires when initial events are loaded after the SDK paginates the thread. // eslint-disable-next-line @typescript-eslint/no-explicit-any (thread as any).on(RoomEvent.TimelineReset, handleUpdate); - + // Also listen to Timeline events which fire when events are added thread.on(RoomEvent.Timeline, handleUpdate); } @@ -373,9 +372,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { if (eventRoom?.roomId !== room.roomId) return; // Check if this event is related to our thread (either it's a reply to it, or it IS the root event) const relations = mEvent.getRelation(); - const isThreadReply = relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId; + const isThreadReply = + relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId; const isRootEvent = mEvent.getId() === threadRootId; - + if (isThreadReply || isRootEvent) { handleUpdate(); } @@ -418,10 +418,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { room.roomId, space?.roomId, userId, - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), ); }, - [room, space, openUserRoomProfile] + [room, space, openUserRoomProfile], ); const handleUsernameClick: MouseEventHandler = useCallback( @@ -434,25 +434,23 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { createMentionElement( userId, name.startsWith('@') ? name : `@${name}`, - userId === mx.getUserId() - ) + userId === mx.getUserId(), + ), ); ReactEditor.focus(editor); moveCursor(editor); }, - [mx, room, editor] + [mx, room, editor], ); const handleReplyClick: MouseEventHandler = useCallback( (evt) => { const replyId = evt.currentTarget.getAttribute('data-event-id'); if (!replyId) return; - const replyEvt = - thread?.findEventById(replyId) ?? room.findEventById(replyId); + const replyEvt = thread?.findEventById(replyId) ?? room.findEventById(replyId); if (!replyEvt) return; const editedReply = getEditedEvent(replyId, replyEvt, roomTimelineSet); - const content = - editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent(); + const content = editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent(); const { body, formatted_body: formattedBody } = content; const senderId = replyEvt.getSender(); if (senderId && typeof body === 'string') { @@ -466,14 +464,14 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { setTimeout(() => ReactEditor.focus(editor), 100); } }, - [room, thread, roomTimelineSet, threadRootId, setReplyDraft, editor] + [room, thread, roomTimelineSet, threadRootId, setReplyDraft, editor], ); const handleOpenReply: MouseEventHandler = useCallback((evt) => { const targetId = evt.currentTarget.getAttribute('data-event-id'); if (!targetId) return; const el = scrollRef.current?.querySelector( - `[data-message-id="${targetId}"]` + `[data-message-id="${targetId}"]`, ) as HTMLElement | null; if (el) scrollElementIntoView(el, { behavior: 'smooth', block: 'center' }); }, []); @@ -498,10 +496,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { room.roomId, // eslint-disable-next-line @typescript-eslint/no-explicit-any MessageEvent.Reaction as any, - getReactionContent(targetEventId, key, rShortcode) + getReactionContent(targetEventId, key, rShortcode), ); }, - [mx, room, roomTimelineSet] + [mx, room, roomTimelineSet], ); /** Renders a single thread event into JSX. Returns null for non-message events. */ @@ -514,17 +512,12 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { if (reactionOrEditEvent(mEvent)) return null; const type = mEvent.getType(); - if ( - type !== MessageEvent.RoomMessage && - type !== MessageEvent.RoomMessageEncrypted - ) { + if (type !== MessageEvent.RoomMessage && type !== MessageEvent.RoomMessageEncrypted) { return null; } const prevEvent = index > 0 ? all[index - 1] : undefined; - const dayDivider = prevEvent - ? !inSameDay(prevEvent.getTs(), mEvent.getTs()) - : false; + const dayDivider = prevEvent ? !inSameDay(prevEvent.getTs(), mEvent.getTs()) : false; const collapse = !dayDivider && @@ -534,21 +527,17 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) { minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2; const reactionRelations = getEventReactions(roomTimelineSet, mEventId); - const hasReactions = - !!reactionRelations?.getSortedAnnotationsByKey()?.length; + const hasReactions = !!reactionRelations?.getSortedAnnotationsByKey()?.length; const { replyEventId, threadRootId: evtThreadRootId } = mEvent; const editedEvent = getEditedEvent(mEventId, mEvent, roomTimelineSet); const getContent = (() => - editedEvent?.getContent()['m.new_content'] ?? - mEvent.getContent()) as GetContentCallback; + editedEvent?.getContent()['m.new_content'] ?? mEvent.getContent()) as GetContentCallback; const senderId = mEvent.getSender() ?? ''; const senderDisplayName = - getMemberDisplayName(room, senderId) ?? - getMxIdLocalPart(senderId) ?? - senderId; + getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId; const dayDividerJSX = dayDivider ? ( {/* Render the thread root event */} {rootEvent && renderEvent(rootEvent, -1, [])} - + {/* Show "no replies" message if no replies exist */} {events.length === 0 && ( - + No replies yet. Be the first! )} - + {/* Render all reply events */} {events.map((evt, idx, arr) => renderEvent(evt, idx, arr))} diff --git a/src/app/features/room/emoji-confetti/EmojiConfettiBurstCanvas.tsx b/src/app/features/room/emoji-confetti/EmojiConfettiBurstCanvas.tsx index be513638..59e5faed 100644 --- a/src/app/features/room/emoji-confetti/EmojiConfettiBurstCanvas.tsx +++ b/src/app/features/room/emoji-confetti/EmojiConfettiBurstCanvas.tsx @@ -1,7 +1,12 @@ import React, { useEffect, useMemo, useRef } from 'react'; import { createPortal } from 'react-dom'; import { EmojiConfettiBurst } from './types'; -import { findJumboEmojiElement, getLocalBurstCanvasSize, measureJumboGlyph, setJumboEmojiHidden } from './findJumboMount'; +import { + findJumboEmojiElement, + getLocalBurstCanvasSize, + measureJumboGlyph, + setJumboEmojiHidden, +} from './findJumboMount'; import { BurstParticle, drawBurstParticles, @@ -30,7 +35,9 @@ export function EmojiConfettiBurstCanvas({ burst, onComplete }: EmojiConfettiBur const fullscreen = isFullscreenBurstEmoji(primaryEmoji); if (fullscreen) { - return ; + return ( + + ); } return ; @@ -89,7 +96,7 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro const origin = { x: glyph ? glyph.x : burst.origin.x, y: glyph ? glyph.y : burst.origin.y, - maskRadius: glyph ? glyph.size * 0.5 : burst.origin.maskRadius ?? 36, + maskRadius: glyph ? glyph.size * 0.5 : (burst.origin.maskRadius ?? 36), }; // Keep morph heroes glued to the message emoji; only clamp undirected fireworks. @@ -105,7 +112,7 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro primaryEmoji, profile, performance.now(), - glyph?.size + glyph?.size, ); const revealJumbo = () => { @@ -188,7 +195,14 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro // Extra Things: allow Strict Mode remount to start a fresh burst. spawnedRef.current = false; }; - }, [burst.id, burst.origin.maskRadius, burst.origin.x, burst.origin.y, burst.targetEventId, primaryEmoji]); + }, [ + burst.id, + burst.origin.maskRadius, + burst.origin.x, + burst.origin.y, + burst.targetEventId, + primaryEmoji, + ]); return createPortal(
, - document.body + document.body, ); } @@ -234,7 +248,7 @@ function LocalBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasProps) y: canvasSize / 2, maskRadius: burst.origin.maskRadius ?? 36, }), - [burst.origin.maskRadius, canvasSize] + [burst.origin.maskRadius, canvasSize], ); const updateLayerPosition = () => { @@ -370,6 +384,6 @@ function LocalBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasProps) }} />
, - document.body + document.body, ); } diff --git a/src/app/features/room/emoji-confetti/EmojiConfettiOverlay.tsx b/src/app/features/room/emoji-confetti/EmojiConfettiOverlay.tsx index ff0a4aab..bfadeee1 100644 --- a/src/app/features/room/emoji-confetti/EmojiConfettiOverlay.tsx +++ b/src/app/features/room/emoji-confetti/EmojiConfettiOverlay.tsx @@ -13,11 +13,7 @@ export function EmojiConfettiOverlay({ bursts, onBurstComplete }: EmojiConfettiO return ( <> {bursts.map((burst) => ( - + ))} ); diff --git a/src/app/features/room/emoji-confetti/burstOrigin.ts b/src/app/features/room/emoji-confetti/burstOrigin.ts index 3fdc8abd..b5273e88 100644 --- a/src/app/features/room/emoji-confetti/burstOrigin.ts +++ b/src/app/features/room/emoji-confetti/burstOrigin.ts @@ -19,7 +19,7 @@ export function getElementCenter(element: Element): BurstPoint { export function findEmojiOriginInMessage( targetEventId: string, - emoji: string + emoji: string, ): BurstPoint | undefined { const message = document.querySelector(`[data-message-id="${CSS.escape(targetEventId)}"]`); if (!message) return undefined; @@ -54,7 +54,7 @@ export function getMessageFallbackOrigin(targetEventId: string): BurstPoint | un export function resolveBurstOrigin( targetEventId: string | undefined, emojis: string[], - explicitOrigin?: BurstPoint + explicitOrigin?: BurstPoint, ): BurstPoint { if (explicitOrigin) return explicitOrigin; diff --git a/src/app/features/room/emoji-confetti/emojiBurstEngine.ts b/src/app/features/room/emoji-confetti/emojiBurstEngine.ts index ccd22b99..1ff61c0e 100644 --- a/src/app/features/room/emoji-confetti/emojiBurstEngine.ts +++ b/src/app/features/room/emoji-confetti/emojiBurstEngine.ts @@ -93,7 +93,7 @@ function emergeOpacity( y: number, spawnX: number, spawnY: number, - maskRadius: number + maskRadius: number, ): number { const dist = Math.hypot(x - spawnX, y - spawnY); const inner = maskRadius * 0.55; @@ -111,7 +111,7 @@ function spawnParticle( primaryEmoji: string, profile: EmojiBurstProfile, bornAt: number, - options?: { hero?: boolean } + options?: { hero?: boolean }, ) { const hero = options?.hero ?? false; const angle = sampleBurstAngle(profile); @@ -174,7 +174,7 @@ export function spawnEmojiBurst( burstId: string, point: BurstPoint, emoji: string, - now = performance.now() + now = performance.now(), ) { const profile = getEmojiBurstProfile(emoji); const burstStartMs = now; @@ -183,7 +183,7 @@ export function spawnEmojiBurst( hero: true, }); - const particleCount = profile.particleCount; + const { particleCount } = profile; for (let i = 0; i < particleCount; i += 1) { const slot = i / particleCount; const bornAt = @@ -197,7 +197,9 @@ function stepSpiralParticle(particle: BurstParticle, dtSeconds: number) { particle.orbitAngle += particle.orbitSpeed * dtSeconds; particle.x = particle.spawnX + Math.cos(particle.orbitAngle) * particle.orbitRadius; particle.y = - particle.spawnY + Math.sin(particle.orbitAngle) * particle.orbitRadius * 0.65 + particle.vy * dtSeconds * 8; + particle.spawnY + + Math.sin(particle.orbitAngle) * particle.orbitRadius * 0.65 + + particle.vy * dtSeconds * 8; particle.vy += particle.gravity * dtSeconds * 0.35; particle.rotation += particle.spin * dtSeconds; } @@ -231,7 +233,7 @@ function stepDefaultParticle(particle: BurstParticle, dtSeconds: number, dragFac export function stepBurstParticles( particles: BurstParticle[], now: number, - dtSeconds: number + dtSeconds: number, ): void { for (let i = particles.length - 1; i >= 0; i -= 1) { const particle = particles[i]; @@ -285,7 +287,7 @@ function particleDrawState(particle: BurstParticle, now: number): DrawState | nu particle.y, particle.spawnX, particle.spawnY, - particle.maskRadius + particle.maskRadius, ); if (opacity <= 0) return null; @@ -329,7 +331,7 @@ export function drawBurstParticles( context: CanvasRenderingContext2D, particles: BurstParticle[], dpr: number, - now: number + now: number, ) { for (const particle of particles) { const state = particleDrawState(particle, now); diff --git a/src/app/features/room/emoji-confetti/fireworkParticleEngine.ts b/src/app/features/room/emoji-confetti/fireworkParticleEngine.ts index a6b7e520..f6b9f2ee 100644 --- a/src/app/features/room/emoji-confetti/fireworkParticleEngine.ts +++ b/src/app/features/room/emoji-confetti/fireworkParticleEngine.ts @@ -102,7 +102,7 @@ function getEmojiBitmap( emoji: string, tintColor: string | undefined, cssPx: number | undefined, - padRatio: number + padRatio: number, ): EmojiBitmap { const targetCss = Math.max(16, Math.round(cssPx ?? EMOJI_CACHE_PX)); const dpr = typeof window !== 'undefined' ? Math.min(window.devicePixelRatio || 1, 2) : 1; @@ -162,7 +162,7 @@ function particleTint(profile: EmojiBurstProfile, emoji: string): string | undef /** Spew particles for morph bursts — never the morphTo face (that stays on the hero). */ function pickSpewEmoji(profile: EmojiBurstProfile, primaryEmoji: string): string { - const morphTo = profile.morphTo; + const { morphTo } = profile; const companions = (profile.companions ?? []).filter((e) => e !== morphTo); if (morphTo && companions.length) { return companions[Math.floor(Math.random() * companions.length)] ?? primaryEmoji; @@ -174,7 +174,7 @@ function pickSpewEmoji(profile: EmojiBurstProfile, primaryEmoji: string): string function buildSpawnPlan( profile: EmojiBurstProfile, primaryEmoji: string, - startMs: number + startMs: number, ): SpawnItem[] { // Anchored morphing hero is drawn separately — skip a flying hero twin. const plan: SpawnItem[] = profile.morphTo @@ -192,11 +192,7 @@ function buildSpawnPlan( const slot = (i + 0.5) / count; const eased = slot * slot; plan.push({ - atMs: - startMs + - 80 + - eased * SPAWN_WINDOW_MS + - (Math.random() - 0.5) * 70, + atMs: startMs + 80 + eased * SPAWN_WINDOW_MS + (Math.random() - 0.5) * 70, emoji: pickSpewEmoji(profile, primaryEmoji), fontSize: lerp(profile.fontSizeMin, profile.fontSizeMax), }); @@ -250,7 +246,7 @@ function spawnOne(sim: FireworkSim, item: SpawnItem, now: number) { const speed = lerp(profile.speedMin, profile.speedMax); const launchUp = lerp(profile.launchUpMin, profile.launchUpMax); const drawSize = item.fontSize * EMOJI_CACHE_SCALE * 0.85; - const emoji = item.emoji; + const { emoji } = item; // Directed cones (e.g. throw-up) push along the sampled angle. // Undirected fireworks keep the classic upward launch kick. @@ -321,7 +317,7 @@ export function createFireworkSim( profile: EmojiBurstProfile, startMs = performance.now(), /** Pixel size of the source jumbo emoji — hero face matches this when set. */ - heroSizePx?: number + heroSizePx?: number, ): FireworkSim { const colCount = Math.max(8, Math.ceil(widthPx / PILE_CELL)); const fallbackHero = @@ -374,7 +370,7 @@ export function createFireworkSim( /** Keep the stand-in face glued to the live jumbo metrics. */ export function syncFireworkHero( sim: FireworkSim, - metrics: { x: number; y: number; size: number } | null + metrics: { x: number; y: number; size: number } | null, ) { if (!sim.hero || !metrics) return; sim.origin.x = metrics.x; @@ -445,11 +441,7 @@ export function stepFireworkSim(sim: FireworkSim, now: number, dtSeconds: number return true; } -export function drawFireworkSim( - context: CanvasRenderingContext2D, - sim: FireworkSim, - now: number -) { +export function drawFireworkSim(context: CanvasRenderingContext2D, sim: FireworkSim, now: number) { const elapsed = now - sim.startMs; let fade = 1; if (elapsed >= SETTLE_HOLD_MS) { @@ -466,7 +458,7 @@ export function drawFireworkSim( // Anchored face at the spew origin — morphs 🤢 → 🤮 mid-throw, then drops away. if (sim.hero && fade > 0.02) { - const hero = sim.hero; + const { hero } = sim; const heaveAmp = Math.max(1.5, hero.drawSize * 0.02); const heave = Math.sin(elapsed / 70) * (hero.morphed ? heaveAmp * 1.25 : heaveAmp); // Scale includes bitmap padding so the glyph matches jumbo size without clipping. diff --git a/src/app/features/room/emoji-confetti/jumboEmojiInteraction.ts b/src/app/features/room/emoji-confetti/jumboEmojiInteraction.ts index 51e965c5..7cfcc511 100644 --- a/src/app/features/room/emoji-confetti/jumboEmojiInteraction.ts +++ b/src/app/features/room/emoji-confetti/jumboEmojiInteraction.ts @@ -1,6 +1,9 @@ import { KeyboardEvent, MouseEvent } from 'react'; -export type JumboEmojiClickHandler = (body: string, event: MouseEvent | KeyboardEvent) => void; +export type JumboEmojiClickHandler = ( + body: string, + event: MouseEvent | KeyboardEvent, +) => void; export function getJumboEmojiInteractionProps({ body, diff --git a/src/app/features/room/emoji-confetti/resolveClickedEmoji.ts b/src/app/features/room/emoji-confetti/resolveClickedEmoji.ts index cc144391..d8f2f238 100644 --- a/src/app/features/room/emoji-confetti/resolveClickedEmoji.ts +++ b/src/app/features/room/emoji-confetti/resolveClickedEmoji.ts @@ -4,11 +4,12 @@ import { BurstPoint, getBurstPointFromElement } from './burstOrigin'; export function resolveClickedEmoji( event: MouseEvent | KeyboardEvent, - fallbackBody: string + fallbackBody: string, ): { emoji: string; origin: BurstPoint } | null { const currentTarget = event.currentTarget as HTMLElement; const target = event.target as HTMLElement; - const emoticonEl = target.closest('[data-emoticon]') ?? currentTarget.querySelector('[data-emoticon]'); + const emoticonEl = + target.closest('[data-emoticon]') ?? currentTarget.querySelector('[data-emoticon]'); if (emoticonEl instanceof HTMLElement) { const emoji = emoticonEl.getAttribute('data-emoticon'); if (emoji) { @@ -19,7 +20,10 @@ export function resolveClickedEmoji( } } - if (!currentTarget.closest('[data-jumbo-emoji]') && !currentTarget.hasAttribute('data-jumbo-emoji')) { + if ( + !currentTarget.closest('[data-jumbo-emoji]') && + !currentTarget.hasAttribute('data-jumbo-emoji') + ) { return null; } diff --git a/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts b/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts index 27f1a912..feacda22 100644 --- a/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts +++ b/src/app/features/room/emoji-confetti/sendEmojiConfetti.ts @@ -30,7 +30,7 @@ export function sendEmojiConfettiEvent( mx: MatrixClient, roomId: string, targetEventId: string, - emojis: string[] + emojis: string[], ) { const content: EmojiConfettiContent = { emojis, diff --git a/src/app/features/room/emoji-confetti/useEmojiConfetti.ts b/src/app/features/room/emoji-confetti/useEmojiConfetti.ts index 9fd2abd6..706f8871 100644 --- a/src/app/features/room/emoji-confetti/useEmojiConfetti.ts +++ b/src/app/features/room/emoji-confetti/useEmojiConfetti.ts @@ -1,11 +1,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { MatrixEvent, Room, RoomEvent } from 'matrix-js-sdk'; import { BurstPoint, resolveBurstOrigin } from './burstOrigin'; -import { - EMOJI_CONFETTI_EVENT_TYPE, - EmojiConfettiBurst, - EmojiConfettiContent, -} from './types'; +import { EMOJI_CONFETTI_EVENT_TYPE, EmojiConfettiBurst, EmojiConfettiContent } from './types'; function scheduleBurstFromValues( burstId: string, @@ -13,11 +9,10 @@ function scheduleBurstFromValues( targetEventId: string | undefined, onBurst: (burst: EmojiConfettiBurst) => void, attempt = 0, - explicitOrigin?: BurstPoint + explicitOrigin?: BurstPoint, ) { const targetElement = - targetEventId && - document.querySelector(`[data-message-id="${CSS.escape(targetEventId)}"]`); + targetEventId && document.querySelector(`[data-message-id="${CSS.escape(targetEventId)}"]`); if (targetEventId && !targetElement && attempt < 8) { window.setTimeout( @@ -28,9 +23,9 @@ function scheduleBurstFromValues( targetEventId, onBurst, attempt + 1, - explicitOrigin + explicitOrigin, ), - 50 + 50, ); return; } @@ -46,7 +41,7 @@ function scheduleBurstFromValues( function scheduleBurst( event: MatrixEvent, onBurst: (burst: EmojiConfettiBurst) => void, - attempt = 0 + attempt = 0, ) { const eventId = event.getId(); if (!eventId) return; @@ -58,7 +53,9 @@ function scheduleBurst( function parseEmojiConfettiContent(content: unknown): { emojis: string[]; targetEventId?: string } { const confettiContent = content as EmojiConfettiContent; const emojis = Array.isArray(confettiContent.emojis) - ? confettiContent.emojis.filter((emoji): emoji is string => typeof emoji === 'string' && emoji.length > 0) + ? confettiContent.emojis.filter( + (emoji): emoji is string => typeof emoji === 'string' && emoji.length > 0, + ) : []; return { @@ -83,26 +80,29 @@ export function useEmojiConfetti(room: Room) { ownEventIdsRef.current.add(eventId); }, []); - const queueBurst = useCallback((event: MatrixEvent) => { - const eventId = event.getId(); - if (!eventId || seenEventIdsRef.current.has(eventId)) return; + const queueBurst = useCallback( + (event: MatrixEvent) => { + const eventId = event.getId(); + if (!eventId || seenEventIdsRef.current.has(eventId)) return; - seenEventIdsRef.current.add(eventId); + seenEventIdsRef.current.add(eventId); - if (ownEventIdsRef.current.has(eventId)) { - ownEventIdsRef.current.delete(eventId); - return; - } + if (ownEventIdsRef.current.has(eventId)) { + ownEventIdsRef.current.delete(eventId); + return; + } - scheduleBurst(event, addBurst); - }, [addBurst]); + scheduleBurst(event, addBurst); + }, + [addBurst], + ); const triggerLocalBurst = useCallback( (targetEventId: string, emojis: string[], origin?: BurstPoint) => { const burstId = `local-${targetEventId}-${Date.now()}`; scheduleBurstFromValues(burstId, emojis, targetEventId, addBurst, 0, origin); }, - [addBurst] + [addBurst], ); useEffect(() => { @@ -110,7 +110,7 @@ export function useEmojiConfetti(room: Room) { event: MatrixEvent, eventRoom: Room | undefined, toStartOfTimeline?: boolean, - removed?: boolean + removed?: boolean, ) => void = (event, eventRoom, toStartOfTimeline, removed) => { if (removed || toStartOfTimeline || eventRoom?.roomId !== room.roomId) return; if (event.getType() !== EMOJI_CONFETTI_EVENT_TYPE) return; diff --git a/src/app/features/room/emoji-confetti/useJumboEmojiConfetti.ts b/src/app/features/room/emoji-confetti/useJumboEmojiConfetti.ts index e211cfee..2f900d37 100644 --- a/src/app/features/room/emoji-confetti/useJumboEmojiConfetti.ts +++ b/src/app/features/room/emoji-confetti/useJumboEmojiConfetti.ts @@ -10,7 +10,11 @@ export function useJumboEmojiConfetti(room: Room) { const { bursts, removeBurst, triggerLocalBurst, registerOwnEventId } = useEmojiConfetti(room); const handleJumboEmojiClick = useCallback( - (targetEventId: string, body: string, event: MouseEvent | KeyboardEvent) => { + ( + targetEventId: string, + body: string, + event: MouseEvent | KeyboardEvent, + ) => { const clicked = resolveClickedEmoji(event, body); if (!clicked) return; @@ -26,7 +30,7 @@ export function useJumboEmojiConfetti(room: Room) { console.error('[emoji-confetti] Failed to send confetti event:', error); }); }, - [mx, registerOwnEventId, room.roomId, triggerLocalBurst] + [mx, registerOwnEventId, room.roomId, triggerLocalBurst], ); return { diff --git a/src/app/features/room/jump-to-time/JumpToTime.tsx b/src/app/features/room/jump-to-time/JumpToTime.tsx index 6af1f865..971a7c68 100644 --- a/src/app/features/room/jump-to-time/JumpToTime.tsx +++ b/src/app/features/room/jump-to-time/JumpToTime.tsx @@ -1,8 +1,24 @@ import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner, Chip, PopOut, RectCords } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Dialog, + Overlay, + OverlayCenter, + OverlayBackdrop, + Header, + config, + Box, + Text, + IconButton, + color, + Button, + Spinner, + Chip, + PopOut, + RectCords, +} from 'folds'; import { Direction, MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { stopPropagation } from '../../../utils/keyboard'; @@ -56,8 +72,8 @@ export function JumpToTime({ onCancel, onSubmit }: JumpToTimeProps) { const result = await mx.timestampToEvent(room.roomId, newTs, Direction.Forward); return result.event_id; }, - [mx, room] - ) + [mx, room], + ), ); const handleSubmit = () => { diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 3382d73f..88cf472e 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -1,5 +1,26 @@ -import { Avatar, Box, Button, Dialog, Header, IconButton, Input, Line, Menu, MenuItem, Modal, Overlay, OverlayBackdrop, OverlayCenter, PopOut, RectCords, Spinner, Text, as, color, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Box, + Button, + Dialog, + Header, + IconButton, + Input, + Line, + Menu, + MenuItem, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, + PopOut, + RectCords, + Spinner, + Text, + as, + color, + config, +} from 'folds'; import React, { FormEventHandler, MouseEventHandler, @@ -14,6 +35,7 @@ import { MatrixEvent, Room } from 'matrix-js-sdk'; import { Relations } from 'matrix-js-sdk/lib/models/relations'; import classNames from 'classnames'; import { RoomPinnedEventsEventContent } from 'matrix-js-sdk/lib/types'; +import { Icon, Icons } from '../../../components/icons'; import { AvatarBase, BubbleLayout, @@ -109,7 +131,7 @@ export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>( ); - } + }, ); export const MessageAllReactionItem = as< @@ -432,8 +454,8 @@ export const MessageDeleteItem = as< useCallback( (eventId: string, reason?: string) => mx.redactEvent(room.roomId, eventId, undefined, reason ? { reason } : undefined), - [mx, room] - ) + [mx, room], + ), ); const handleSubmit: FormEventHandler = (evt) => { @@ -571,8 +593,8 @@ export const MessageReportItem = as< useCallback( (eventId: string, score: number, reason: string) => mx.reportEvent(room.roomId, eventId, score, reason), - [mx, room] - ) + [mx, room], + ), ); const handleSubmit: FormEventHandler = (evt) => { @@ -707,7 +729,7 @@ export type MessageProps = { onUsernameClick: MouseEventHandler; onReplyClick: ( ev: Parameters>[0], - startThread?: boolean + startThread?: boolean, ) => void; onEditId?: (eventId?: string) => void; onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void; @@ -754,7 +776,7 @@ export const Message = as<'div', MessageProps>( children, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -764,7 +786,7 @@ export const Message = as<'div', MessageProps>( const { assetUrls } = useOtherUserCollectibles(senderId); const nameplateUrl = pickNameplateUrl(assetUrls); const nameplateIsVideo = Boolean( - assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm'] + assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm'], ); const avatarDecorationUrl = pickAvatarDecorationUrl(assetUrls); @@ -867,7 +889,12 @@ export const Message = as<'div', MessageProps>( playsInline /> ) : ( - + )}
)} @@ -875,13 +902,14 @@ export const Message = as<'div', MessageProps>( ); - const presenceClass = senderPresence?.presence === Presence.Online - ? css.MessageAvatarOnline - : senderPresence?.presence === Presence.Unavailable - ? css.MessageAvatarUnavailable - : senderPresence?.presence === Presence.Offline - ? css.MessageAvatarOffline - : undefined; + const presenceClass = + senderPresence?.presence === Presence.Online + ? css.MessageAvatarOnline + : senderPresence?.presence === Presence.Unavailable + ? css.MessageAvatarUnavailable + : senderPresence?.presence === Presence.Offline + ? css.MessageAvatarOffline + : undefined; const avatarJSX = !collapse && messageLayout !== MessageLayout.Compact && ( ( ( userId={senderId} src={ senderAvatarMxc - ? mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? + undefined) : undefined } alt={senderDisplayName} @@ -947,7 +976,8 @@ export const Message = as<'div', MessageProps>( const handleContextMenu: MouseEventHandler = (evt) => { if (evt.altKey || !window.getSelection()?.isCollapsed || edit) return; const tag = (evt.target as any).tagName; - if (typeof tag === 'string' && (tag.toLowerCase() === 'a' || tag.toLowerCase() === 'img')) return; + if (typeof tag === 'string' && (tag.toLowerCase() === 'a' || tag.toLowerCase() === 'img')) + return; evt.preventDefault(); setMenuAnchor({ x: evt.clientX, @@ -1002,184 +1032,164 @@ export const Message = as<'div', MessageProps>( className={css.MessageContentLayer} data-message-nameplate-readable={showNameplate ? '' : undefined} > - {!edit && (hover || !!menuAnchor || !!emojiBoardAnchor) && ( -
- - - {canSendReaction && ( - { - onReactionToggle(mEvent.getId()!, key); - setEmojiBoardAnchor(undefined); - }} - onCustomEmojiSelect={(mxc, shortcode) => { - onReactionToggle(mEvent.getId()!, mxc, shortcode); - setEmojiBoardAnchor(undefined); - }} - requestClose={() => { - setEmojiBoardAnchor(undefined); - }} - /> - } - > - + + + {canSendReaction && ( + { + onReactionToggle(mEvent.getId()!, key); + setEmojiBoardAnchor(undefined); + }} + onCustomEmojiSelect={(mxc, shortcode) => { + onReactionToggle(mEvent.getId()!, mxc, shortcode); + setEmojiBoardAnchor(undefined); + }} + requestClose={() => { + setEmojiBoardAnchor(undefined); + }} + /> + } > - - - - )} - - - - {!isThreadedMessage && ( + + + + + )} onReplyClick(ev, true)} + onClick={onReplyClick} data-event-id={mEvent.getId()} variant="SurfaceVariant" size="300" radii="300" > - + - )} - {canEditEvent(mx, mEvent) && onEditId && ( - onEditId(mEvent.getId())} - variant="SurfaceVariant" - size="300" - radii="300" - > - - - )} - {mEvent.getContent().body && !mEvent.isRedacted() && ( - { - const rawText = mEvent.getContent().body ?? ''; - if (rawText) copyToClipboard(rawText); - }} - variant="SurfaceVariant" - size="300" - radii="300" - title="Copy Raw Text" - > - - - )} - {shiftHeld && canDelete && ( - { - const eventId = mEvent.getId(); - if (eventId) { - mx.redactEvent(room.roomId, eventId); - } - }} - variant="Critical" - size="300" - radii="300" - title="Delete Message (Shift held)" - > - - - )} - - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} + {!isThreadedMessage && ( + onReplyClick(ev, true)} + data-event-id={mEvent.getId()} + variant="SurfaceVariant" + size="300" + radii="300" > - - {canSendReaction && ( - { - onReactionToggle(mEvent.getId()!, key, shortcode); - closeMenu(); - }} - /> - )} - + + + )} + {canEditEvent(mx, mEvent) && onEditId && ( + onEditId(mEvent.getId())} + variant="SurfaceVariant" + size="300" + radii="300" + > + + + )} + {mEvent.getContent().body && !mEvent.isRedacted() && ( + { + const rawText = mEvent.getContent().body ?? ''; + if (rawText) copyToClipboard(rawText); + }} + variant="SurfaceVariant" + size="300" + radii="300" + title="Copy Raw Text" + > + + + )} + {shiftHeld && canDelete && ( + { + const eventId = mEvent.getId(); + if (eventId) { + mx.redactEvent(room.roomId, eventId); + } + }} + variant="Critical" + size="300" + radii="300" + title="Delete Message (Shift held)" + > + + + )} + + setMenuAnchor(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, + }} + > + {canSendReaction && ( - } - radii="300" - onClick={handleAddReactions} - > - - Add Reaction - - - )} - {relations && ( - { + onReactionToggle(mEvent.getId()!, key, shortcode); + closeMenu(); + }} /> )} - } - radii="300" - data-event-id={mEvent.getId()} - onClick={(evt: any) => { - onReplyClick(evt); - closeMenu(); - }} - > - - Reply - - - {!isThreadedMessage && ( + + {canSendReaction && ( + } + radii="300" + onClick={handleAddReactions} + > + + Add Reaction + + + )} + {relations && ( + + )} } + after={} radii="300" data-event-id={mEvent.getId()} onClick={(evt: any) => { - onReplyClick(evt, true); + onReplyClick(evt); closeMenu(); }} > @@ -1189,111 +1199,131 @@ export const Message = as<'div', MessageProps>( size="T300" truncate > - Reply in Thread + Reply - )} - {canEditEvent(mx, mEvent) && onEditId && ( - } - radii="300" - data-event-id={mEvent.getId()} - onClick={() => { - onEditId(mEvent.getId()); - closeMenu(); - }} - > - } + radii="300" + data-event-id={mEvent.getId()} + onClick={(evt: any) => { + onReplyClick(evt, true); + closeMenu(); + }} > - Edit Message - - + + Reply in Thread + + + )} + {canEditEvent(mx, mEvent) && onEditId && ( + } + radii="300" + data-event-id={mEvent.getId()} + onClick={() => { + onEditId(mEvent.getId()); + closeMenu(); + }} + > + + Edit Message + + + )} + {!hideReadReceipts && ( + + )} + {showDeveloperTools && ( + + )} + + + {canPinEvent && ( + + )} + + {((!mEvent.isRedacted() && canDelete) || + mEvent.getSender() !== mx.getUserId()) && ( + <> + + + {!mEvent.isRedacted() && canDelete && ( + + )} + {mEvent.getSender() !== mx.getUserId() && ( + + )} + + )} - {!hideReadReceipts && ( - - )} - {showDeveloperTools && ( - - )} - - - {canPinEvent && ( - - )} - - {((!mEvent.isRedacted() && canDelete) || - mEvent.getSender() !== mx.getUserId()) && ( - <> - - - {!mEvent.isRedacted() && canDelete && ( - - )} - {mEvent.getSender() !== mx.getUserId() && ( - - )} - - - )} - - - } - > - + + } > - - - - - -
- )} - {messageLayout === MessageLayout.Compact && ( - - {msgContentJSX} - - )} - {messageLayout === MessageLayout.Bubble && ( - - {msgContentJSX} - - )} - {messageLayout !== MessageLayout.Compact && messageLayout !== MessageLayout.Bubble && ( - - {headerJSX} - {msgContentJSX} - - )} + + + + + + +
+ )} + {messageLayout === MessageLayout.Compact && ( + + {msgContentJSX} + + )} + {messageLayout === MessageLayout.Bubble && ( + + {msgContentJSX} + + )} + {messageLayout !== MessageLayout.Compact && messageLayout !== MessageLayout.Bubble && ( + + {headerJSX} + {msgContentJSX} + + )}
); - } + }, ); export type EventProps = { @@ -1319,7 +1349,7 @@ export const Event = as<'div', EventProps>( children, ...props }, - ref + ref, ) => { const mx = useMatrixClient(); const [hover, setHover] = useState(false); @@ -1331,7 +1361,8 @@ export const Event = as<'div', EventProps>( const handleContextMenu: MouseEventHandler = (evt) => { if (evt.altKey || !window.getSelection()?.isCollapsed) return; const tag = (evt.target as any).tagName; - if (typeof tag === 'string' && (tag.toLowerCase() === 'a' || tag.toLowerCase() === 'img')) return; + if (typeof tag === 'string' && (tag.toLowerCase() === 'a' || tag.toLowerCase() === 'img')) + return; evt.preventDefault(); setMenuAnchor({ x: evt.clientX, @@ -1446,5 +1477,5 @@ export const Event = as<'div', EventProps>(
{children}
); - } + }, ); diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 7757b659..348ce753 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -6,10 +6,10 @@ import React, { useState, } from 'react'; import { Box, Chip, IconButton, Line, PopOut, RectCords, Spinner, Text, as, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { Editor, Transforms } from 'slate'; import { IContent, IMentions, MatrixEvent, RelationType, Room } from 'matrix-js-sdk'; import { isKeyHotkey } from 'is-hotkey'; +import { Icon, Icons } from '../../../components/icons'; import { AUTOCOMPLETE_PREFIXES, AutocompletePrefix, @@ -66,7 +66,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( const getPrevBodyAndFormattedBody = useCallback((): [ string | undefined, string | undefined, - IMentions | undefined + IMentions | undefined, ] => { const evtId = mEvent.getId()!; const evtTimeline = room.getTimelineForEvent(evtId); @@ -93,7 +93,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( allowTextFormatting: true, allowBlockMarkdown: isMarkdown, allowInlineMarkdown: isMarkdown, - }) + }), ); const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody(); @@ -142,7 +142,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( }; return mx.sendMessage(roomId, content); - }, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody]) + }, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody]), ); const handleSave = useCallback(() => { @@ -165,7 +165,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( onCancel(); } }, - [onCancel, handleSave, enterForNewline, isComposing] + [onCancel, handleSave, enterForNewline, isComposing], ); const handleKeyUp: KeyboardEventHandler = useCallback( @@ -181,7 +181,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( : undefined; setAutocompleteQuery(query); }, - [editor] + [editor], ); const handleCloseAutocomplete = useCallback(() => { @@ -314,7 +314,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( onClick={ ((evt) => setAnchor( - evt.currentTarget.getBoundingClientRect() + evt.currentTarget.getBoundingClientRect(), )) as MouseEventHandler } variant="SurfaceVariant" @@ -339,5 +339,5 @@ export const MessageEditor = as<'div', MessageEditorProps>( />
); - } + }, ); diff --git a/src/app/features/room/message/Reactions.tsx b/src/app/features/room/message/Reactions.tsx index 2bee5e9c..fbb4b7b2 100644 --- a/src/app/features/room/message/Reactions.tsx +++ b/src/app/features/room/message/Reactions.tsx @@ -39,7 +39,7 @@ export const Reactions = as<'div', ReactionsProps>( const myUserId = mx.getUserId(); const reactions = useRelations( relations, - useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], []) + useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], []), ); const handleViewReaction: MouseEventHandler = (evt) => { @@ -127,5 +127,5 @@ export const Reactions = as<'div', ReactionsProps>( )} ); - } + }, ); diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 5132dfd0..519f5bba 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -31,7 +31,7 @@ const generateThumbnailContent = async ( mx: MatrixClient, img: HTMLImageElement | HTMLVideoElement, dimensions: [number, number], - encrypt: boolean + encrypt: boolean, ): Promise => { const thumbnail = await getThumbnail(img, ...dimensions); if (!thumbnail) throw new Error('Can not create thumbnail!'); @@ -56,7 +56,7 @@ export const getImageMsgContent = async ( mx: MatrixClient, item: TUploadItem, mxc: string, - carouselMetadata?: CarouselMetadata + carouselMetadata?: CarouselMetadata, ): Promise => { const { file, originalFile, encInfo, metadata } = item; const [imgError, imgEl] = await to(loadImageElement(getImageFileUrl(originalFile))); @@ -99,7 +99,7 @@ export const getImageMsgContent = async ( export const getVideoMsgContent = async ( mx: MatrixClient, item: TUploadItem, - mxc: string + mxc: string, ): Promise => { const { file, originalFile, encInfo, metadata } = item; @@ -118,14 +118,14 @@ export const getVideoMsgContent = async ( mx, videoEl, getThumbnailDimensions(videoEl.videoWidth, videoEl.videoHeight), - !!encInfo - ) + !!encInfo, + ), ); if (thumbContent && thumbContent.thumbnail_info) { thumbContent.thumbnail_info[MATRIX_BLUR_HASH_PROPERTY_NAME] = encodeBlurHash( videoEl, 512, - scaleYDimension(videoEl.videoWidth, 512, videoEl.videoHeight) + scaleYDimension(videoEl.videoWidth, 512, videoEl.videoHeight), ); } if (thumbError) console.warn(thumbError); diff --git a/src/app/features/room/reaction-viewer/ReactionViewer.tsx b/src/app/features/room/reaction-viewer/ReactionViewer.tsx index 76911279..19b151b5 100644 --- a/src/app/features/room/reaction-viewer/ReactionViewer.tsx +++ b/src/app/features/room/reaction-viewer/ReactionViewer.tsx @@ -1,9 +1,9 @@ import React, { useCallback, useState } from 'react'; import classNames from 'classnames'; import { Avatar, Box, Header, IconButton, Line, MenuItem, Scroll, Text, as, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { MatrixEvent, Room, RoomMember } from 'matrix-js-sdk'; import { Relations } from 'matrix-js-sdk/lib/models/relations'; +import { Icon, Icons } from '../../../components/icons'; import { getMemberDisplayName } from '../../../utils/room'; import { eventWithShortcode, getMxIdLocalPart } from '../../../utils/matrix'; import * as css from './ReactionViewer.css'; @@ -29,7 +29,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( const useAuthentication = useMediaAuthentication(); const reactions = useRelations( relations, - useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], []) + useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], []), ); const space = useSpaceOptionally(); const openProfile = useOpenUserRoomProfile(); @@ -111,7 +111,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( 'crop', undefined, false, - useAuthentication + useAuthentication, ) : undefined; @@ -126,7 +126,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( space?.roomId, senderId, getMouseEventCords(event.nativeEvent), - 'Bottom' + 'Bottom', ); }} before={ @@ -154,5 +154,5 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( ); - } + }, ); diff --git a/src/app/features/room/room-media-menu/RoomMediaMenu.tsx b/src/app/features/room/room-media-menu/RoomMediaMenu.tsx index c7375005..1873d7f3 100644 --- a/src/app/features/room/room-media-menu/RoomMediaMenu.tsx +++ b/src/app/features/room/room-media-menu/RoomMediaMenu.tsx @@ -1,16 +1,5 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; -import { - Box, - Header, - IconButton, - Scroll, - Spinner, - Text, - as, - config, - Chip, - Avatar, -} from 'folds'; +import { Box, Header, IconButton, Scroll, Spinner, Text, as, config, Chip, Avatar } from 'folds'; import { MsgType, Room } from 'matrix-js-sdk'; import { useAtom } from 'jotai'; import classNames from 'classnames'; @@ -43,7 +32,7 @@ import { ContainerColor } from '../../../styles/ContainerColor.css'; const fetchAuthenticatedMedia = async ( url: string, - accessToken: string | null + accessToken: string | null, ): Promise => { try { let response = await fetch(url, { @@ -81,7 +70,7 @@ function MediaTileImageThumb({ item }: { item: RoomMediaItem & { thumbMxc: strin mediaUrl, (encBuf) => decryptFile(encBuf, item.thumbMimeType ?? FALLBACK_MIMETYPE, item.thumbEncInfo!), - accessToken + accessToken, ); return URL.createObjectURL(fileContent); } @@ -94,7 +83,7 @@ function MediaTileImageThumb({ item }: { item: RoomMediaItem & { thumbMxc: strin } return mediaUrl; - }, [mx, item.thumbMxc, item.thumbEncInfo, item.thumbMimeType, useAuthentication]) + }, [mx, item.thumbMxc, item.thumbEncInfo, item.thumbMimeType, useAuthentication]), ); useEffect(() => { @@ -109,7 +98,9 @@ function MediaTileImageThumb({ item }: { item: RoomMediaItem & { thumbMxc: strin }, [srcState]); if (srcState.status === AsyncStatus.Success) { - return {item.body}; + return ( + {item.body} + ); } return ( @@ -137,7 +128,7 @@ function MediaTileFullImageThumb({ item }: { item: RoomMediaItem }) { mediaUrl, (encBuf) => decryptFile(encBuf, item.fullMimeType ?? FALLBACK_MIMETYPE, item.fullEncInfo!), - accessToken + accessToken, ); return URL.createObjectURL(fileContent); } @@ -147,7 +138,7 @@ function MediaTileFullImageThumb({ item }: { item: RoomMediaItem }) { } return mediaUrl; - }, [mx, item.fullMxc, item.fullEncInfo, item.fullMimeType, useAuthentication]) + }, [mx, item.fullMxc, item.fullEncInfo, item.fullMimeType, useAuthentication]), ); useEffect(() => { @@ -162,7 +153,9 @@ function MediaTileFullImageThumb({ item }: { item: RoomMediaItem }) { }, [srcState]); if (srcState.status === AsyncStatus.Success) { - return {item.body}; + return ( + {item.body} + ); } return ( @@ -184,11 +177,7 @@ function MediaTileThumb({ item }: MediaTileThumbProps) { if (item.msgtype === MsgType.Video) { return ( - + (({ room, solo = false, className, ...props }, ref) => { - const mx = useMatrixClient(); - const useAuthentication = useMediaAuthentication(); - const { navigateRoom } = useRoomNavigate(); - const [, setMediaDrawer] = useAtom(isMediaDrawerAtom); - const { items, loading, hasMore, loadMore } = useRoomMediaEvents(room); - const [excludedSenders, setExcludedSenders] = useState>(() => new Set()); - const scrollRef = useRef(null); - const restoredScrollRef = useRef(false); +export const MediaDrawer = as<'div', MediaDrawerProps>( + ({ room, solo = false, className, ...props }, ref) => { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); + const { navigateRoom } = useRoomNavigate(); + const [, setMediaDrawer] = useAtom(isMediaDrawerAtom); + const { items, loading, hasMore, loadMore } = useRoomMediaEvents(room); + const [excludedSenders, setExcludedSenders] = useState>(() => new Set()); + const scrollRef = useRef(null); + const restoredScrollRef = useRef(false); - const senders = useMemo(() => { - const counts = new Map(); - for (const item of items) { - counts.set(item.sender, (counts.get(item.sender) ?? 0) + 1); - } + const senders = useMemo(() => { + const counts = new Map(); + for (const item of items) { + counts.set(item.sender, (counts.get(item.sender) ?? 0) + 1); + } - return Array.from(counts.entries()) - .map(([userId, count]) => ({ - userId, - count, - name: getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId, - avatarMxc: getMemberAvatarMxc(room, userId), - })) - .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)); - }, [items, room]); + return Array.from(counts.entries()) + .map(([userId, count]) => ({ + userId, + count, + name: getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId, + avatarMxc: getMemberAvatarMxc(room, userId), + })) + .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)); + }, [items, room]); - const filteredItems = useMemo( - () => items.filter((item) => !excludedSenders.has(item.sender)), - [items, excludedSenders] - ); - const sections = useMemo(() => groupMediaByMonthAndDay(filteredItems), [filteredItems]); + const filteredItems = useMemo( + () => items.filter((item) => !excludedSenders.has(item.sender)), + [items, excludedSenders], + ); + const sections = useMemo(() => groupMediaByMonthAndDay(filteredItems), [filteredItems]); - useLayoutEffect(() => { - restoredScrollRef.current = false; - }, [room.roomId]); + useLayoutEffect(() => { + restoredScrollRef.current = false; + }, [room.roomId]); - useLayoutEffect(() => { - if (restoredScrollRef.current || items.length === 0) return; - const el = scrollRef.current; - if (!el) return; - const saved = getMediaDrawerScrollTop(room.roomId); - if (typeof saved === 'number') { - el.scrollTop = saved; - } - restoredScrollRef.current = true; - }, [room.roomId, items.length]); + useLayoutEffect(() => { + if (restoredScrollRef.current || items.length === 0) return; + const el = scrollRef.current; + if (!el) return; + const saved = getMediaDrawerScrollTop(room.roomId); + if (typeof saved === 'number') { + el.scrollTop = saved; + } + restoredScrollRef.current = true; + }, [room.roomId, items.length]); - const handleClose = useCallback(() => { - setMediaDrawer(false); - }, [setMediaDrawer]); + const handleClose = useCallback(() => { + setMediaDrawer(false); + }, [setMediaDrawer]); + + const handleSenderClick = useCallback( + (evt: React.MouseEvent, userId: string) => { + if (evt.ctrlKey || evt.metaKey) { + evt.preventDefault(); + const allIds = senders.map((sender) => sender.userId); + setExcludedSenders((prev) => { + const enabledIds = allIds.filter((id) => !prev.has(id)); + const alreadySolo = enabledIds.length === 1 && enabledIds[0] === userId; + if (alreadySolo) return new Set(); + return new Set(allIds.filter((id) => id !== userId)); + }); + return; + } - const handleSenderClick = useCallback( - (evt: React.MouseEvent, userId: string) => { - if (evt.ctrlKey || evt.metaKey) { - evt.preventDefault(); - const allIds = senders.map((sender) => sender.userId); setExcludedSenders((prev) => { - const enabledIds = allIds.filter((id) => !prev.has(id)); - const alreadySolo = enabledIds.length === 1 && enabledIds[0] === userId; - if (alreadySolo) return new Set(); - return new Set(allIds.filter((id) => id !== userId)); + const next = new Set(prev); + if (next.has(userId)) next.delete(userId); + else next.add(userId); + return next; }); - return; - } + }, + [senders], + ); - setExcludedSenders((prev) => { - const next = new Set(prev); - if (next.has(userId)) next.delete(userId); - else next.add(userId); - return next; - }); - }, - [senders] - ); + const handleOpen = useCallback( + (eventId: string) => { + navigateRoom(room.roomId, eventId); + if (solo) setMediaDrawer(false); + }, + [navigateRoom, room.roomId, solo, setMediaDrawer], + ); - const handleOpen = useCallback( - (eventId: string) => { - navigateRoom(room.roomId, eventId); - if (solo) setMediaDrawer(false); - }, - [navigateRoom, room.roomId, solo, setMediaDrawer] - ); + const handleScroll = useCallback( + (evt: React.UIEvent) => { + const el = evt.currentTarget; + setMediaDrawerScrollTop(room.roomId, el.scrollTop); + const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 80; + if (nearBottom && hasMore && !loading) { + loadMore(); + } + }, + [hasMore, loading, loadMore, room.roomId], + ); - const handleScroll = useCallback( - (evt: React.UIEvent) => { - const el = evt.currentTarget; - setMediaDrawerScrollTop(room.roomId, el.scrollTop); - const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 80; - if (nearBottom && hasMore && !loading) { - loadMore(); - } - }, - [hasMore, loading, loadMore, room.roomId] - ); + return ( + +
+ + + Shared Media + + + + + +
- return ( - -
- - - Shared Media - - - - - -
+ {senders.length > 0 && ( +
+
+ {senders.map((sender) => { + const enabled = !excludedSenders.has(sender.userId); + const avatarUrl = sender.avatarMxc + ? (mxcUrlToHttp(mx, sender.avatarMxc, useAuthentication, 48, 48, 'crop') ?? + undefined) + : undefined; - {senders.length > 0 && ( -
-
- {senders.map((sender) => { - const enabled = !excludedSenders.has(sender.userId); - const avatarUrl = sender.avatarMxc - ? mxcUrlToHttp(mx, sender.avatarMxc, useAuthentication, 48, 48, 'crop') ?? - undefined - : undefined; - - return ( - handleSenderClick(evt, sender.userId)} - before={ - - ( - - {sender.name.slice(0, 1).toUpperCase()} - - )} - /> - - } - > - - {sender.name} - - - ); - })} -
-
- )} - - - -
- {items.length === 0 && !loading && ( - - No shared photos or videos yet. - - )} - - {items.length > 0 && filteredItems.length === 0 && ( - - No media from the selected people. - - )} - - {sections.map((month) => ( -
- - {month.monthLabel} - - {month.days.map((day) => ( -
- - {day.dayLabel} - -
- {day.items.map((item) => ( - - ))} -
-
- ))} -
- ))} - - {(loading || hasMore) && ( -
- {loading && } -
- )} + /> + + } + > + + {sender.name} + + + ); + })} +
- + )} + + + +
+ {items.length === 0 && !loading && ( + + No shared photos or videos yet. + + )} + + {items.length > 0 && filteredItems.length === 0 && ( + + No media from the selected people. + + )} + + {sections.map((month) => ( +
+ + {month.monthLabel} + + {month.days.map((day) => ( +
+ + {day.dayLabel} + +
+ {day.items.map((item) => ( + + ))} +
+
+ ))} +
+ ))} + + {(loading || hasMore) && ( +
+ {loading && } +
+ )} +
+
+
- - ); -}); + ); + }, +); diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 84999ad8..9acf269c 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -2,11 +2,24 @@ import React, { forwardRef, MouseEventHandler, useCallback, useMemo, useRef } from 'react'; import { MatrixEvent, Room } from 'matrix-js-sdk'; import { RoomPinnedEventsEventContent } from 'matrix-js-sdk/lib/types'; -import { Avatar, Box, Chip, color, config, Header, IconButton, Menu, Scroll, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Box, + Chip, + color, + config, + Header, + IconButton, + Menu, + Scroll, + Spinner, + Text, + toRem, +} from 'folds'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { HTMLReactParserOptions } from 'html-react-parser'; import { useVirtualizer } from '@tanstack/react-virtual'; +import { Icon, Icons } from '../../../components/icons'; import { useRoomPinnedEvents } from '../../../hooks/useRoomPinnedEvents'; import * as css from './RoomPinMenu.css'; import { SequenceCard } from '../../../components/sequence-card'; @@ -111,7 +124,7 @@ function PinnedMessage({ }; return mx.sendStateEvent(room.roomId, StateEvent.RoomPinnedEvents as any, newContent); - }, [room, eventId, mx]) + }, [room, eventId, mx]), ); const sender = pinnedEvent?.getSender(); @@ -188,8 +201,8 @@ function PinnedMessage({ userId={sender} src={ senderAvatarMxc - ? mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? - undefined + ? (mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ?? + undefined) : undefined } alt={displayName} @@ -255,7 +268,7 @@ export const RoomPinMenu = forwardRef( const accessibleTagColors = useAccessiblePowerTagColors( theme.kind, creatorsTag, - powerLevelTags + powerLevelTags, ); const pinnedEvents = useRoomPinnedEvents(room); @@ -287,10 +300,10 @@ export const RoomPinMenu = forwardRef( () => ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)), ), }), - [mx, room, mentionClickHandler] + [mx, room, mentionClickHandler], ); const htmlReactParserOptions = useMemo( () => @@ -300,7 +313,7 @@ export const RoomPinMenu = forwardRef( handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, }), - [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication] + [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication], ); const renderMatrixEvent = useMatrixEventRenderer<[MatrixEvent, string, GetContentCallback]>( @@ -431,7 +444,7 @@ export const RoomPinMenu = forwardRef( ); - } + }, ); const handleOpen = (roomId: string, eventId: string) => { @@ -531,5 +544,5 @@ export const RoomPinMenu = forwardRef( ); - } + }, ); diff --git a/src/app/features/search/Search.tsx b/src/app/features/search/Search.tsx index 7af0e848..85e51432 100644 --- a/src/app/features/search/Search.tsx +++ b/src/app/features/search/Search.tsx @@ -1,6 +1,18 @@ import FocusTrap from 'focus-trap-react'; -import { Avatar, Box, config, Input, Line, MenuItem, Modal, Overlay, OverlayCenter, Scroll, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Avatar, + Box, + config, + Input, + Line, + MenuItem, + Modal, + Overlay, + OverlayCenter, + Scroll, + Text, + toRem, +} from 'folds'; import React, { ChangeEventHandler, KeyboardEventHandler, @@ -14,6 +26,7 @@ import React, { import { isKeyHotkey } from 'is-hotkey'; import { useAtom, useAtomValue } from 'jotai'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../components/icons'; import { useDirects, useOrphanSpaces, useRooms, useSpaces } from '../../state/hooks/roomList'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { mDirectAtom } from '../../state/mDirectList'; @@ -63,7 +76,7 @@ const useTopActiveRooms = ( searchRoomType: SearchRoomType | undefined, rooms: string[], directs: string[], - spaces: string[] + spaces: string[], ) => { const mx = useMatrixClient(); @@ -84,7 +97,7 @@ const useTopActiveRooms = ( const getDmUserId = ( roomId: string, getRoom: (roomId: string) => Room | undefined, - myUserId: string + myUserId: string, ): string | undefined => { const room = getRoom(roomId); const targetUserId = room && guessDmRoomUserId(room, myUserId); @@ -95,7 +108,7 @@ const useSearchTargetRooms = ( searchRoomType: SearchRoomType | undefined, rooms: string[], directs: string[], - spaces: string[] + spaces: string[], ) => useMemo(() => { if (searchRoomType === undefined) { @@ -165,7 +178,7 @@ export function Search({ requestClose }: SearchProps) { } return roomName; }, - [getRoom, mDirects, mx] + [getRoom, mDirects, mx], ); const [result, search, resetSearch] = useAsyncSearch(targetRooms, getTargetStr, SEARCH_OPTIONS); @@ -439,8 +452,8 @@ export function SearchModalRenderer() { setOpen(true); } }, - [opened, setOpen] - ) + [opened, setOpen], + ), ); return opened && setOpen(false)} />; diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 26fa823a..479498d3 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -12,8 +12,8 @@ import { OverlayCenter, Text, } from 'folds'; -import { Icon, Icons, IconSrc } from '../../components/icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons, IconSrc } from '../../components/icons'; import { General } from './general'; import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; @@ -39,10 +39,7 @@ import { SETTINGS_SEARCH_CATALOG } from './settingsSearchCatalog'; import { SettingsPages } from './SettingsPages'; import { SettingsSearchResult } from './styles.css'; import { BreakWord } from '../../styles/Text.css'; -import { - SettingsFocusProvider, - settingAnchorId, -} from '../../components/setting-tile'; +import { SettingsFocusProvider, settingAnchorId } from '../../components/setting-tile'; export { SettingsPages }; @@ -101,7 +98,7 @@ const useSettingsMenuItems = (): SettingsMenuItem[] => icon: Icons.Info, }, ], - [] + [], ); type SettingsProps = { @@ -115,7 +112,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { const profile = useUserProfile(userId); const displayName = profile.displayName ?? getMxIdLocalPart(userId) ?? userId; const avatarUrl = profile.avatarUrl - ? mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const screenSize = useScreenSizeContext(); @@ -152,7 +149,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { anchorId: focusAnchorId, setAnchorId: setFocusAnchorId, }), - [focusAnchorId] + [focusAnchorId], ); const handlePageRequestClose = () => { @@ -175,7 +172,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { setActivePage(page); setSearchQuery(''); }, - [pageNameByPage] + [pageNameByPage], ); // Fallback scroll if the page just mounted and tiles need a moment to render. @@ -384,9 +381,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { {activePage === SettingsPages.NotificationPage && ( )} - {activePage === SettingsPages.AudioPage && ( -
{thumbUrl && ( - + )}
@@ -265,7 +260,7 @@ function CollectibleVariantGroupCard({ className={classNames( css.CollectibleGroupPreview, applyingId && css.CollectibleGroupPreviewDisabled, - applyingId && applyingId !== selectedItem.id && css.CollectibleGroupPreviewDimmed + applyingId && applyingId !== selectedItem.id && css.CollectibleGroupPreviewDimmed, )} onMouseEnter={handlePreviewHover} onClick={() => onApply(selectedItem)} @@ -277,7 +272,7 @@ function CollectibleVariantGroupCard({ className={classNames( css.CollectiblePreviewFrame, kind === 'avatar_decoration' && css.CollectiblePreviewFrameDecoration, - kind === 'profile_effect' && css.CollectiblePreviewFrameProfileEffect + kind === 'profile_effect' && css.CollectiblePreviewFrameProfileEffect, )} style={{ aspectRatio: kind === 'nameplate' ? undefined : aspectRatio, @@ -327,14 +322,13 @@ export function CollectiblesSection({ collectibles, onApply }: CollectiblesSecti const previewAvatarUrl = useMemo( () => profile.avatarUrl - ? mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined, - [mx, profile.avatarUrl, useAuthentication] + [mx, profile.avatarUrl, useAuthentication], ); const previewBannerUrl = useMemo( - () => - bannerMxc ? mxcUrlToHttp(mx, bannerMxc, useAuthentication) ?? undefined : undefined, - [bannerMxc, mx, useAuthentication] + () => (bannerMxc ? (mxcUrlToHttp(mx, bannerMxc, useAuthentication) ?? undefined) : undefined), + [bannerMxc, mx, useAuthentication], ); const previewDisplayName = profile.displayName; const [kind, setKind] = useState('profile_effect'); @@ -430,14 +424,14 @@ export function CollectiblesSection({ collectibles, onApply }: CollectiblesSecti css.CollectibleGroupGrid, kind === 'nameplate' && css.CollectibleGroupGridNameplate, kind === 'profile_effect' && css.CollectibleGroupGridEffects, - kind === 'avatar_decoration' && css.CollectibleGroupGridDecorations + kind === 'avatar_decoration' && css.CollectibleGroupGridDecorations, ); return ( - Browse a community-published Discord collectibles catalog, then download and upload only what - you pick to Matrix. + Browse a community-published Discord collectibles catalog, then download and upload only + what you pick to Matrix. @@ -454,89 +448,97 @@ export function CollectiblesSection({ collectibles, onApply }: CollectiblesSecti <> - - {KIND_TABS.map((tab) => ( - - ))} + + {KIND_TABS.map((tab) => ( + + ))} + + + setSearch(e.target.value)} + /> + + {current && ( + + Active: {current.name} + + )} - setSearch(e.target.value)} - /> + {catalogLoading && ( + + + Loading collectibles catalog… + + )} - {current && ( - - Active: {current.name} - - - )} + {catalogError && !catalogLoading && ( + + {catalogError} + + )} - {catalogLoading && ( - - - Loading collectibles catalog… - - )} + {applyProgress && ( + + + {applyProgress} + + )} - {catalogError && !catalogLoading && ( - {catalogError} - )} + {error && ( + + {error} + + )} - {applyProgress && ( - - - {applyProgress} - - )} +
+ {filteredGroups.map((group) => { + const selectedSku = selectedByGroup[group.id] ?? group.items[0]?.skuId; + const selectedItem = + group.items.find((item) => item.skuId === selectedSku) ?? group.items[0]; + if (!selectedItem) return null; - {error && {error}} + return ( + + setSelectedByGroup((prev) => ({ ...prev, [group.id]: item.skuId })) + } + applyingId={applyingId} + onApply={handleApply} + previewAvatarUrl={previewAvatarUrl} + previewBannerUrl={previewBannerUrl} + previewDisplayName={previewDisplayName} + previewUserId={userId} + /> + ); + })} +
-
- {filteredGroups.map((group) => { - const selectedSku = selectedByGroup[group.id] ?? group.items[0]?.skuId; - const selectedItem = - group.items.find((item) => item.skuId === selectedSku) ?? group.items[0]; - if (!selectedItem) return null; - - return ( - - setSelectedByGroup((prev) => ({ ...prev, [group.id]: item.skuId })) - } - applyingId={applyingId} - onApply={handleApply} - previewAvatarUrl={previewAvatarUrl} - previewBannerUrl={previewBannerUrl} - previewDisplayName={previewDisplayName} - previewUserId={userId} - /> - ); - })} -
- - {!catalogLoading && filteredGroups.length === 0 && ( - No items match your search. - )} + {!catalogLoading && filteredGroups.length === 0 && ( + + No items match your search. + + )}
); diff --git a/src/app/features/settings/account/ContactInfo.tsx b/src/app/features/settings/account/ContactInfo.tsx index cfde7e29..ec6bca10 100644 --- a/src/app/features/settings/account/ContactInfo.tsx +++ b/src/app/features/settings/account/ContactInfo.tsx @@ -9,7 +9,7 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; export function ContactInformation() { const mx = useMatrixClient(); const [threePIdsState, loadThreePIds] = useAsyncCallback( - useCallback(() => mx.getThreePids(), [mx]) + useCallback(() => mx.getThreePids(), [mx]), ); const threePIds = threePIdsState.status === AsyncStatus.Success ? threePIdsState.data.threepids : undefined; diff --git a/src/app/features/settings/account/IgnoredUserList.tsx b/src/app/features/settings/account/IgnoredUserList.tsx index 747bb526..16206241 100644 --- a/src/app/features/settings/account/IgnoredUserList.tsx +++ b/src/app/features/settings/account/IgnoredUserList.tsx @@ -20,8 +20,8 @@ function IgnoreUserInput({ userList }: { userList: string[] }) { async (uId: string) => { await mx.setIgnoredUsers([...userList, uId]); }, - [mx, userList] - ) + [mx, userList], + ), ); const ignoring = ignoreState.status === AsyncStatus.Loading; @@ -101,8 +101,8 @@ function IgnoredUserChip({ userId, userList }: { userId: string; userList: strin const [unignoreState, unignore] = useAsyncCallback( useCallback( () => mx.setIgnoredUsers(userList.filter((uId) => uId !== userId)), - [mx, userId, userList] - ) + [mx, userId, userList], + ), ); const handleUnignore = () => unignore(); diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 18efe972..47cfc64b 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -9,10 +9,27 @@ import React, { useState, } from 'react'; import classNames from 'classnames'; -import { Box, Text, IconButton, Input, Avatar, Button, Overlay, OverlayBackdrop, OverlayCenter, Modal, Dialog, Header, config, Spinner, color, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + IconButton, + Input, + Avatar, + Button, + Overlay, + OverlayBackdrop, + OverlayCenter, + Modal, + Dialog, + Header, + config, + Spinner, + color, + toRem, +} from 'folds'; import { HexColorPicker } from 'react-colorful'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { UserProfile, useUserProfile } from '../../../hooks/useUserProfile'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../../utils/matrix'; @@ -54,7 +71,13 @@ import { /** * Banner upload component for user's profile banner (MSC4427 via MSC4133). */ -function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject; nameRef: React.RefObject }) { +function ProfileBanner({ + avatarRef, + nameRef, +}: { + avatarRef: React.RefObject; + nameRef: React.RefObject; +}) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const userId = mx.getUserId()!; @@ -90,7 +113,7 @@ function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject { @@ -106,7 +129,7 @@ function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject { @@ -431,7 +454,8 @@ function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject - {/* Banner/Cover wrapper - provides positioning context so status bubble is not inside the button */} + {/* Banner/Cover wrapper - provides positioning context so status bubble is not inside the button */} + pickFile('image/*')} + onMouseEnter={() => setHoveredArea('banner')} + onMouseLeave={() => setHoveredArea(null)} style={{ - position: 'relative', - height: toRem(140), + position: 'absolute', + inset: 0, width: '100%', + height: '100%', + overflow: 'hidden', + cursor: 'pointer', + border: 'none', + padding: 0, + backgroundColor: bannerBlobUrl ? 'transparent' : colorMXID(userId), + filter: bannerBlobUrl || authenticatedCoverUrl ? 'none' : 'brightness(50%)', + display: 'flex', + alignItems: 'center', }} > - pickFile('image/*')} - onMouseEnter={() => setHoveredArea('banner')} - onMouseLeave={() => setHoveredArea(null)} - style={{ - position: 'absolute', - inset: 0, - width: '100%', - height: '100%', - overflow: 'hidden', - cursor: 'pointer', - border: 'none', - padding: 0, - backgroundColor: bannerBlobUrl ? 'transparent' : colorMXID(userId), - filter: bannerBlobUrl || authenticatedCoverUrl ? 'none' : 'brightness(50%)', - display: 'flex', - alignItems: 'center', - }} - > - {bannerBlobUrl ? ( + {bannerBlobUrl ? ( + Banner + ) : ( + authenticatedCoverUrl && ( Banner - ) : ( - authenticatedCoverUrl && ( - Cover - ) - )} - {/* Banner hover overlay - right side action bar */} - {hoveredArea === 'banner' && ( + ) + )} + {/* Banner hover overlay - right side action bar */} + {hoveredArea === 'banner' && ( + + + + {userBanner && ( { + e.preventDefault(); + e.stopPropagation(); + handleRemoveBanner(); + }} style={{ - backgroundColor: color.Surface.Container, + backgroundColor: color.Critical.Main, borderRadius: toRem(16), padding: toRem(8), display: 'flex', alignItems: 'center', justifyContent: 'center', + cursor: 'pointer', + border: 'none', }} > - + - {userBanner && ( - { - e.preventDefault(); - e.stopPropagation(); - handleRemoveBanner(); - }} - style={{ - backgroundColor: color.Critical.Main, - borderRadius: toRem(16), - padding: toRem(8), - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - cursor: 'pointer', - border: 'none', - }} - > - - - )} - - )} - + )} + + )} +
- {/* Avatar Container - matches UserHeroAvatarContainer height */} + {/* Avatar Container - matches UserHeroAvatarContainer height */} + + {/* Avatar - centered */} setHoveredArea('avatar')} + onMouseLeave={() => setHoveredArea(null)} > - {/* Avatar - centered */} setHoveredArea('avatar')} - onMouseLeave={() => setHoveredArea(null)} > - + ) + } > - - ) - } - > - - - } - /> - - {avatarDecorationUrl && ( - - )} - - - - {/* Avatar action icons - shown on hover */} - {hoveredArea === 'avatar' && ( + + } + /> + + {avatarDecorationUrl && ( + + )} + + + + {/* Avatar action icons - shown on hover */} + {hoveredArea === 'avatar' && ( + + + + + {avatarUrl && ( { + e.preventDefault(); + e.stopPropagation(); + handleRemoveAvatar(); + }} style={{ - background: 'none', - border: 'none', + backgroundColor: color.Critical.Main, + borderRadius: toRem(8), padding: toRem(4), - cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', - borderRadius: toRem(8), + border: 'none', + cursor: 'pointer', + }} + > + + + )} + + )} + + + + {/* Profile Info Section */} + + {/* Display Name */} + + {isEditingName ? ( + setEditedName(e.target.value)} + onKeyDown={handleNameKeyDown} + onBlur={handleNameSave} + variant="Background" + size="400" + disabled={savingName} + style={{ + width: '100%', + fontSize: 'var(--token.font-size.H400)', + fontWeight: 'var(--token.font-weight.H400)', + padding: `${toRem(4)} ${toRem(8)}`, + textAlign: 'center', + }} + /> + ) : ( + { + setEditedName(profile.displayName || getMxIdLocalPart(userId) || userId); + setIsEditingName(true); + }} + onMouseEnter={() => setHoveredArea('name')} + onMouseLeave={() => setHoveredArea(null)} + style={{ + width: '100%', + border: 'none', + background: 'none', + cursor: 'pointer', + padding: `${toRem(4)} ${toRem(8)}`, + position: 'relative', + display: 'flex', + justifyContent: 'center', + alignItems: 'center', + lineHeight: 1.2, + }} + > + + {profile.displayName || getMxIdLocalPart(userId) || userId} + + {hoveredArea === 'name' && ( + - {avatarUrl && ( + )} + + )} + + + {/* Username */} + + {userId} + + + {/* Status Pill - Editable */} + setHoveredArea('status')} + onMouseLeave={() => setHoveredArea(null)} + style={{ + backgroundColor: color.Surface.Container, + border: `${toRem(1)} solid ${color.Surface.ContainerLine}`, + padding: `${toRem(6)} ${toRem(10)}`, + borderRadius: toRem(16), + maxWidth: toRem(250), + cursor: 'pointer', + }} + > + {isEditingStatus ? ( + ) => setEditedStatus(e.target.value)} + onKeyDown={handleStatusKeyDown} + onBlur={handleStatusSave} + disabled={savingStatus} + placeholder="Set a custom status..." + /> + ) : ( + + { + setEditedStatus(presence?.status || ''); + setIsEditingStatus(true); + }} + style={{ + background: 'none', + border: 'none', + padding: 0, + cursor: 'pointer', + display: 'flex', + alignItems: 'center', + }} + > + + {presence?.status || 'Click to set a custom status...'} + + + {presence?.status && hoveredArea === 'status' && ( + <> + { e.preventDefault(); e.stopPropagation(); - handleRemoveAvatar(); + handleRemoveStatus(); }} style={{ backgroundColor: color.Critical.Main, borderRadius: toRem(8), - padding: toRem(4), + padding: toRem(2), display: 'flex', alignItems: 'center', justifyContent: 'center', - border: 'none', cursor: 'pointer', + border: 'none', }} > - )} - - )} - + + )} + + )} - {/* Profile Info Section */} - - {/* Display Name */} - - {isEditingName ? ( - setEditedName(e.target.value)} - onKeyDown={handleNameKeyDown} - onBlur={handleNameSave} - variant="Background" - size="400" - disabled={savingName} - style={{ - width: '100%', - fontSize: 'var(--token.font-size.H400)', - fontWeight: 'var(--token.font-weight.H400)', - padding: `${toRem(4)} ${toRem(8)}`, - textAlign: 'center', - }} - /> - ) : ( - { - setEditedName(profile.displayName || getMxIdLocalPart(userId) || userId); - setIsEditingName(true); - }} - onMouseEnter={() => setHoveredArea('name')} - onMouseLeave={() => setHoveredArea(null)} - style={{ - width: '100%', - border: 'none', - background: 'none', - cursor: 'pointer', - padding: `${toRem(4)} ${toRem(8)}`, - position: 'relative', - display: 'flex', - justifyContent: 'center', - alignItems: 'center', - lineHeight: 1.2, - }} - > - - {profile.displayName || getMxIdLocalPart(userId) || userId} - - {hoveredArea === 'name' && ( - - - - )} - - )} - - - {/* Username */} - - {userId} - - - {/* Status Pill - Editable */} + {/* Chips Row - Placeholder chips */} + setHoveredArea('status')} - onMouseLeave={() => setHoveredArea(null)} style={{ backgroundColor: color.Surface.Container, border: `${toRem(1)} solid ${color.Surface.ContainerLine}`, - padding: `${toRem(6)} ${toRem(10)}`, + padding: `${toRem(4)} ${toRem(8)}`, borderRadius: toRem(16), - maxWidth: toRem(250), - cursor: 'pointer', }} > - {isEditingStatus ? ( - ) => - setEditedStatus(e.target.value) - } - onKeyDown={handleStatusKeyDown} - onBlur={handleStatusSave} - disabled={savingStatus} - placeholder="Set a custom status..." - /> - ) : ( - - { - setEditedStatus(presence?.status || ''); - setIsEditingStatus(true); - }} - style={{ - background: 'none', - border: 'none', - padding: 0, - cursor: 'pointer', - display: 'flex', - alignItems: 'center', - }} - > - - {presence?.status || 'Click to set a custom status...'} - - {presence?.status && hoveredArea === 'status' && ( - <> - - { - e.preventDefault(); - e.stopPropagation(); - handleRemoveStatus(); - }} - style={{ - backgroundColor: color.Critical.Main, - borderRadius: toRem(8), - padding: toRem(2), - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - cursor: 'pointer', - border: 'none', - }} - > - - - - )} - - )} + ruv.wtf - - {/* Chips Row - Placeholder chips */} - - - ruv.wtf - - - Share - - - Admin - + + Share + + + Admin + {/* MSC4522 username colors */} Username colors - + On dark themes - Bright colors work best + + Bright colors work best + On light themes - Darker colors work best + + Darker colors work best + {colorError && ( - {colorError} + + {colorError} + )} @@ -1157,7 +1186,9 @@ function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject {verbError && ( - {verbError} + + {verbError} + )} @@ -1201,7 +1232,9 @@ function ProfileBanner({ avatarRef, nameRef }: { avatarRef: React.RefObject )} {error && ( - {error} + + {error} + )} ); @@ -1213,7 +1246,5 @@ export function Profile() { const avatarRef = useRef(null); const nameRef = useRef(null); - return ( - - ); + return ; } diff --git a/src/app/features/settings/account/ProfileEffectHeroPreview.tsx b/src/app/features/settings/account/ProfileEffectHeroPreview.tsx index d0a91597..2abcacb5 100644 --- a/src/app/features/settings/account/ProfileEffectHeroPreview.tsx +++ b/src/app/features/settings/account/ProfileEffectHeroPreview.tsx @@ -53,7 +53,12 @@ export function ProfileEffectHeroPreview({ ) : ( avatarUrl && ( - + ) )}
diff --git a/src/app/features/settings/audio/Audio.tsx b/src/app/features/settings/audio/Audio.tsx index 19a2ed38..28ca452e 100644 --- a/src/app/features/settings/audio/Audio.tsx +++ b/src/app/features/settings/audio/Audio.tsx @@ -1,8 +1,24 @@ /* eslint-disable no-console */ import React, { useCallback, useEffect, useRef, useState, MouseEventHandler } from 'react'; -import { Box, Button, color, config, Header, IconButton, Input, Menu, MenuItem, PopOut, RectCords, Scroll, Switch, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Button, + color, + config, + Header, + IconButton, + Input, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Switch, + Text, + toRem, +} from 'folds'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { SequenceCard } from '../../../components/sequence-card'; import { SettingTile } from '../../../components/setting-tile'; @@ -22,24 +38,28 @@ interface AudioDevice { export type ScreenShareResolution = '720p' | '1080p' | '1440p' | '4k' | 'source'; /** Screen share resolution configs */ -export const SCREEN_SHARE_RESOLUTIONS: Record = { +export const SCREEN_SHARE_RESOLUTIONS: Record< + ScreenShareResolution, + { width: number; height: number; label: string } +> = { '720p': { width: 1280, height: 720, label: '720p (HD)' }, '1080p': { width: 1920, height: 1080, label: '1080p (Full HD)' }, '1440p': { width: 2560, height: 1440, label: '1440p (2K)' }, '4k': { width: 3840, height: 2160, label: '4K (Ultra HD)' }, - 'source': { width: 0, height: 0, label: 'Source Resolution' }, + source: { width: 0, height: 0, label: 'Source Resolution' }, }; /** Screen share bitrate presets in kbps */ export type ScreenShareBitrate = 'low' | 'medium' | 'high' | 'ultra'; /** Screen share bitrate configs */ -export const SCREEN_SHARE_BITRATES: Record = { - 'low': { bitrate: 1000, label: 'Low (1 Mbps)' }, - 'medium': { bitrate: 2500, label: 'Medium (2.5 Mbps)' }, - 'high': { bitrate: 5000, label: 'High (5 Mbps)' }, - 'ultra': { bitrate: 10000, label: 'Ultra (10 Mbps)' }, -}; +export const SCREEN_SHARE_BITRATES: Record = + { + low: { bitrate: 1000, label: 'Low (1 Mbps)' }, + medium: { bitrate: 2500, label: 'Medium (2.5 Mbps)' }, + high: { bitrate: 5000, label: 'High (5 Mbps)' }, + ultra: { bitrate: 10000, label: 'Ultra (10 Mbps)' }, + }; /** Stored audio device settings */ interface AudioSettings { @@ -235,11 +255,7 @@ function DeviceSelectButton({ devices, selectedId, onSelect }: DeviceSelectButto escapeDeactivates: stopPropagation, }} > - + } /> @@ -471,10 +487,14 @@ export function Audio({ requestClose }: AudioProps) { const [microphones, setMicrophones] = useState([]); const [speakers, setSpeakers] = useState([]); const [settings, setSettings] = useState(loadAudioSettings); - const [permissionStatus, setPermissionStatus] = useState<'granted' | 'denied' | 'prompt'>('prompt'); + const [permissionStatus, setPermissionStatus] = useState<'granted' | 'denied' | 'prompt'>( + 'prompt', + ); const [micTestState, setMicTestState] = useState<'idle' | 'testing' | 'done' | 'error'>('idle'); const [micLevel, setMicLevel] = useState(0); - const [speakerTestState, setSpeakerTestState] = useState<'idle' | 'testing' | 'done' | 'error'>('idle'); + const [speakerTestState, setSpeakerTestState] = useState<'idle' | 'testing' | 'done' | 'error'>( + 'idle', + ); const [micMonitoring, setMicMonitoring] = useState(false); const micAnimFrameRef = useRef(null); const micMonitorContextRef = useRef(null); @@ -490,7 +510,7 @@ export function Audio({ requestClose }: AudioProps) { setPermissionStatus('granted'); const devices = await navigator.mediaDevices.enumerateDevices(); - + const mics = devices .filter((d) => d.kind === 'audioinput') .map((d) => ({ @@ -498,7 +518,7 @@ export function Audio({ requestClose }: AudioProps) { label: d.label, kind: d.kind, })); - + const spks = devices .filter((d) => d.kind === 'audiooutput') .map((d) => ({ @@ -682,10 +702,10 @@ export function Audio({ requestClose }: AudioProps) { const dataArray = new Uint8Array(analyser.frequencyBinCount); const microphone = audioContext.createMediaStreamSource(stream); const gainNode = audioContext.createGain(); - + // Connect microphone to analyser for level monitoring microphone.connect(analyser); - + // Connect microphone to speakers for playback microphone.connect(gainNode); gainNode.connect(audioContext.destination); @@ -708,11 +728,17 @@ export function Audio({ requestClose }: AudioProps) { console.error('Microphone monitoring failed:', e); } } - }, [micMonitoring, settings.microphoneId, settings.noiseSuppression, settings.echoCancellation, settings.autoGainControl]); + }, [ + micMonitoring, + settings.microphoneId, + settings.noiseSuppression, + settings.echoCancellation, + settings.autoGainControl, + ]); // Cleanup monitoring on unmount - useEffect(() => { - return () => { + useEffect( + () => () => { if (micAnimFrameRef.current !== null) { cancelAnimationFrame(micAnimFrameRef.current); } @@ -722,8 +748,9 @@ export function Audio({ requestClose }: AudioProps) { if (micMonitorContextRef.current) { micMonitorContextRef.current.close(); } - }; - }, []); + }, + [], + ); // Apply processing toggles to the live monitor track without tearing it down. useEffect(() => { @@ -807,14 +834,26 @@ export function Audio({ requestClose }: AudioProps) { {(micTestState === 'testing' || micMonitoring) && ( - - + + )} @@ -864,14 +916,26 @@ export function Audio({ requestClose }: AudioProps) { /> @@ -992,10 +1056,12 @@ export function Audio({ requestClose }: AudioProps) { - • If you don't see your devices, make sure they are connected and permissions are granted. + • If you don't see your devices, make sure they are connected and + permissions are granted. - • The "Test" button will help verify your devices are working correctly. + • The "Test" button will help verify your devices are working + correctly. • Changes are saved automatically and will apply to your next call. diff --git a/src/app/features/settings/developer-tools/AccountData.tsx b/src/app/features/settings/developer-tools/AccountData.tsx index 31fbab80..911a3778 100644 --- a/src/app/features/settings/developer-tools/AccountData.tsx +++ b/src/app/features/settings/developer-tools/AccountData.tsx @@ -16,14 +16,14 @@ type AccountDataProps = { export function AccountData({ expand, onExpandToggle, onSelect }: AccountDataProps) { const mx = useMatrixClient(); const [accountDataTypes, setAccountDataKeys] = useState(() => - Array.from(mx.store.accountData.keys()) + Array.from(mx.store.accountData.keys()), ); useAccountDataCallback( mx, useCallback(() => { setAccountDataKeys(Array.from(mx.store.accountData.keys())); - }, [mx]) + }, [mx]), ); return ( diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx index e4440dcb..1f2c0a38 100644 --- a/src/app/features/settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/settings/developer-tools/DevelopTools.tsx @@ -1,5 +1,16 @@ import React, { useCallback, useState } from 'react'; -import { Box, Text, IconButton, Scroll, Switch, Button, Modal, Overlay, OverlayBackdrop, OverlayCenter } from 'folds'; +import { + Box, + Text, + IconButton, + Scroll, + Switch, + Button, + Modal, + Overlay, + OverlayBackdrop, + OverlayCenter, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; @@ -36,23 +47,26 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { const profileEditable = profileSupported && profileUserId.trim() === mx.getUserId(); - const fetchProfileFields = useCallback(async (userId: string) => { - if (!userId) return; + const fetchProfileFields = useCallback( + async (userId: string) => { + if (!userId) return; - try { - const supported = await mx.doesServerSupportExtendedProfiles(); - setProfileSupported(supported); - setProfileFields( - supported - ? await mx.getExtendedProfile(userId) - : ((await mx.getProfileInfo(userId)) as Record), - ); - } catch (err) { - console.error('Failed to fetch profile fields:', err); - setProfileSupported(false); - setProfileFields({}); - } - }, [mx]); + try { + const supported = await mx.doesServerSupportExtendedProfiles(); + setProfileSupported(supported); + setProfileFields( + supported + ? await mx.getExtendedProfile(userId) + : ((await mx.getProfileInfo(userId)) as Record), + ); + } catch (err) { + console.error('Failed to fetch profile fields:', err); + setProfileSupported(false); + setProfileFields({}); + } + }, + [mx], + ); const submitProfileField: AccountDataSubmitCallback = useCallback( async (key, content) => { @@ -61,7 +75,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { // The rest of the client reads through the shared profile cache clearProfileCache(profileUserId.trim()); }, - [mx, profileUserId] + [mx, profileUserId], ); const deleteProfileField = useCallback( @@ -79,7 +93,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { console.error('Failed to delete profile field:', err); } }, - [mx, profileUserId] + [mx, profileUserId], ); const handleProfileExpand = useCallback( @@ -87,14 +101,14 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { setProfileExpand(expand); if (expand) fetchProfileFields(profileUserId.trim()); }, - [fetchProfileFields, profileUserId] + [fetchProfileFields, profileUserId], ); const submitAccountData: AccountDataSubmitCallback = useCallback( async (type, content) => { await mx.setAccountData(type, content); }, - [mx] + [mx], ); if (accountDataType !== undefined) { diff --git a/src/app/features/settings/developer-tools/ProfileFields.tsx b/src/app/features/settings/developer-tools/ProfileFields.tsx index 22ebb826..70c997b7 100644 --- a/src/app/features/settings/developer-tools/ProfileFields.tsx +++ b/src/app/features/settings/developer-tools/ProfileFields.tsx @@ -69,37 +69,39 @@ export function ProfileFields({ Total: {Object.keys(fields).length} - {Object.keys(fields).sort().map((key) => ( - - {editable && ( - onDelete(key)} - > - - - )} - + {Object.keys(fields) + .sort() + .map((key) => ( + + {editable && ( + onDelete(key)} + > + + + )} + + + } + onClick={() => onSelect(key)} + > + + + {key} + - } - onClick={() => onSelect(key)} - > - - - {key} - - - - ))} + + ))}
)} diff --git a/src/app/features/settings/devices/DeviceTile.tsx b/src/app/features/settings/devices/DeviceTile.tsx index 078eea69..bbc6e884 100644 --- a/src/app/features/settings/devices/DeviceTile.tsx +++ b/src/app/features/settings/devices/DeviceTile.tsx @@ -1,9 +1,22 @@ import React, { FormEventHandler, ReactNode, useCallback, useEffect, useState } from 'react'; -import { Box, Text, IconButton, Chip, Input, Button, color, Spinner, toRem, Overlay, OverlayBackdrop, OverlayCenter } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + IconButton, + Chip, + Input, + Button, + color, + Spinner, + toRem, + Overlay, + OverlayBackdrop, + OverlayCenter, +} from 'folds'; import { CryptoApi } from 'matrix-js-sdk/lib/crypto-api'; import FocusTrap from 'focus-trap-react'; import { IMyDevice, MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { SettingTile } from '../../../components/setting-tile'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { timeDayMonYear, timeHourMinute, today, yesterday } from '../../../utils/time'; @@ -72,7 +85,7 @@ export function DeviceKeyDetails({ crypto }: DeviceKeyDetailsProps) { useCallback(() => { const keys = crypto.getOwnDeviceKeys(); return keys; - }, [crypto]) + }, [crypto]), ); useEffect(() => { @@ -104,8 +117,8 @@ function DeviceRename({ device, onCancel, onRename, refreshDeviceList }: DeviceR await mx.setDeviceDetails(device.device_id, { display_name: name }); await refreshDeviceList(); }, - [mx, device.device_id, refreshDeviceList] - ) + [mx, device.device_id, refreshDeviceList], + ), ); const renaming = renameState.status === AsyncStatus.Loading; diff --git a/src/app/features/settings/devices/Devices.tsx b/src/app/features/settings/devices/Devices.tsx index 2a42d83c..e79f6e09 100644 --- a/src/app/features/settings/devices/Devices.tsx +++ b/src/app/features/settings/devices/Devices.tsx @@ -50,19 +50,19 @@ export function Devices({ requestClose }: DevicesProps) { const verificationStatus = useDeviceVerificationStatus( crypto, mx.getSafeUserId(), - currentDevice?.device_id + currentDevice?.device_id, ); const otherDevicesId = useDeviceIds(otherDevices); const unverifiedDeviceCount = useUnverifiedDeviceCount( crypto, mx.getSafeUserId(), - otherDevicesId + otherDevicesId, ); const defaultSecretStorageKeyId = useSecretStorageDefaultKeyId(); const defaultSecretStorageKeyContent = useSecretStorageKeyContent( - defaultSecretStorageKeyId ?? '' + defaultSecretStorageKeyId ?? '', ); return ( diff --git a/src/app/features/settings/devices/LocalBackup.tsx b/src/app/features/settings/devices/LocalBackup.tsx index a446938c..d151240c 100644 --- a/src/app/features/settings/devices/LocalBackup.tsx +++ b/src/app/features/settings/devices/LocalBackup.tsx @@ -1,7 +1,7 @@ import React, { FormEventHandler, useCallback, useEffect, useState } from 'react'; import { Box, Button, color, Spinner, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import FileSaver from 'file-saver'; +import { Icon, Icons } from '../../../components/icons'; import { SequenceCard } from '../../../components/sequence-card'; import { SettingTile } from '../../../components/setting-tile'; import { SequenceCardStyle } from '../styles.css'; @@ -31,8 +31,8 @@ function ExportKeys() { }); FileSaver.saveAs(blob, 'paarrot-keys.txt'); }, - [mx] - ) + [mx], + ), ); const exporting = exportState.status === AsyncStatus.Loading; @@ -175,8 +175,8 @@ function ImportKeys({ file, onDone }: ImportKeysProps) { await crypto.importRoomKeysAsJson(keys); }, - [file, mx] - ) + [file, mx], + ), ); const decrypting = decryptState.status === AsyncStatus.Loading; diff --git a/src/app/features/settings/devices/OtherDevices.tsx b/src/app/features/settings/devices/OtherDevices.tsx index fba73564..4f7e73af 100644 --- a/src/app/features/settings/devices/OtherDevices.tsx +++ b/src/app/features/settings/devices/OtherDevices.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useState } from 'react'; -import { openExternalUrl } from '../../../utils/tauri'; import { Box, Button, config, Menu, Spinner, Text } from 'folds'; import { AuthDict, IMyDevice, MatrixError } from 'matrix-js-sdk'; +import { openExternalUrl } from '../../../utils/tauri'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../styles.css'; import { ActionUIA, ActionUIAFlowsLoader } from '../../../components/ActionUIA'; @@ -37,7 +37,7 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O openExternalUrl( withSearchParam(authUrl, { action: accountManagementActions.sessionsList, - }) + }), ); }, [authMetadata, accountManagementActions]); @@ -50,10 +50,10 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O withSearchParam(authUrl, { action: accountManagementActions.sessionEnd, device_id: deviceId, - }) + }), ); }, - [authMetadata, accountManagementActions] + [authMetadata, accountManagementActions], ); const handleToggleDelete = useCallback((deviceId: string) => { @@ -77,7 +77,7 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O async (authDict?: AuthDict) => { await mx.deleteMultipleDevices(Array.from(deleted), authDict); }, - [mx, deleted] + [mx, deleted], ), useCallback( (state: typeof deleteState) => { @@ -87,11 +87,11 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O } setDeleteState(state); }, - [refreshDeviceList] - ) + [refreshDeviceList], + ), ); const [authData, deleteError] = useUIAMatrixError( - deleteState.status === AsyncStatus.Error ? deleteState.error : undefined + deleteState.status === AsyncStatus.Error ? deleteState.error : undefined, ); const deleting = deleteState.status === AsyncStatus.Loading || authData !== undefined; diff --git a/src/app/features/settings/devices/Verification.tsx b/src/app/features/settings/devices/Verification.tsx index 9581177d..d2d9628f 100644 --- a/src/app/features/settings/devices/Verification.tsx +++ b/src/app/features/settings/devices/Verification.tsx @@ -1,8 +1,24 @@ import React, { MouseEventHandler, useCallback, useState } from 'react'; -import { Badge, Box, Button, Chip, config, Spinner, Text, Overlay, OverlayBackdrop, OverlayCenter, IconButton, RectCords, PopOut, Menu, MenuItem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Badge, + Box, + Button, + Chip, + config, + Spinner, + Text, + Overlay, + OverlayBackdrop, + OverlayCenter, + IconButton, + RectCords, + PopOut, + Menu, + MenuItem, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { CryptoApi, VerificationRequest } from 'matrix-js-sdk/lib/crypto-api'; +import { Icon, Icons } from '../../../components/icons'; import { VerificationStatus } from '../../../hooks/useDeviceVerificationStatus'; import { InfoCard } from '../../../components/info-card'; import { ManualVerificationTile } from '../../../components/ManualVerification'; @@ -161,7 +177,7 @@ export function VerifyOtherDeviceTile({ crypto, deviceId }: VerifyOtherDeviceTil const requestPromise = crypto.requestDeviceVerification(mx.getSafeUserId(), deviceId); return requestPromise; }, [mx, crypto, deviceId]), - setRequestState + setRequestState, ); const handleExit = useCallback(() => { @@ -260,7 +276,7 @@ export function DeviceVerificationOptions() { openExternalUrl( withSearchParam(authUrl, { action: accountManagementActions.crossSigningReset, - }) + }), ); return; } diff --git a/src/app/features/settings/emojis-stickers/EmojisStickers.tsx b/src/app/features/settings/emojis-stickers/EmojisStickers.tsx index 96d4e7df..e2119502 100644 --- a/src/app/features/settings/emojis-stickers/EmojisStickers.tsx +++ b/src/app/features/settings/emojis-stickers/EmojisStickers.tsx @@ -17,7 +17,10 @@ type EmojisStickersProps = { }; export function EmojisStickers({ requestClose }: EmojisStickersProps) { const [imagePack, setImagePack] = useState(); - const [autoConvertEmoticons, setAutoConvertEmoticons] = useSetting(settingsAtom, 'autoConvertEmoticons'); + const [autoConvertEmoticons, setAutoConvertEmoticons] = useSetting( + settingsAtom, + 'autoConvertEmoticons', + ); const handleImagePackViewClose = () => { setImagePack(undefined); diff --git a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx index d7271305..192be8e7 100644 --- a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx +++ b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx @@ -1,9 +1,27 @@ import React, { MouseEventHandler, useCallback, useEffect, useMemo, useState } from 'react'; -import { Box, Text, Button, IconButton, Avatar, AvatarFallback, config, Spinner, Menu, RectCords, PopOut, Checkbox, toRem, Scroll, Header, Line, Chip } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Text, + Button, + IconButton, + Avatar, + AvatarFallback, + config, + Spinner, + Menu, + RectCords, + PopOut, + Checkbox, + toRem, + Scroll, + Header, + Line, + Chip, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { useAtomValue } from 'jotai'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { useGlobalImagePacks, useRoomsImagePacks } from '../../../hooks/useImagePacks'; import { SequenceCardStyle } from '../styles.css'; import { SequenceCard } from '../../../components/sequence-card'; @@ -76,7 +94,7 @@ function GlobalPackSelector({ const removeSelected = (adds: PackAddress[]) => { setSelected((addresses) => { const newAddresses = addresses.filter( - (addr) => !adds.find((address) => packAddressEqual(addr, address)) + (addr) => !adds.find((address) => packAddressEqual(addr, address)), ); return newAddresses; }); @@ -122,7 +140,7 @@ function GlobalPackSelector({ .map((pack) => pack.address) .filter((addr) => addr !== undefined); const allSelected = roomPackAddresses.every((addr) => - selected.find((address) => packAddressEqual(addr, address)) + selected.find((address) => packAddressEqual(addr, address)), ); return ( @@ -171,7 +189,10 @@ function GlobalPackSelector({ {avatarUrl ? ( - + ) : ( @@ -250,9 +271,9 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { const nonGlobalPacks = useMemo( () => roomsImagePack.filter( - (pack) => !globalPacks.find((p) => packAddressEqual(pack.address, p.address)) + (pack) => !globalPacks.find((p) => packAddressEqual(pack.address, p.address)), ), - [roomsImagePack, globalPacks] + [roomsImagePack, globalPacks], ); const [selectedPacks, setSelectedPacks] = useState([]); @@ -261,9 +282,9 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { const unselectedGlobalPacks = useMemo( () => nonGlobalPacks.filter( - (pack) => !selectedPacks.find((addr) => packAddressEqual(pack.address, addr)) + (pack) => !selectedPacks.find((addr) => packAddressEqual(pack.address, addr)), ), - [selectedPacks, nonGlobalPacks] + [selectedPacks, nonGlobalPacks], ); const handleRemove = (address: PackAddress) => { @@ -302,7 +323,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { }); await mx.setAccountData(AccountDataEvent.PoniesEmoteRooms, updatedContent); - }, [mx, selectedPacks, removedPacks]) + }, [mx, selectedPacks, removedPacks]), ); const resetChanges = useCallback(() => { diff --git a/src/app/features/settings/emojis-stickers/TelegramImport.tsx b/src/app/features/settings/emojis-stickers/TelegramImport.tsx index 5a0753f3..2b0a42bb 100644 --- a/src/app/features/settings/emojis-stickers/TelegramImport.tsx +++ b/src/app/features/settings/emojis-stickers/TelegramImport.tsx @@ -1,21 +1,10 @@ import React, { useState, useCallback } from 'react'; -import { - Box, - Text, - Button, - Input, - Spinner, - color, - toRem, -} from 'folds'; +import { Box, Text, Button, Input, Spinner, color, toRem } from 'folds'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../styles.css'; import { SettingTile } from '../../../components/setting-tile'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; -import { - extractPackName, - importTelegramStickerPack, -} from '../../../utils/telegramStickerImport'; +import { extractPackName, importTelegramStickerPack } from '../../../utils/telegramStickerImport'; import { getUserImagePack, ImagePack } from '../../../plugins/custom-emoji'; const TELEGRAM_BOT_TOKEN_KEY = 'cinny_telegram_bot_token'; @@ -29,8 +18,8 @@ type TelegramImportProps = { */ export function TelegramImport({ onViewPack }: TelegramImportProps) { const mx = useMatrixClient(); - const [botToken, setBotToken] = useState(() => - localStorage.getItem(TELEGRAM_BOT_TOKEN_KEY) || '' + const [botToken, setBotToken] = useState( + () => localStorage.getItem(TELEGRAM_BOT_TOKEN_KEY) || '', ); const [packUrl, setPackUrl] = useState(''); const [importing, setImporting] = useState(false); @@ -74,7 +63,7 @@ export function TelegramImport({ onViewPack }: TelegramImportProps) { packUrl.trim(), (current, total, status) => { setProgress(status); - } + }, ); const count = Object.keys(result.content.images || {}).length; @@ -145,7 +134,9 @@ export function TelegramImport({ onViewPack }: TelegramImportProps) { {importing && progress && ( - {progress} + + {progress} + )} diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 51077926..dd07ebe2 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -7,17 +7,42 @@ import React, { useState, } from 'react'; import dayjs from 'dayjs'; -import { as, Box, Button, Chip, color, config, Header, IconButton, Input, Menu, MenuItem, PopOut, RectCords, Scroll, Switch, Text, toRem } from 'folds'; +import { + as, + Box, + Button, + Chip, + color, + config, + Header, + IconButton, + Input, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Switch, + Text, + toRem, +} from 'folds'; import { useSetAtom } from 'jotai'; import { Range } from 'react-range'; -import { Icon, Icons } from '../../../components/icons'; import { HexColorPicker } from 'react-colorful'; import { isKeyHotkey } from 'is-hotkey'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { SequenceCard } from '../../../components/sequence-card'; import { useSetting } from '../../../state/hooks/settings'; -import { DateFormat, EmojiStyle, MessageLayout, MessageSpacing, ScrollToLatestBehavior, settingsAtom } from '../../../state/settings'; +import { + DateFormat, + EmojiStyle, + MessageLayout, + MessageSpacing, + ScrollToLatestBehavior, + settingsAtom, +} from '../../../state/settings'; import { SettingTile } from '../../../components/setting-tile'; import { KeySymbol } from '../../../utils/key-symbol'; import { isMacOS } from '../../../utils/user-agent'; @@ -51,18 +76,14 @@ const ThemeSelector = as<'div', ThemeSelectorProps>( () => () => { setPreviewId(undefined); }, - [setPreviewId] + [setPreviewId], ); const clearPreview = () => setPreviewId(undefined); const previewTheme = (theme: Theme) => setPreviewId(theme.id); return ( - + {themes.map((theme) => ( ( ); - } + }, ); function SelectTheme({ disabled }: { disabled?: boolean }) { @@ -338,7 +359,7 @@ const emojiStyleNames: Record = { function SidebarNameplate() { const [sidebarNameplateOpacity, setSidebarNameplateOpacity] = useSetting( settingsAtom, - 'sidebarNameplateOpacity' + 'sidebarNameplateOpacity', ); return ( @@ -416,7 +437,7 @@ const EmojiStyleSelector = as<'div', EmojiStyleSelectorProps>( ))} - ) + ), ); function Appearance() { @@ -907,7 +928,7 @@ function Editor() { function Spaces() { const [autoJoinSpaceRooms, setAutoJoinSpaceRooms] = useSetting( settingsAtom, - 'autoJoinSpaceRooms' + 'autoJoinSpaceRooms', ); return ( @@ -918,11 +939,7 @@ function Spaces() { title="Auto-Join Space Rooms" description="Automatically join all accessible rooms when joining a space, with notifications set to Mentions & Keywords." after={ - + } /> @@ -1072,7 +1089,7 @@ function SelectScrollToLatestBehavior() { const [menuCords, setMenuCords] = useState(); const [scrollToLatestBehavior, setScrollToLatestBehavior] = useSetting( settingsAtom, - 'scrollToLatestBehavior' + 'scrollToLatestBehavior', ); const behaviors = [ @@ -1148,15 +1165,15 @@ function SelectScrollToLatestBehavior() { function Messages() { const [legacyUsernameColor, setLegacyUsernameColor] = useSetting( settingsAtom, - 'legacyUsernameColor' + 'legacyUsernameColor', ); const [hideMembershipEvents, setHideMembershipEvents] = useSetting( settingsAtom, - 'hideMembershipEvents' + 'hideMembershipEvents', ); const [hideNickAvatarEvents, setHideNickAvatarEvents] = useSetting( settingsAtom, - 'hideNickAvatarEvents' + 'hideNickAvatarEvents', ); const [mediaAutoLoad, setMediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); const [urlPreview, setUrlPreview] = useSetting(settingsAtom, 'urlPreview'); @@ -1227,18 +1244,53 @@ function Messages() { /> - } - /> - - - For ad-free YouTube streaming, install yt-dlp (required for direct playback): - - - winget install yt-dlp - + } + /> + + + For ad-free YouTube streaming, install yt-dlp (required for direct playback): + + + winget install yt-dlp + { const conditions: PushRuleCondition[] = []; if (oneToOne) @@ -66,7 +66,7 @@ function AllMessagesModeSwitcher({ const actions = getModeActions(mode); await mx.setPushRuleActions('global', kind, ruleId, actions); }, - [mx, getModeActions, kind, ruleId] + [mx, getModeActions, kind, ruleId], ); return ; @@ -76,7 +76,7 @@ export function AllMessagesNotifications() { const pushRulesEvt = useAccountData(AccountDataEvent.PushRules); const pushRules = useMemo( () => pushRulesEvt?.getContent() ?? { global: {} }, - [pushRulesEvt] + [pushRulesEvt], ); return ( diff --git a/src/app/features/settings/notifications/KeywordMessages.tsx b/src/app/features/settings/notifications/KeywordMessages.tsx index 32cea868..2f126744 100644 --- a/src/app/features/settings/notifications/KeywordMessages.tsx +++ b/src/app/features/settings/notifications/KeywordMessages.tsx @@ -34,8 +34,8 @@ function KeywordInput() { }); setKeyword(''); }, - [mx] - ) + [mx], + ), ); const addingKeyword = keywordState.status === AsyncStatus.Loading; @@ -113,8 +113,8 @@ function KeywordCross({ pushRule }: PushRulesProps) { const [removeState, remove] = useAsyncCallback( useCallback( () => mx.deletePushRule('global', PushRuleKind.ContentSpecific, pushRule.rule_id), - [mx, pushRule] - ) + [mx, pushRule], + ), ); const removing = removeState.status === AsyncStatus.Loading; @@ -137,10 +137,10 @@ function KeywordModeSwitcher({ pushRule }: PushRulesProps) { 'global', PushRuleKind.ContentSpecific, pushRule.rule_id, - actions + actions, ); }, - [mx, getModeActions, pushRule] + [mx, getModeActions, pushRule], ); return ; @@ -150,13 +150,13 @@ export function KeywordMessagesNotifications() { const pushRulesEvt = useAccountData(AccountDataEvent.PushRules); const pushRules = useMemo( () => pushRulesEvt?.getContent() ?? { global: {} }, - [pushRulesEvt] + [pushRulesEvt], ); const keywordPushRules = useMemo(() => { const content = pushRules.global.content ?? []; return content.filter( - (pushRule) => pushRule.default === false && typeof pushRule.pattern === 'string' + (pushRule) => pushRule.default === false && typeof pushRule.pattern === 'string', ); }, [pushRules]); diff --git a/src/app/features/settings/notifications/NotificationModeSwitcher.tsx b/src/app/features/settings/notifications/NotificationModeSwitcher.tsx index 8bc93137..a2f073c7 100644 --- a/src/app/features/settings/notifications/NotificationModeSwitcher.tsx +++ b/src/app/features/settings/notifications/NotificationModeSwitcher.tsx @@ -1,8 +1,8 @@ import { Box, Button, config, Menu, MenuItem, PopOut, RectCords, Spinner, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { IPushRule } from 'matrix-js-sdk'; import React, { MouseEventHandler, useMemo, useState } from 'react'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { NotificationMode, useNotificationActionsMode } from '../../../hooks/useNotificationMode'; import { stopPropagation } from '../../../utils/keyboard'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; @@ -17,7 +17,7 @@ const useNotificationModeStr = (): Record => [NotificationMode.Notify]: 'Notify Silent', [NotificationMode.NotifyLoud]: 'Notify Loud', }), - [] + [], ); type NotificationModeSwitcherProps = { diff --git a/src/app/features/settings/notifications/Notifications.tsx b/src/app/features/settings/notifications/Notifications.tsx index 97a5d858..f6396cb9 100644 --- a/src/app/features/settings/notifications/Notifications.tsx +++ b/src/app/features/settings/notifications/Notifications.tsx @@ -46,9 +46,7 @@ export function Notifications({ requestClose }: NotificationsProps) { direction="Column" gap="400" > - Block Users" section.'} - /> + diff --git a/src/app/features/settings/notifications/SpecialMessages.tsx b/src/app/features/settings/notifications/SpecialMessages.tsx index cbebf648..275c71b7 100644 --- a/src/app/features/settings/notifications/SpecialMessages.tsx +++ b/src/app/features/settings/notifications/SpecialMessages.tsx @@ -32,7 +32,7 @@ const getDefaultIsUserMention = (userId: string): PushRuleData => key: 'content.m\\.mentions.user_ids', value: userId, }, - ] + ], ); const DefaultContainsDisplayName = makePushRuleData( @@ -43,7 +43,7 @@ const DefaultContainsDisplayName = makePushRuleData( { kind: ConditionKind.ContainsDisplayName, }, - ] + ], ); const getDefaultContainsUsername = (username: string) => @@ -52,7 +52,7 @@ const getDefaultContainsUsername = (username: string) => RuleId.ContainsUserName, getNotificationModeActions(NotificationMode.NotifyLoud, { highlight: true }), undefined, - username + username, ); const DefaultIsRoomMention = makePushRuleData( @@ -69,7 +69,7 @@ const DefaultIsRoomMention = makePushRuleData( kind: ConditionKind.SenderNotificationPermission, key: 'room', }, - ] + ], ); const DefaultAtRoomNotification = makePushRuleData( @@ -86,7 +86,7 @@ const DefaultAtRoomNotification = makePushRuleData( kind: ConditionKind.SenderNotificationPermission, key: 'room', }, - ] + ], ); type PushRulesProps = { @@ -105,7 +105,7 @@ function MentionModeSwitcher({ ruleId, pushRules, defaultPushRuleData }: PushRul const actions = getModeActions(mode); await mx.setPushRuleActions('global', kind, ruleId, actions); }, - [mx, getModeActions, kind, ruleId] + [mx, getModeActions, kind, ruleId], ); return ; @@ -118,7 +118,7 @@ export function SpecialMessagesNotifications() { const pushRulesEvt = useAccountData(AccountDataEvent.PushRules); const pushRules = useMemo( () => pushRulesEvt?.getContent() ?? { global: {} }, - [pushRulesEvt] + [pushRulesEvt], ); return ( diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index ad1aa781..8413186c 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -46,8 +46,8 @@ function EmailNotification() { kind: null, } as unknown as IPusherRequest); }, - [mx] - ) + [mx], + ), ); const handleChange = (value: boolean) => { @@ -97,7 +97,7 @@ export function SystemNotification() { const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications'); const [isNotificationSounds, setIsNotificationSounds] = useSetting( settingsAtom, - 'isNotificationSounds' + 'isNotificationSounds', ); const requestNotificationPermission = async () => { @@ -199,7 +199,7 @@ function AndroidPushNotifications() { lastFailure: s.lastFailure || '', autoStartBlocked: Boolean(s.autoStartBlocked), } - : undefined + : undefined, ); setLoading(false); }, []); @@ -215,16 +215,16 @@ function AndroidPushNotifications() { await refresh(); if (!result.success) { setLastError( - 'Selected distributor but did not get a push endpoint. In ntfy: enable UnifiedPush, allow unrestricted battery, then try Reset again.' + 'Selected distributor but did not get a push endpoint. In ntfy: enable UnifiedPush, allow unrestricted battery, then try Reset again.', ); } - }, [refresh]) + }, [refresh]), ); const [pingState, ping] = useAsyncCallback( useCallback(async () => { await triggerBackgroundSyncPing('manual-test'); - }, []) + }, []), ); const isBusy = @@ -251,7 +251,8 @@ function AndroidPushNotifications() { if (status.lastFailure === 'AUTO_START_BLOCKED' || status.autoStartBlocked) { return ( - Phone is blocking auto-start for Paarrot. Open App Boot / Auto-start settings, allow Paarrot (and ntfy), then tap Reset. + Phone is blocking auto-start for Paarrot. Open App Boot / Auto-start settings, allow + Paarrot (and ntfy), then tap Reset. ); } @@ -265,7 +266,8 @@ function AndroidPushNotifications() { if (status.distributors.length === 0) { return ( - No UnifiedPush distributor found. Install ntfy from Play Store/F-Droid and enable UnifiedPush in ntfy settings. + No UnifiedPush distributor found. Install ntfy from Play Store/F-Droid and enable + UnifiedPush in ntfy settings. ); } @@ -291,7 +293,11 @@ function AndroidPushNotifications() { <> {statusDescription} {lastError ? ( - + {lastError} ) : null} diff --git a/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md b/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md index 5bc983a8..82b3f4ca 100644 --- a/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md +++ b/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md @@ -3,10 +3,12 @@ ## Plugin Structure Each plugin must be a directory containing at least: + - `index.js` - Main entry point - `plugin-metadata.json` - Plugin metadata ### Example Directory Structure + ``` my-plugin/ ├── index.js @@ -38,22 +40,22 @@ Your `index.js` must export a default plugin object with an `onLoad` function: ```javascript // index.js module.exports = { - name: "My Plugin", - version: "1.0.0", + name: 'My Plugin', + version: '1.0.0', dependencies: { - "paarrot.utils": "^1.0.0" // Optional: depend on other plugins + 'paarrot.utils': '^1.0.0', // Optional: depend on other plugins }, - + /** * Called when the plugin is loaded * @param {PluginContext} ctx - The plugin context */ onLoad: async (ctx) => { ctx.log('Plugin loaded!'); - + // Your plugin code here }, - + /** * Called when the plugin is unloaded (optional) */ @@ -61,13 +63,15 @@ module.exports = { ctx.log('Plugin unloaded!'); // Cleanup resources here }, - + /** * Exports for other plugins to use (optional) */ exports: { - myFunction: () => { /* ... */ } - } + myFunction: () => { + /* ... */ + }, + }, }; ``` @@ -82,32 +86,32 @@ Register slash commands with argument parsing: ```javascript // Simple command ctx.commands.register({ - name: "shrug", - run: () => "¯\\_(ツ)_/¯" + name: 'shrug', + run: () => '¯\\_(ツ)_/¯', }); // Command with args ctx.commands.register({ - name: "echo", - args: ["text"], - run: ({ text }) => text + name: 'echo', + args: ['text'], + run: ({ text }) => text, }); // Advanced command ctx.commands.register({ - name: "greet", - description: "Greet someone", - args: ["name", "greeting"], + name: 'greet', + description: 'Greet someone', + args: ['name', 'greeting'], run: ({ name, greeting }) => { return `${greeting || 'Hello'}, ${name || 'stranger'}!`; - } + }, }); // Execute commands programmatically -ctx.commands.execute("shrug", {}); +ctx.commands.execute('shrug', {}); // Unregister a command -ctx.commands.unregister("mycommand"); +ctx.commands.unregister('mycommand'); ``` ### 💬 Messages API @@ -117,26 +121,27 @@ Intercept and modify messages: ```javascript // Before send interceptor ctx.messages.onBeforeSend((msg) => { - if (msg.content === "brb") { - msg.content = "be right back!"; + if (msg.content === 'brb') { + msg.content = 'be right back!'; } - + // Add prefix msg.content = `[Bot] ${msg.content}`; - + // Access metadata msg.metadata = { processed: true }; }); // Receive interceptor ctx.messages.onReceive((msg) => { - if (msg.content.includes("@bot")) { + if (msg.content.includes('@bot')) { ctx.log('Bot was mentioned!'); } }); ``` MessageContext interface: + ```typescript interface MessageContext { content: string; @@ -162,8 +167,8 @@ ctx.ui.registerRenderer('message', (msg, defaultRenderer) => { Register custom renderers: ```javascript -ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { - if (msg.type === "image") { +ctx.ui.registerRenderer('message', (msg, defaultRenderer) => { + if (msg.type === 'image') { return ``; } // Fall back to default @@ -171,7 +176,7 @@ ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { }); // Unregister renderer -ctx.ui.unregisterRenderer("message"); +ctx.ui.unregisterRenderer('message'); ``` ### ⚙️ Settings API @@ -181,36 +186,36 @@ Define plugin settings with UI: ```javascript ctx.settings.define({ theme: { - type: "select", - label: "Theme", - description: "Choose your theme", + type: 'select', + label: 'Theme', + description: 'Choose your theme', options: [ - { value: "dark", label: "Dark" }, - { value: "light", label: "Light" } + { value: 'dark', label: 'Dark' }, + { value: 'light', label: 'Light' }, ], - default: "dark" + default: 'dark', }, spamFilter: { - type: "boolean", - label: "Spam Filter", - description: "Enable spam filtering", - default: true + type: 'boolean', + label: 'Spam Filter', + description: 'Enable spam filtering', + default: true, }, prefix: { - type: "string", - label: "Command Prefix", - default: "!" + type: 'string', + label: 'Command Prefix', + default: '!', }, maxMessages: { - type: "number", - label: "Max Messages", - default: 100 + type: 'number', + label: 'Max Messages', + default: 100, }, accentColor: { - type: "color", - label: "Accent Color", - default: "#6366f1" - } + type: 'color', + label: 'Accent Color', + default: '#6366f1', + }, }); // Get/set settings @@ -223,22 +228,23 @@ ctx.settings.set('theme', 'light'); Listen to raw Matrix events: ```javascript -ctx.matrix.on("m.room.message", (event) => { +ctx.matrix.on('m.room.message', (event) => { const content = event.getContent(); ctx.log('Message received:', content.body); }); -ctx.matrix.on("Room.timeline", (event) => { +ctx.matrix.on('Room.timeline', (event) => { if (event.getType() === 'm.room.member') { ctx.log('Member event:', event.getSender()); } }); // Remove listener -ctx.matrix.off("m.room.message", handler); +ctx.matrix.off('m.room.message', handler); ``` Common events: + - `"m.room.message"` - Room messages - `"m.room.member"` - Membership changes - `"Room.timeline"` - Timeline events @@ -274,22 +280,22 @@ Show notifications to users: ```javascript // Simple notification -ctx.notify("Plugin loaded!"); +ctx.notify('Plugin loaded!'); // Advanced notification ctx.notify({ - title: "New Message", - body: "You have a new message from Steve", - type: "info", // info, success, error, warning + title: 'New Message', + body: 'You have a new message from Steve', + type: 'info', // info, success, error, warning duration: 5000, actions: [ { - label: "View", + label: 'View', action: () => { // Handle action - } - } - ] + }, + }, + ], }); ``` @@ -312,12 +318,12 @@ Use other plugins: ```javascript // Require another plugin's exports -const utils = ctx.require("paarrot.utils"); +const utils = ctx.require('paarrot.utils'); utils.formatDate(new Date()); // Check if plugin exists try { - const plugin = ctx.require("optional.plugin"); + const plugin = ctx.require('optional.plugin'); } catch (err) { ctx.warn('Optional plugin not available'); } @@ -339,7 +345,7 @@ const rooms = mx.getRooms(); const room = mx.getRoom(roomId); // Send messages -await mx.sendTextMessage(roomId, "Hello!"); +await mx.sendTextMessage(roomId, 'Hello!'); // Full Matrix.js SDK available ``` @@ -354,9 +360,13 @@ const { useState, useEffect } = ctx.React; // Create custom UI components const MyComponent = () => { const [count, setCount] = useState(0); - return ctx.React.createElement('button', { - onClick: () => setCount(count + 1) - }, `Count: ${count}`); + return ctx.React.createElement( + 'button', + { + onClick: () => setCount(count + 1), + }, + `Count: ${count}`, + ); }; ``` @@ -366,54 +376,55 @@ See [`example-plugin/index.js`](../../../../example-plugin/index.js) for a full- ```javascript module.exports = { - name: "Awesome Plugin", - version: "1.0.0", - + name: 'Awesome Plugin', + version: '1.0.0', + onLoad: async (ctx) => { // Register commands ctx.commands.register({ - name: "shrug", - run: () => "¯\\_(ツ)_/¯" + name: 'shrug', + run: () => '¯\\_(ツ)_/¯', }); - + // Message interceptors ctx.messages.onBeforeSend((msg) => { - if (msg.content === "brb") { - msg.content = "be right back!"; + if (msg.content === 'brb') { + msg.content = 'be right back!'; } }); - + // Settings ctx.settings.define({ - enabled: { type: "boolean", default: true } + enabled: { type: 'boolean', default: true }, }); - + // Matrix events - ctx.matrix.on("m.room.message", (event) => { + ctx.matrix.on('m.room.message', (event) => { ctx.log('Message:', event.getContent().body); }); - + // Background task ctx.timers.setInterval(() => { ctx.log('Checking for updates...'); }, 60000); - - ctx.notify("Plugin loaded!"); + + ctx.notify('Plugin loaded!'); }, - + onUnload: async () => { // Cleanup happens automatically }, - + exports: { - version: "1.0.0" - } + version: '1.0.0', + }, }; ``` ## Best Practices ### 1. Error Handling + Always wrap your code in try-catch blocks: ```javascript @@ -423,24 +434,28 @@ onLoad: async (ctx) => { } catch (error) { ctx.error('Failed to load:', error); } -} +}; ``` ### 2. Cleanup Resources + Timers and Matrix handlers are auto-cleaned, but clean up other resources: ```javascript onUnload: async () => { // Close connections, save state, etc. -} +}; ``` ### 3. Performance + Don't block the main thread: ```javascript // Bad -for (let i = 0; i < 1000000; i++) { /* ... */ } +for (let i = 0; i < 1000000; i++) { + /* ... */ +} // Good ctx.timers.setTimeout(() => { @@ -449,26 +464,28 @@ ctx.timers.setTimeout(() => { ``` ### 4. Settings Best Practices + Provide defaults and descriptions: ```javascript ctx.settings.define({ maxRetries: { - type: "number", - label: "Max Retries", - description: "Number of retry attempts", - default: 3 - } + type: 'number', + label: 'Max Retries', + description: 'Number of retry attempts', + default: 3, + }, }); ``` ### 5. Logging + Use ctx.log() instead of console.log(): ```javascript -ctx.log('Info'); // Shows in plugin logs panel +ctx.log('Info'); // Shows in plugin logs panel ctx.warn('Warning'); // Highlighted as warning -ctx.error('Error'); // Highlighted as error +ctx.error('Error'); // Highlighted as error ``` ## Advanced Patterns @@ -480,13 +497,13 @@ Require and use other plugins: ```javascript onLoad: async (ctx) => { try { - const utils = ctx.require("paarrot.utils"); + const utils = ctx.require('paarrot.utils'); const formatted = utils.formatDate(new Date()); ctx.log('Using utils:', formatted); } catch (err) { ctx.warn('Utils plugin not available, using fallback'); } -} +}; ``` ### Conditional Features @@ -496,7 +513,7 @@ Enable features based on settings: ```javascript const autoReply = ctx.settings.get('autoReply'); if (autoReply) { - ctx.matrix.on("m.room.message", (event) => { + ctx.matrix.on('m.room.message', (event) => { // Auto-reply logic }); } @@ -520,10 +537,10 @@ const lastRun = ctx.settings.get('lastRun'); Create multiple commands for the same function: ```javascript -const shrugFn = () => "¯\\_(ツ)_/¯"; +const shrugFn = () => '¯\\_(ツ)_/¯'; -ctx.commands.register({ name: "shrug", run: shrugFn }); -ctx.commands.register({ name: "dunno", run: shrugFn }); +ctx.commands.register({ name: 'shrug', run: shrugFn }); +ctx.commands.register({ name: 'dunno', run: shrugFn }); ``` ### Hot Reload Support @@ -581,26 +598,32 @@ To list your plugin in the marketplace: ## Debugging ### Browser Console + Check the browser console (F12) for plugin logs: + - `[PluginLoader]` - Plugin loading messages - `[Plugin yourplugin]` - Your plugin's logs ### Plugin Logs Panel + View per-plugin logs in Settings → Plugins → Logs (coming soon) ### Common Issues **Plugin won't load:** + - Check `index.js` exists - Verify `module.exports` is correct - Look for JavaScript syntax errors **Command not working:** + - Ensure command is registered in onLoad - Check command name doesn't conflict - Verify run function returns a value **Settings not saving:** + - Use ctx.settings.set() not localStorage - Check setting key matches defined schema diff --git a/src/app/features/settings/plugins/PluginAPI.ts b/src/app/features/settings/plugins/PluginAPI.ts index cd571bda..d8b6bfa3 100644 --- a/src/app/features/settings/plugins/PluginAPI.ts +++ b/src/app/features/settings/plugins/PluginAPI.ts @@ -5,6 +5,12 @@ * All other modules in this folder should import from here rather than * directly from the package so the singleton is guaranteed to be shared. */ +import { + PluginMarketplaceClient, + PluginMarketplaceManager, + PluginRegistry, +} from '@paarrot/plugin-manager'; + export { PluginMarketplaceClient, PluginMarketplaceManager, @@ -49,15 +55,9 @@ export type { export { PluginTab } from '@paarrot/plugin-manager'; -import { - PluginMarketplaceClient, - PluginMarketplaceManager, - PluginRegistry, -} from '@paarrot/plugin-manager'; - const PLUGIN_INDEX_URL = import.meta.env.VITE_PLUGIN_INDEX_URL || - `https://raw.githubusercontent.com/Paarrot/Plugin-Directory/refs/heads/main/plugins/index.json?cache_burst=${(Math.random()*256).toString()}`; + `https://raw.githubusercontent.com/Paarrot/Plugin-Directory/refs/heads/main/plugins/index.json?cache_burst=${(Math.random() * 256).toString()}`; const PLUGIN_BASE_URL = import.meta.env.VITE_PLUGIN_BASE_URL || 'https://raw.githubusercontent.com/Paarrot/Plugin-Directory/refs/heads/main/plugins/'; @@ -79,8 +79,7 @@ function removeThemeStyle(styleId: string): void { /** Shared singleton registry for the entire application. */ export const pluginRegistry = new PluginRegistry({ storage: localStorage, - onThemeRegistered: (themeId, _className, css) => - injectThemeStyle(`plugin-theme-${themeId}`, css), + onThemeRegistered: (themeId, _className, css) => injectThemeStyle(`plugin-theme-${themeId}`, css), onThemeUnregistered: (themeId) => removeThemeStyle(`plugin-theme-${themeId}`), }); @@ -126,7 +125,11 @@ export const pluginMarketplaceManager = new PluginMarketplaceManager({ return; } - const result = await window.electron.plugins.download(plugin.id, plugin.downloadUrl, plugin.name); + const result = await window.electron.plugins.download( + plugin.id, + plugin.downloadUrl, + plugin.name, + ); if (!result.success) { throw new Error(result.error ?? 'Failed to install plugin'); } @@ -142,4 +145,4 @@ export const pluginMarketplaceManager = new PluginMarketplaceManager({ } }, }, -}); \ No newline at end of file +}); diff --git a/src/app/features/settings/plugins/PluginButtonSlot.tsx b/src/app/features/settings/plugins/PluginButtonSlot.tsx index a9b0eabb..78d9e44c 100644 --- a/src/app/features/settings/plugins/PluginButtonSlot.tsx +++ b/src/app/features/settings/plugins/PluginButtonSlot.tsx @@ -40,10 +40,7 @@ interface PluginButtonSlotProps { location: UILocation; } -function renderPluginButtonIcon(button: { - icon?: string; - lucideIcon?: string; -}): React.ReactNode { +function renderPluginButtonIcon(button: { icon?: string; lucideIcon?: string }): React.ReactNode { const lucideName = button.lucideIcon ?? (typeof button.icon === 'string' && button.icon.startsWith('lucide:') @@ -55,9 +52,12 @@ function renderPluginButtonIcon(button: { } if (lucideName) { - const IconComponent = (lucide as Record | undefined>)[ - lucideName - ]; + const IconComponent = ( + lucide as Record< + string, + React.ComponentType<{ size?: number; strokeWidth?: number }> | undefined + > + )[lucideName]; if (IconComponent) { return ; } diff --git a/src/app/features/settings/plugins/PluginLoader.tsx b/src/app/features/settings/plugins/PluginLoader.tsx index 9564da21..146a576d 100644 --- a/src/app/features/settings/plugins/PluginLoader.tsx +++ b/src/app/features/settings/plugins/PluginLoader.tsx @@ -17,7 +17,7 @@ interface PluginLoaderProps { */ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { console.log('[PluginLoader] Component rendering, matrixClient:', !!matrixClient); - + useEffect(() => { const loadPlugins = async () => { try { @@ -33,7 +33,10 @@ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { const pluginsToLoad = await pluginMarketplaceManager.listEnabledPlugins(); console.log('[PluginLoader] Plugins to load:', pluginsToLoad.length); - console.log('[PluginLoader] Plugin list:', pluginsToLoad.map(p => p.id)); + console.log( + '[PluginLoader] Plugin list:', + pluginsToLoad.map((p) => p.id), + ); for (const installedPlugin of pluginsToLoad) { try { @@ -44,14 +47,14 @@ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { if (!plugin || typeof plugin !== 'object') { console.error( - `[PluginLoader] Plugin ${installedPlugin.id} does not export a valid plugin object` + `[PluginLoader] Plugin ${installedPlugin.id} does not export a valid plugin object`, ); continue; } if (typeof plugin.onLoad !== 'function') { console.error( - `[PluginLoader] Plugin ${installedPlugin.id} does not have an onLoad function` + `[PluginLoader] Plugin ${installedPlugin.id} does not have an onLoad function`, ); continue; } @@ -68,7 +71,7 @@ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) { }); }, }, - pluginRegistry + pluginRegistry, ); const compatContext = Object.assign(context as Record, { diff --git a/src/app/features/settings/plugins/PluginSidebarSlot.tsx b/src/app/features/settings/plugins/PluginSidebarSlot.tsx index b86b714d..2c452507 100644 --- a/src/app/features/settings/plugins/PluginSidebarSlot.tsx +++ b/src/app/features/settings/plugins/PluginSidebarSlot.tsx @@ -1,10 +1,6 @@ import React, { useSyncExternalStore } from 'react'; import { UILocation } from '@paarrot/plugin-manager'; -import { - SidebarItem, - SidebarItemTooltip, - SidebarAvatar, -} from '../../../components/sidebar'; +import { SidebarItem, SidebarItemTooltip, SidebarAvatar } from '../../../components/sidebar'; import { pluginRegistry } from './PluginAPI'; import { subscribeToButtons, getStoreVersion } from './PluginButtonSlot'; diff --git a/src/app/features/settings/plugins/Plugins.tsx b/src/app/features/settings/plugins/Plugins.tsx index b182421f..51822705 100644 --- a/src/app/features/settings/plugins/Plugins.tsx +++ b/src/app/features/settings/plugins/Plugins.tsx @@ -1,8 +1,27 @@ import React, { useState, useEffect, useCallback, useMemo } from 'react'; -import { Avatar, Badge, Box, Button, color, config, Header, IconButton, Input, Menu, MenuItem, PopOut, RectCords, Scroll, Spinner, Switch, Text, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Badge, + Box, + Button, + color, + config, + Header, + IconButton, + Input, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Spinner, + Switch, + Text, + toRem, +} from 'folds'; import { HexColorPicker } from 'react-colorful'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { PluginTab, PluginMetadata, InstalledPlugin } from './types'; import { SequenceCard } from '../../../components/sequence-card'; @@ -22,7 +41,9 @@ function PluginSettingsRenderer({ pluginId }: { pluginId: string }) { if (!schema || Object.keys(schema).length === 0) { return ( - No settings available for this plugin. + + No settings available for this plugin. + ); } @@ -65,7 +86,7 @@ function SettingRenderer({ const [selectMenuCords, setSelectMenuCords] = useState(); const label = definition.label || settingKey; - const description = definition.description; + const { description } = definition; // Boolean - Switch if (definition.type === 'boolean') { @@ -111,7 +132,7 @@ function SettingRenderer({ // Select - Dropdown if (definition.type === 'select' && definition.options) { const currentValue = value ?? definition.default ?? definition.options[0]?.value; - const selectedOption = definition.options.find(opt => opt.value === currentValue); + const selectedOption = definition.options.find((opt) => opt.value === currentValue); return ( @@ -145,7 +166,11 @@ function SettingRenderer({ : undefined} + after={ + currentValue === option.value ? ( + + ) : undefined + } radii="300" onClick={() => { onChange(option.value); @@ -277,7 +302,7 @@ export function Plugins({ requestClose }: PluginsProps) { setLoading(false); } }, - [refreshInstalledPlugins] + [refreshInstalledPlugins], ); const handleUninstall = useCallback( @@ -291,7 +316,7 @@ export function Plugins({ requestClose }: PluginsProps) { setError(err instanceof Error ? err.message : 'Failed to uninstall plugin'); } }, - [refreshInstalledPlugins] + [refreshInstalledPlugins], ); const handleToggleEnabled = useCallback( @@ -313,15 +338,15 @@ export function Plugins({ requestClose }: PluginsProps) { setError(err instanceof Error ? err.message : 'Failed to update plugin state'); } }, - [installedPlugins, refreshInstalledPlugins] + [installedPlugins, refreshInstalledPlugins], ); const isPluginInstalled = useCallback( (pluginId: string) => installedPlugins.some((p) => p.id === pluginId), - [installedPlugins] + [installedPlugins], ); - const PluginAvatar = ({ thumbnail, name }: { thumbnail: string; name: string }) => { + function PluginAvatar({ thumbnail, name }: { thumbnail: string; name: string }) { const [imageError, setImageError] = useState(false); return ( @@ -356,7 +381,7 @@ export function Plugins({ requestClose }: PluginsProps) { )} ); - }; + } const filteredMarketplacePlugins = useMemo(() => { if (!searchQuery.trim()) return marketplacePlugins; @@ -468,7 +493,9 @@ export function Plugins({ requestClose }: PluginsProps) { {!loading && !error && filteredMarketplacePlugins.length === 0 && ( - {searchQuery ? 'No plugins found matching your search' : 'No plugins available'} + {searchQuery + ? 'No plugins found matching your search' + : 'No plugins available'} )} @@ -504,7 +531,9 @@ export function Plugins({ requestClose }: PluginsProps) { by {plugin.author} - • + + • + v{plugin.version} @@ -545,112 +574,127 @@ export function Plugins({ requestClose }: PluginsProps) { {filteredInstalledPlugins.length === 0 && ( - {searchQuery ? 'No installed plugins found matching your search' : 'No plugins installed'} + {searchQuery + ? 'No installed plugins found matching your search' + : 'No plugins installed'} )} {filteredInstalledPlugins.map((plugin) => { - const hasSettings = pluginRegistry.getPluginSettingsSchema(plugin.id) && + const hasSettings = + pluginRegistry.getPluginSettingsSchema(plugin.id) && Object.keys(pluginRegistry.getPluginSettingsSchema(plugin.id)!).length > 0; const settingsExpanded = expandedSettings === plugin.id; return ( - { - e.currentTarget.parentElement!.style.transform = 'translateY(-2px)'; - e.currentTarget.parentElement!.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)'; - }} - onMouseLeave={(e) => { - e.currentTarget.parentElement!.style.transform = 'translateY(0)'; - e.currentTarget.parentElement!.style.boxShadow = 'none'; + background: color.Surface.Container, + borderRadius: config.radii.R400, + border: `1px solid ${color.Surface.ContainerLine}`, + transition: 'all 0.2s ease', }} > - - - - - - - {plugin.name} - - - by {plugin.author} - - • - - v{plugin.version} - - - - - {plugin.description} - - - - {plugin.enabled ? 'Enabled' : 'Disabled'} - - - - - {hasSettings && ( - - )} - - - - - - {hasSettings && settingsExpanded && ( { + e.currentTarget.parentElement!.style.transform = 'translateY(-2px)'; + e.currentTarget.parentElement!.style.boxShadow = + '0 4px 12px rgba(0,0,0,0.1)'; + }} + onMouseLeave={(e) => { + e.currentTarget.parentElement!.style.transform = 'translateY(0)'; + e.currentTarget.parentElement!.style.boxShadow = 'none'; }} > - + + + + + + + {plugin.name} + + + by {plugin.author} + + + • + + + v{plugin.version} + + + + + {plugin.description} + + + + {plugin.enabled ? 'Enabled' : 'Disabled'} + + + + + {hasSettings && ( + + )} + + + + - )} - + {hasSettings && settingsExpanded && ( + + + + )} + ); })} diff --git a/src/app/features/settings/settingsSearchCatalog.ts b/src/app/features/settings/settingsSearchCatalog.ts index b168ea8f..0e8434ca 100644 --- a/src/app/features/settings/settingsSearchCatalog.ts +++ b/src/app/features/settings/settingsSearchCatalog.ts @@ -14,27 +14,51 @@ export type SettingsSearchEntry = { */ export const SETTINGS_SEARCH_CATALOG: SettingsSearchEntry[] = [ // Pages - { page: SettingsPages.GeneralPage, title: 'General', keywords: ['appearance', 'theme', 'messages', 'editor'] }, - { page: SettingsPages.AccountPage, title: 'Account', keywords: ['profile', 'email', 'mxid', 'ignore'] }, + { + page: SettingsPages.GeneralPage, + title: 'General', + keywords: ['appearance', 'theme', 'messages', 'editor'], + }, + { + page: SettingsPages.AccountPage, + title: 'Account', + keywords: ['profile', 'email', 'mxid', 'ignore'], + }, { page: SettingsPages.NotificationPage, title: 'Notifications', keywords: ['alerts', 'push', 'desktop', 'sound', 'mentions'], }, - { page: SettingsPages.AudioPage, title: 'Audio & Video', keywords: ['microphone', 'speaker', 'call', 'camera'] }, - { page: SettingsPages.DevicesPage, title: 'Devices', keywords: ['sessions', 'verification', 'backup', 'export'] }, + { + page: SettingsPages.AudioPage, + title: 'Audio & Video', + keywords: ['microphone', 'speaker', 'call', 'camera'], + }, + { + page: SettingsPages.DevicesPage, + title: 'Devices', + keywords: ['sessions', 'verification', 'backup', 'export'], + }, { page: SettingsPages.EmojisStickersPage, title: 'Emojis & Stickers', keywords: ['emoticons', 'stickers', 'telegram', 'custom emoji'], }, - { page: SettingsPages.PluginsPage, title: 'Plugins', keywords: ['extensions', 'addons', 'marketplace'] }, + { + page: SettingsPages.PluginsPage, + title: 'Plugins', + keywords: ['extensions', 'addons', 'marketplace'], + }, { page: SettingsPages.DeveloperToolsPage, title: 'Developer Tools', keywords: ['debug', 'token', 'account data'], }, - { page: SettingsPages.AboutPage, title: 'About', keywords: ['version', 'cache', 'protocol', 'paarrot'] }, + { + page: SettingsPages.AboutPage, + title: 'About', + keywords: ['version', 'cache', 'protocol', 'paarrot'], + }, // General { @@ -43,71 +67,167 @@ export const SETTINGS_SEARCH_CATALOG: SettingsSearchEntry[] = [ keywords: ['appearance', 'dark', 'light', 'auto'], }, { page: SettingsPages.GeneralPage, title: 'Theme', keywords: ['appearance', 'color scheme'] }, - { page: SettingsPages.GeneralPage, title: 'Monochrome Mode', keywords: ['grayscale', 'appearance'] }, - { page: SettingsPages.GeneralPage, title: 'Emoji Style', keywords: ['appearance', 'twemoji', 'native'] }, - { page: SettingsPages.GeneralPage, title: 'Page Zoom', keywords: ['scale', 'accessibility', 'size'] }, + { + page: SettingsPages.GeneralPage, + title: 'Monochrome Mode', + keywords: ['grayscale', 'appearance'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Emoji Style', + keywords: ['appearance', 'twemoji', 'native'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Page Zoom', + keywords: ['scale', 'accessibility', 'size'], + }, { page: SettingsPages.GeneralPage, title: 'Date Format', keywords: ['time', 'calendar'] }, { page: SettingsPages.GeneralPage, title: '24-Hour Time Format', keywords: ['clock', 'time'] }, - { page: SettingsPages.GeneralPage, title: 'ENTER for Newline', keywords: ['editor', 'keyboard', 'shift enter'] }, - { page: SettingsPages.GeneralPage, title: 'Markdown Formatting', keywords: ['editor', 'formatting'] }, + { + page: SettingsPages.GeneralPage, + title: 'ENTER for Newline', + keywords: ['editor', 'keyboard', 'shift enter'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Markdown Formatting', + keywords: ['editor', 'formatting'], + }, { page: SettingsPages.GeneralPage, title: 'Hide Typing & Read Receipts', keywords: ['privacy', 'activity', 'typing'], }, { page: SettingsPages.GeneralPage, title: 'Auto-Join Space Rooms', keywords: ['spaces', 'join'] }, - { page: SettingsPages.GeneralPage, title: 'Message Layout', keywords: ['bubbles', 'compact', 'modern'] }, + { + page: SettingsPages.GeneralPage, + title: 'Message Layout', + keywords: ['bubbles', 'compact', 'modern'], + }, { page: SettingsPages.GeneralPage, title: 'Message Spacing', keywords: ['density', 'gap'] }, { page: SettingsPages.GeneralPage, title: 'Scroll to Latest on Room Reselect', keywords: ['timeline', 'jump'], }, - { page: SettingsPages.GeneralPage, title: 'Legacy Username Color', keywords: ['appearance', 'mxid color'] }, - { page: SettingsPages.GeneralPage, title: 'Hide Membership Change', keywords: ['joins', 'leaves', 'timeline'] }, - { page: SettingsPages.GeneralPage, title: 'Hide Profile Change', keywords: ['avatar', 'displayname', 'timeline'] }, - { page: SettingsPages.GeneralPage, title: 'Disable Media Auto Load', keywords: ['images', 'bandwidth', 'lazy'] }, + { + page: SettingsPages.GeneralPage, + title: 'Legacy Username Color', + keywords: ['appearance', 'mxid color'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Hide Membership Change', + keywords: ['joins', 'leaves', 'timeline'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Hide Profile Change', + keywords: ['avatar', 'displayname', 'timeline'], + }, + { + page: SettingsPages.GeneralPage, + title: 'Disable Media Auto Load', + keywords: ['images', 'bandwidth', 'lazy'], + }, { page: SettingsPages.GeneralPage, title: 'Url Preview', keywords: ['link', 'embed', 'unfurl'] }, { page: SettingsPages.GeneralPage, title: 'Url Preview in Encrypted Room', keywords: ['e2ee', 'link', 'embed'], }, - { page: SettingsPages.GeneralPage, title: 'Show Hidden Events', keywords: ['state', 'debug', 'timeline'] }, + { + page: SettingsPages.GeneralPage, + title: 'Show Hidden Events', + keywords: ['state', 'debug', 'timeline'], + }, // Account - { page: SettingsPages.AccountPage, title: 'Profile', keywords: ['displayname', 'avatar', 'name'] }, + { + page: SettingsPages.AccountPage, + title: 'Profile', + keywords: ['displayname', 'avatar', 'name'], + }, { page: SettingsPages.AccountPage, title: 'Email Address', keywords: ['contact', 'mail'] }, - { page: SettingsPages.AccountPage, title: 'Ignored Users', keywords: ['block', 'mute', 'ignore'] }, + { + page: SettingsPages.AccountPage, + title: 'Ignored Users', + keywords: ['block', 'mute', 'ignore'], + }, // Notifications - { page: SettingsPages.NotificationPage, title: 'Desktop Notifications', keywords: ['system', 'os'] }, - { page: SettingsPages.NotificationPage, title: 'Notification Sound', keywords: ['audio', 'alert'] }, + { + page: SettingsPages.NotificationPage, + title: 'Desktop Notifications', + keywords: ['system', 'os'], + }, + { + page: SettingsPages.NotificationPage, + title: 'Notification Sound', + keywords: ['audio', 'alert'], + }, { page: SettingsPages.NotificationPage, title: 'Email Notification', keywords: ['mail'] }, - { page: SettingsPages.NotificationPage, title: 'Background Notifications', keywords: ['tray', 'electron'] }, + { + page: SettingsPages.NotificationPage, + title: 'Background Notifications', + keywords: ['tray', 'electron'], + }, { page: SettingsPages.NotificationPage, title: '1-to-1 Chats', keywords: ['dm', 'direct'] }, { page: SettingsPages.NotificationPage, title: 'Rooms', keywords: ['messages', 'push'] }, { page: SettingsPages.NotificationPage, title: 'Mention @room', keywords: ['highlight', 'ping'] }, - { page: SettingsPages.NotificationPage, title: 'Keyword Messages', keywords: ['highlight', 'filter'] }, - { page: SettingsPages.NotificationPage, title: 'Special Messages', keywords: ['mentions', 'displayname'] }, - { page: SettingsPages.NotificationPage, title: 'Test Notification', keywords: ['preview', 'sound'] }, + { + page: SettingsPages.NotificationPage, + title: 'Keyword Messages', + keywords: ['highlight', 'filter'], + }, + { + page: SettingsPages.NotificationPage, + title: 'Special Messages', + keywords: ['mentions', 'displayname'], + }, + { + page: SettingsPages.NotificationPage, + title: 'Test Notification', + keywords: ['preview', 'sound'], + }, // Audio & Video { page: SettingsPages.AudioPage, title: 'Input Device', keywords: ['microphone', 'mic'] }, { page: SettingsPages.AudioPage, title: 'Output Device', keywords: ['speaker', 'headphones'] }, - { page: SettingsPages.AudioPage, title: 'Noise Suppression', keywords: ['microphone', 'processing'] }, + { + page: SettingsPages.AudioPage, + title: 'Noise Suppression', + keywords: ['microphone', 'processing'], + }, { page: SettingsPages.AudioPage, title: 'Echo Cancellation', keywords: ['microphone', 'aec'] }, { page: SettingsPages.AudioPage, title: 'Auto Gain Control', keywords: ['microphone', 'agc'] }, { page: SettingsPages.AudioPage, title: 'Resolution', keywords: ['screen share', 'video'] }, { page: SettingsPages.AudioPage, title: 'Bitrate', keywords: ['screen share', 'quality'] }, { page: SettingsPages.AudioPage, title: 'Frame Rate', keywords: ['screen share', 'fps'] }, - { page: SettingsPages.AudioPage, title: 'Show Remote Cursor', keywords: ['screen share', 'pointer'] }, + { + page: SettingsPages.AudioPage, + title: 'Show Remote Cursor', + keywords: ['screen share', 'pointer'], + }, // Devices - { page: SettingsPages.DevicesPage, title: 'Device Verification', keywords: ['crypto', 'cross signing'] }, + { + page: SettingsPages.DevicesPage, + title: 'Device Verification', + keywords: ['crypto', 'cross signing'], + }, { page: SettingsPages.DevicesPage, title: 'Device Dashboard', keywords: ['sessions', 'logout'] }, - { page: SettingsPages.DevicesPage, title: 'Export Messages Data', keywords: ['backup', 'download'] }, - { page: SettingsPages.DevicesPage, title: 'Import Messages Data', keywords: ['backup', 'restore'] }, + { + page: SettingsPages.DevicesPage, + title: 'Export Messages Data', + keywords: ['backup', 'download'], + }, + { + page: SettingsPages.DevicesPage, + title: 'Import Messages Data', + keywords: ['backup', 'restore'], + }, // Emojis & Stickers { @@ -115,8 +235,16 @@ export const SETTINGS_SEARCH_CATALOG: SettingsSearchEntry[] = [ title: 'Auto-convert Text Emoticons', keywords: ['smileys', 'colon'], }, - { page: SettingsPages.EmojisStickersPage, title: 'Telegram Bot Token', keywords: ['stickers', 'import'] }, - { page: SettingsPages.EmojisStickersPage, title: 'Sticker Pack URL', keywords: ['telegram', 'import'] }, + { + page: SettingsPages.EmojisStickersPage, + title: 'Telegram Bot Token', + keywords: ['stickers', 'import'], + }, + { + page: SettingsPages.EmojisStickersPage, + title: 'Sticker Pack URL', + keywords: ['telegram', 'import'], + }, // Developer Tools { diff --git a/src/app/features/space-settings/SpaceSettings.tsx b/src/app/features/space-settings/SpaceSettings.tsx index 44fc1fb9..431a1fcd 100644 --- a/src/app/features/space-settings/SpaceSettings.tsx +++ b/src/app/features/space-settings/SpaceSettings.tsx @@ -1,8 +1,8 @@ import React, { useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import { Avatar, Box, config, IconButton, MenuItem, Text } from 'folds'; -import { Icon, Icons, IconSrc } from '../../components/icons'; import { JoinRule } from 'matrix-js-sdk'; +import { Icon, Icons, IconSrc } from '../../components/icons'; import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -54,7 +54,7 @@ const useSpaceSettingsMenuItems = (): SpaceSettingsMenuItem[] => icon: Icons.Terminal, }, ], - [] + [], ); type SpaceSettingsProps = { @@ -72,7 +72,7 @@ export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps) const joinRuleContent = useRoomJoinRule(room); const avatarUrl = roomAvatar - ? mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined; const screenSize = useScreenSizeContext(); diff --git a/src/app/features/space-settings/permissions/Permissions.tsx b/src/app/features/space-settings/permissions/Permissions.tsx index 477f0a04..71c392a4 100644 --- a/src/app/features/space-settings/permissions/Permissions.tsx +++ b/src/app/features/space-settings/permissions/Permissions.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useMemo, useState } from 'react'; import { Box, Button, IconButton, Scroll, Spinner, Text, color } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageHeader } from '../../../components/page'; import { useRoom } from '../../../hooks/useRoom'; import { usePowerLevels } from '../../../hooks/usePowerLevels'; @@ -14,7 +14,11 @@ import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { allRoomsAtom } from '../../../state/room-list/roomList'; import { roomToParentsAtom } from '../../../state/room/roomToParents'; -import { useRecursiveChildScopeFactory, useRecursiveChildSpaceScopeFactory, useSpaceChildren } from '../../../state/hooks/roomList'; +import { + useRecursiveChildScopeFactory, + useRecursiveChildSpaceScopeFactory, + useSpaceChildren, +} from '../../../state/hooks/roomList'; type PermissionsProps = { requestClose: () => void; @@ -38,14 +42,14 @@ export function Permissions({ requestClose }: PermissionsProps) { const childSpaces = useSpaceChildren( allRoomsAtom, room.roomId, - useRecursiveChildSpaceScopeFactory(mx, roomToParents) + useRecursiveChildSpaceScopeFactory(mx, roomToParents), ); // Get all child rooms recursively const childRooms = useSpaceChildren( allRoomsAtom, room.roomId, - useRecursiveChildScopeFactory(mx, roomToParents) + useRecursiveChildScopeFactory(mx, roomToParents), ); // Combine both spaces and rooms for syncing @@ -64,18 +68,26 @@ export function Permissions({ requestClose }: PermissionsProps) { } // Check if we have permission to edit power levels in the child - const childPowerLevels = childRoom.currentState.getStateEvents(StateEvent.RoomPowerLevels, ''); + const childPowerLevels = childRoom.currentState.getStateEvents( + StateEvent.RoomPowerLevels, + '', + ); const childPowerLevelsContent = childPowerLevels?.getContent() || {}; const childCreators = new Set(); - const creatorId = childRoom.currentState.getStateEvents('m.room.create', '')?.getContent()?.creator; + const creatorId = childRoom.currentState + .getStateEvents('m.room.create', '') + ?.getContent()?.creator; if (creatorId) childCreators.add(creatorId); const myUserId = mx.getSafeUserId(); - const myPower = childPowerLevelsContent.users?.[myUserId] ?? childPowerLevelsContent.users_default ?? 0; - + const myPower = + childPowerLevelsContent.users?.[myUserId] ?? childPowerLevelsContent.users_default ?? 0; + // Check the specific power level required for m.room.power_levels events - const requiredPower = childPowerLevelsContent.events?.[StateEvent.RoomPowerLevels] ?? - childPowerLevelsContent.state_default ?? 50; + const requiredPower = + childPowerLevelsContent.events?.[StateEvent.RoomPowerLevels] ?? + childPowerLevelsContent.state_default ?? + 50; if (myPower >= requiredPower || childCreators.has(myUserId)) { syncable.push(childId); @@ -90,7 +102,10 @@ export function Permissions({ requestClose }: PermissionsProps) { const [syncState, syncPermissions] = useAsyncCallback( useCallback(async () => { // Get the power level tags from this space - const powerLevelTagsEvent = room.currentState.getStateEvents('in.cinny.room.power_level_tags', ''); + const powerLevelTagsEvent = room.currentState.getStateEvents( + 'in.cinny.room.power_level_tags', + '', + ); const powerLevelTags = powerLevelTagsEvent?.getContent(); let completed = 0; @@ -103,15 +118,19 @@ export function Permissions({ requestClose }: PermissionsProps) { if (!childRoom) continue; // Get current power levels in the child room - const childPowerLevelsEvent = childRoom.currentState.getStateEvents(StateEvent.RoomPowerLevels, ''); + const childPowerLevelsEvent = childRoom.currentState.getStateEvents( + StateEvent.RoomPowerLevels, + '', + ); const childPowerLevels = childPowerLevelsEvent?.getContent() || {}; - + // Get my power level in the child room - const myPowerInChild = childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0; - + const myPowerInChild = + childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0; + // Build merged users: only sync users with power <= mine, preserve higher-powered users const mergedUsers: Record = {}; - + // Copy users from parent where power <= my power in child if (powerLevels.users) { Object.entries(powerLevels.users).forEach(([userId, power]) => { @@ -120,7 +139,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } }); } - + // Preserve all users in child room who have power >= mine if (childPowerLevels.users) { Object.entries(childPowerLevels.users).forEach(([userId, power]) => { @@ -129,7 +148,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } }); } - + // Cap all power level values at my power level const capPowerLevel = (value: any) => { if (typeof value === 'number') { @@ -137,7 +156,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } return value; }; - + // Create the merged power levels with capped values const mergedPowerLevels: any = { ...powerLevels, @@ -150,7 +169,7 @@ export function Permissions({ requestClose }: PermissionsProps) { state_default: capPowerLevel(powerLevels.state_default), users_default: capPowerLevel(powerLevels.users_default), }; - + // Cap event-specific power levels if (powerLevels.events) { mergedPowerLevels.events = {}; @@ -158,7 +177,7 @@ export function Permissions({ requestClose }: PermissionsProps) { mergedPowerLevels.events[eventType] = capPowerLevel(power); }); } - + // Cap notification power levels if (powerLevels.notifications) { mergedPowerLevels.notifications = {}; @@ -166,19 +185,23 @@ export function Permissions({ requestClose }: PermissionsProps) { mergedPowerLevels.notifications[key] = capPowerLevel(power); }); } - + await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels); - + // Also copy power level tags if they exist if (powerLevelTags) { - await mx.sendStateEvent(childId, 'in.cinny.room.power_level_tags' as any, powerLevelTags); + await mx.sendStateEvent( + childId, + 'in.cinny.room.power_level_tags' as any, + powerLevelTags, + ); } - + completed += 1; - + // Add a small delay to avoid rate limiting if (completed < total) { - await new Promise(resolve => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); } } catch (error) { console.error(`Failed to sync permissions to ${childId}:`, error); @@ -186,7 +209,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } return { completed, total }; - }, [mx, syncableChildren, powerLevels, room]) + }, [mx, syncableChildren, powerLevels, room]), ); const [syncPowerLevelsState, syncPowerLevelsOnly] = useAsyncCallback( @@ -201,15 +224,19 @@ export function Permissions({ requestClose }: PermissionsProps) { if (!childRoom) continue; // Get current power levels in the child room - const childPowerLevelsEvent = childRoom.currentState.getStateEvents(StateEvent.RoomPowerLevels, ''); + const childPowerLevelsEvent = childRoom.currentState.getStateEvents( + StateEvent.RoomPowerLevels, + '', + ); const childPowerLevels = childPowerLevelsEvent?.getContent() || {}; - + // Get my power level in the child room - const myPowerInChild = childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0; - + const myPowerInChild = + childPowerLevels.users?.[myUserId] ?? childPowerLevels.users_default ?? 0; + // Build merged users: only sync users with power <= mine, preserve higher-powered users const mergedUsers: Record = {}; - + // Copy users from parent where power <= my power in child if (powerLevels.users) { Object.entries(powerLevels.users).forEach(([userId, power]) => { @@ -218,7 +245,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } }); } - + // Preserve all users in child room who have power >= mine if (childPowerLevels.users) { Object.entries(childPowerLevels.users).forEach(([userId, power]) => { @@ -227,7 +254,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } }); } - + // Cap all power level values at my power level const capPowerLevel = (value: any) => { if (typeof value === 'number') { @@ -235,7 +262,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } return value; }; - + // Create the merged power levels with capped values const mergedPowerLevels: any = { ...powerLevels, @@ -248,7 +275,7 @@ export function Permissions({ requestClose }: PermissionsProps) { state_default: capPowerLevel(powerLevels.state_default), users_default: capPowerLevel(powerLevels.users_default), }; - + // Cap event-specific power levels if (powerLevels.events) { mergedPowerLevels.events = {}; @@ -256,7 +283,7 @@ export function Permissions({ requestClose }: PermissionsProps) { mergedPowerLevels.events[eventType] = capPowerLevel(power); }); } - + // Cap notification power levels if (powerLevels.notifications) { mergedPowerLevels.notifications = {}; @@ -264,14 +291,14 @@ export function Permissions({ requestClose }: PermissionsProps) { mergedPowerLevels.notifications[key] = capPowerLevel(power); }); } - + await mx.sendStateEvent(childId, StateEvent.RoomPowerLevels as any, mergedPowerLevels); - + completed += 1; - + // Add a small delay to avoid rate limiting if (completed < total) { - await new Promise(resolve => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); } } catch (error) { console.error(`Failed to sync power levels to ${childId}:`, error); @@ -279,7 +306,7 @@ export function Permissions({ requestClose }: PermissionsProps) { } return { completed, total }; - }, [mx, syncableChildren, powerLevels]) + }, [mx, syncableChildren, powerLevels]), ); const handleEditPowers = () => { @@ -333,18 +360,28 @@ export function Permissions({ requestClose }: PermissionsProps) { Sync these permissions and power level tags to all child subspaces and rooms. {nonSyncableChildren.length > 0 ? ( - <> This will sync to {syncableChildren.length} child{' '} - {syncableChildren.length === 1 ? 'space/room' : 'spaces/rooms'} where you have permission. + <> + {' '} + This will sync to {syncableChildren.length} child{' '} + {syncableChildren.length === 1 ? 'space/room' : 'spaces/rooms'} where you + have permission. - {' '}You don't have permission to edit {nonSyncableChildren.length} other{' '} + {' '} + You don't have permission to edit { + nonSyncableChildren.length + } other{' '} {nonSyncableChildren.length === 1 ? 'space/room' : 'spaces/rooms'} {nonSyncableChildren.length <= 5 && ( - <>: {nonSyncableChildren.map(c => c.name).join(', ')} - )}. + <>: {nonSyncableChildren.map((c) => c.name).join(', ')} + )} + . ) : ( - <> This will overwrite the power levels and custom role tags in {syncableChildren.length} child{' '} + <> + {' '} + This will overwrite the power levels and custom role tags in{' '} + {syncableChildren.length} child{' '} {syncableChildren.length === 1 ? 'space/room' : 'spaces/rooms'}. )} @@ -406,7 +443,8 @@ export function Permissions({ requestClose }: PermissionsProps) { {powerLevelsSyncSuccess && ( - Successfully synced power levels to {syncPowerLevelsState.data.completed} of{' '} + Successfully synced power levels to{' '} + {syncPowerLevelsState.data.completed} of{' '} {syncPowerLevelsState.data.total} children )} diff --git a/src/app/features/space/SpaceOptionsMenu.tsx b/src/app/features/space/SpaceOptionsMenu.tsx index fd0f8301..2c1f3f12 100644 --- a/src/app/features/space/SpaceOptionsMenu.tsx +++ b/src/app/features/space/SpaceOptionsMenu.tsx @@ -2,6 +2,7 @@ import React, { forwardRef, useState } from 'react'; import { Room } from 'matrix-js-sdk'; import { useAtomValue } from 'jotai'; import { Box, Line, Menu, MenuItem, Text, config, toRem } from 'folds'; +import { useNavigate } from 'react-router-dom'; import { Icon, Icons } from '../../components/icons'; import type { HierarchyItem } from '../../hooks/useSpaceHierarchy'; import { useMatrixClient } from '../../hooks/useMatrixClient'; @@ -29,7 +30,6 @@ import { copyToClipboard } from '../../utils/dom'; import { getCanonicalAliasOrRoomId, isRoomAlias } from '../../utils/matrix'; import { getMatrixToRoom } from '../../plugins/matrix-to'; import { getViaServers } from '../../plugins/via-servers'; -import { useNavigate } from 'react-router-dom'; import { getSpaceFeedPath, getSpaceLobbyPath } from '../../pages/pathUtils'; import { shouldShowForumLobby } from '../../utils/room'; import { useSpaceFeedSelected } from '../../hooks/router/useSelectedSpace'; @@ -81,7 +81,7 @@ export const SpaceOptionsMenu = forwardRef - - {forumAdd && ( - <> - + + {forumAdd && ( + <> + + } + radii="300" + > + + Add Topic + + + + + Add Existing Topic + + + {forumAdd.showAddSpace && ( + <> + } + radii="300" + fill="None" + > + + Add Section + + + + + Add Existing Section + + + + )} + + + + )} + + {invitePrompt && ( + { + setInvitePrompt(false); + requestClose(); + }} + /> + )} + {isForum && !onFeed && ( } + after={} radii="300" > - Add Topic + Feed + )} + {isForum && onFeed && ( } radii="300" - fill="None" > - Add Existing Topic + Manage - {forumAdd.showAddSpace && ( - <> - } - radii="300" - fill="None" - > - - Add Section - - - - - Add Existing Section - - - - )} - - - - )} - - {invitePrompt && ( - { - setInvitePrompt(false); - requestClose(); - }} - /> - )} - {isForum && !onFeed && ( + )} } + after={} + radii="300" + disabled={!unread} + > + + Mark as Read + + + + + + } + radii="300" + aria-pressed={invitePrompt} + disabled={!canInvite} + > + + Invite + + + } radii="300" > - Feed + Copy Link - )} - {isForum && onFeed && ( } + after={} radii="300" > - Manage + Space Settings - )} - } - radii="300" - disabled={!unread} - > - - Mark as Read - - - - - - } - radii="300" - aria-pressed={invitePrompt} - disabled={!canInvite} - > - - Invite - - - } - radii="300" - > - - Copy Link - - - } - radii="300" - > - - Space Settings - - - {developerTools && ( - } - radii="300" - > - - Event Timeline - - - )} - - - - {canEditChildren && ( + {developerTools && ( + } + radii="300" + > + + Event Timeline + + + )} + + + + {canEditChildren && ( + + {(promptRemove, setPromptRemove) => ( + <> + setPromptRemove(true)} + variant="Critical" + fill="None" + size="300" + after={} + radii="300" + aria-pressed={promptRemove} + > + + Remove Inaccessible + + + {promptRemove && ( + setPromptRemove(false)} + /> + )} + + )} + + )} - {(promptRemove, setPromptRemove) => ( + {(promptLeave, setPromptLeave) => ( <> setPromptRemove(true)} + onClick={() => setPromptLeave(true)} variant="Critical" fill="None" size="300" - after={} + after={} radii="300" - aria-pressed={promptRemove} + aria-pressed={promptLeave} > - Remove Inaccessible + Leave Space - {promptRemove && ( - setPromptRemove(false)} + onCancel={() => setPromptLeave(false)} /> )} )} - )} - - {(promptLeave, setPromptLeave) => ( - <> - setPromptLeave(true)} - variant="Critical" - fill="None" - size="300" - after={} - radii="300" - aria-pressed={promptLeave} - > - - Leave Space - - - {promptLeave && ( - setPromptLeave(false)} - /> - )} - - )} - - - - {forumAdd && addExistingRoom && ( - setAddExistingRoom(false)} /> - )} - {forumAdd && addExistingSpace && ( - setAddExistingSpace(false)} - /> - )} + + + {forumAdd && addExistingRoom && ( + setAddExistingRoom(false)} + /> + )} + {forumAdd && addExistingSpace && ( + setAddExistingSpace(false)} + /> + )} ); - } + }, ); diff --git a/src/app/hooks/media/useMediaLoading.ts b/src/app/hooks/media/useMediaLoading.ts index 9d732010..ce058a98 100644 --- a/src/app/hooks/media/useMediaLoading.ts +++ b/src/app/hooks/media/useMediaLoading.ts @@ -6,7 +6,7 @@ export type MediaLoadingData = { }; export const useMediaLoading = ( - getTargetElement: () => HTMLMediaElement | null + getTargetElement: () => HTMLMediaElement | null, ): MediaLoadingData => { const [loadingData, setLoadingData] = useState({ loading: false, diff --git a/src/app/hooks/media/useMediaPlay.ts b/src/app/hooks/media/useMediaPlay.ts index e175eee2..5ed61ad5 100644 --- a/src/app/hooks/media/useMediaPlay.ts +++ b/src/app/hooks/media/useMediaPlay.ts @@ -9,7 +9,7 @@ export type MediaPlayControl = { }; export const useMediaPlay = ( - getTargetElement: () => HTMLMediaElement | null + getTargetElement: () => HTMLMediaElement | null, ): MediaPlayData & MediaPlayControl => { const [playing, setPlay] = useState(false); @@ -20,7 +20,7 @@ export const useMediaPlay = ( if (play) targetEl.play(); else targetEl.pause(); }, - [getTargetElement] + [getTargetElement], ); useEffect(() => { diff --git a/src/app/hooks/media/useMediaPlayTimeCallback.ts b/src/app/hooks/media/useMediaPlayTimeCallback.ts index c70ddc6e..8d332f70 100644 --- a/src/app/hooks/media/useMediaPlayTimeCallback.ts +++ b/src/app/hooks/media/useMediaPlayTimeCallback.ts @@ -4,7 +4,7 @@ export type PlayTimeCallback = (duration: number, currentTime: number) => void; export const useMediaPlayTimeCallback = ( getTargetElement: () => HTMLMediaElement | null, - onPlayTimeCallback: PlayTimeCallback + onPlayTimeCallback: PlayTimeCallback, ): void => { useEffect(() => { const targetEl = getTargetElement(); diff --git a/src/app/hooks/media/useMediaPlaybackRate.ts b/src/app/hooks/media/useMediaPlaybackRate.ts index 17368845..b71be651 100644 --- a/src/app/hooks/media/useMediaPlaybackRate.ts +++ b/src/app/hooks/media/useMediaPlaybackRate.ts @@ -8,7 +8,7 @@ export type MediaPlaybackRateControl = { }; export const useMediaPlaybackRate = ( - getTargetElement: () => HTMLMediaElement | null + getTargetElement: () => HTMLMediaElement | null, ): MediaPlaybackRateData & MediaPlaybackRateControl => { const [rate, setRate] = useState(1.0); @@ -18,7 +18,7 @@ export const useMediaPlaybackRate = ( if (!targetEl) return; targetEl.playbackRate = playbackRate; }, - [getTargetElement] + [getTargetElement], ); useEffect(() => { diff --git a/src/app/hooks/media/useMediaSeek.ts b/src/app/hooks/media/useMediaSeek.ts index 89c8d077..28b524ef 100644 --- a/src/app/hooks/media/useMediaSeek.ts +++ b/src/app/hooks/media/useMediaSeek.ts @@ -9,7 +9,7 @@ export type MediaSeekControl = { }; export const useMediaSeek = ( - getTargetElement: () => HTMLMediaElement | null + getTargetElement: () => HTMLMediaElement | null, ): MediaSeekData & MediaSeekControl => { const [seekData, setSeekData] = useState({ seeking: false, @@ -22,7 +22,7 @@ export const useMediaSeek = ( if (!targetEl) return; targetEl.currentTime = time; }, - [getTargetElement] + [getTargetElement], ); useEffect(() => { diff --git a/src/app/hooks/media/useMediaVolume.ts b/src/app/hooks/media/useMediaVolume.ts index 605cee46..4e294b82 100644 --- a/src/app/hooks/media/useMediaVolume.ts +++ b/src/app/hooks/media/useMediaVolume.ts @@ -11,7 +11,7 @@ export type MediaVolumeControl = { }; export const useMediaVolume = ( - getTargetElement: () => HTMLMediaElement | null + getTargetElement: () => HTMLMediaElement | null, ): MediaVolumeData & MediaVolumeControl => { const [volumeData, setVolumeData] = useState({ volume: 1, @@ -24,7 +24,7 @@ export const useMediaVolume = ( if (!targetEl) return; targetEl.muted = mute; }, - [getTargetElement] + [getTargetElement], ); const setVolume = useCallback( @@ -33,7 +33,7 @@ export const useMediaVolume = ( if (!targetEl) return; targetEl.volume = volume; }, - [getTargetElement] + [getTargetElement], ); useEffect(() => { diff --git a/src/app/hooks/types.ts b/src/app/hooks/types.ts index 9aac2b31..14d7052b 100644 --- a/src/app/hooks/types.ts +++ b/src/app/hooks/types.ts @@ -8,5 +8,5 @@ export type RequestEmailTokenResponse = { export type RequestEmailTokenCallback = ( email: string, clientSecret: string, - nextLink?: string + nextLink?: string, ) => Promise; diff --git a/src/app/hooks/useAccountData.ts b/src/app/hooks/useAccountData.ts index 30e47b47..923633a1 100644 --- a/src/app/hooks/useAccountData.ts +++ b/src/app/hooks/useAccountData.ts @@ -14,8 +14,8 @@ export function useAccountData(eventType: string) { setEvent(evt); } }, - [eventType, setEvent] - ) + [eventType, setEvent], + ), ); return event; diff --git a/src/app/hooks/useAccountDataCallback.ts b/src/app/hooks/useAccountDataCallback.ts index e12f1c4d..01cb05a6 100644 --- a/src/app/hooks/useAccountDataCallback.ts +++ b/src/app/hooks/useAccountDataCallback.ts @@ -3,7 +3,7 @@ import { useEffect } from 'react'; export const useAccountDataCallback = ( mx: MatrixClient, - onAccountData: ClientEventHandlerMap[ClientEvent.AccountData] + onAccountData: ClientEventHandlerMap[ClientEvent.AccountData], ) => { useEffect(() => { mx.on(ClientEvent.AccountData, onAccountData); diff --git a/src/app/hooks/useAccountManagement.ts b/src/app/hooks/useAccountManagement.ts index 5eafedc4..b5f0f4ee 100644 --- a/src/app/hooks/useAccountManagement.ts +++ b/src/app/hooks/useAccountManagement.ts @@ -10,7 +10,7 @@ export const useAccountManagementActions = () => { accountDeactivate: 'org.matrix.account_deactivate', crossSigningReset: 'org.matrix.cross_signing_reset', }), - [] + [], ); return actions; diff --git a/src/app/hooks/useAsyncCallback.ts b/src/app/hooks/useAsyncCallback.ts index 5a0380f0..f3b0eb26 100644 --- a/src/app/hooks/useAsyncCallback.ts +++ b/src/app/hooks/useAsyncCallback.ts @@ -33,7 +33,7 @@ export type AsyncCallback = (...args: TArgs) => export const useAsync = ( asyncCallback: AsyncCallback, - onStateChange: (state: AsyncState) => void + onStateChange: (state: AsyncState) => void, ): AsyncCallback => { const alive = useAlive(); @@ -90,14 +90,14 @@ export const useAsync = ( throw e; } }, - [asyncCallback, alive, onStateChange] + [asyncCallback, alive, onStateChange], ); return callback; }; export const useAsyncCallback = ( - asyncCallback: AsyncCallback + asyncCallback: AsyncCallback, ): [AsyncState, AsyncCallback] => { const [state, setState] = useState>({ status: AsyncStatus.Idle, @@ -109,7 +109,7 @@ export const useAsyncCallback = ( }; export const useAsyncCallbackValue = ( - asyncCallback: AsyncCallback<[], TData> + asyncCallback: AsyncCallback<[], TData>, ): [AsyncState, AsyncCallback<[], TData>] => { const [state, load] = useAsyncCallback(asyncCallback); diff --git a/src/app/hooks/useAsyncSearch.ts b/src/app/hooks/useAsyncSearch.ts index 3852d3b9..8518a8bd 100644 --- a/src/app/hooks/useAsyncSearch.ts +++ b/src/app/hooks/useAsyncSearch.ts @@ -19,7 +19,7 @@ export type UseAsyncSearchOptions = AsyncSearchOption & { export type SearchItemStrGetter = ( searchItem: TSearchItem, - query: string + query: string, ) => string | string[]; export type UseAsyncSearchResult = { @@ -32,11 +32,11 @@ export type SearchResetHandler = () => void; const performMatch = ( target: string | string[], query: string, - options?: UseAsyncSearchOptions + options?: UseAsyncSearchOptions, ): string | undefined => { if (Array.isArray(target)) { const matchTarget = target.find((i) => - matchQuery(normalize(i, options?.normalizeOptions), query, options?.matchOptions) + matchQuery(normalize(i, options?.normalizeOptions), query, options?.matchOptions), ); return matchTarget ? normalize(matchTarget, options?.normalizeOptions) : undefined; } @@ -50,7 +50,7 @@ export const orderSearchItems = ( query: string, items: TSearchItem[], getItemStr: SearchItemStrGetter, - options?: UseAsyncSearchOptions + options?: UseAsyncSearchOptions, ): TSearchItem[] => { const orderedItems: TSearchItem[] = Array.from(items); @@ -107,7 +107,7 @@ export const orderSearchItems = ( export const useAsyncSearch = ( list: TSearchItem[], getItemStr: SearchItemStrGetter, - options?: UseAsyncSearchOptions + options?: UseAsyncSearchOptions, ): [UseAsyncSearchResult | undefined, AsyncSearchHandler, SearchResetHandler] => { const [result, setResult] = useState>(); @@ -135,7 +135,7 @@ export const useAsyncSearch = ( const normalizedQuery = normalize(query, options?.normalizeOptions); searchCallback(normalizedQuery); }, - [searchCallback, options?.normalizeOptions] + [searchCallback, options?.normalizeOptions], ); const resetHandler: SearchResetHandler = useCallback(() => { @@ -148,7 +148,7 @@ export const useAsyncSearch = ( // terminate any ongoing search request on unmount. terminateSearch(); }, - [terminateSearch] + [terminateSearch], ); return [result, searchHandler, resetHandler]; diff --git a/src/app/hooks/useAuthenticatedMediaUrl.ts b/src/app/hooks/useAuthenticatedMediaUrl.ts index 2fd7ae49..6fbdc706 100644 --- a/src/app/hooks/useAuthenticatedMediaUrl.ts +++ b/src/app/hooks/useAuthenticatedMediaUrl.ts @@ -12,7 +12,7 @@ import { */ export const useAuthenticatedMediaUrl = ( src: string | undefined, - useAuthentication: boolean + useAuthentication: boolean, ): string | undefined => { const mx = useMatrixClient(); const [blobUrl, setBlobUrl] = useState(() => { @@ -74,6 +74,6 @@ export const useAuthenticatedMediaFetch = () => { return src; } }, - [mx] + [mx], ); }; diff --git a/src/app/hooks/useAutoJoinSpaceRooms.ts b/src/app/hooks/useAutoJoinSpaceRooms.ts index 6cc9023c..5501450a 100644 --- a/src/app/hooks/useAutoJoinSpaceRooms.ts +++ b/src/app/hooks/useAutoJoinSpaceRooms.ts @@ -63,10 +63,7 @@ function isHierarchySpace(hierarchyRoom: IHierarchyRoom): boolean { * @param spaceId - The space room ID * @returns Array of hierarchy rooms */ -async function fetchSpaceHierarchy( - mx: MatrixClient, - spaceId: string -): Promise { +async function fetchSpaceHierarchy(mx: MatrixClient, spaceId: string): Promise { const allRooms: IHierarchyRoom[] = []; let nextBatch: string | undefined; let pageCount = 0; @@ -74,7 +71,13 @@ async function fetchSpaceHierarchy( while (pageCount < MAX_PAGES) { try { // eslint-disable-next-line no-await-in-loop - const result = await mx.getRoomHierarchy(spaceId, PER_PAGE_COUNT, undefined, false, nextBatch); + const result = await mx.getRoomHierarchy( + spaceId, + PER_PAGE_COUNT, + undefined, + false, + nextBatch, + ); allRooms.push(...result.rooms); nextBatch = result.next_batch; pageCount += 1; @@ -114,7 +117,7 @@ async function joinRoomsSequentially( mx: MatrixClient, rooms: IHierarchyRoom[], spaceId: string, - onProgress?: ProgressCallback + onProgress?: ProgressCallback, ): Promise { const spaceServer = getServerFromRoomId(spaceId); @@ -155,7 +158,7 @@ async function joinRoomsSequentially( mx, item.room_id, RoomNotificationMode.SpecialMessages, - RoomNotificationMode.Unset + RoomNotificationMode.Unset, ); } @@ -171,12 +174,12 @@ async function joinRoomsSequentially( // Join spaces first, then rooms await spacesToJoin.reduce( (promise, space) => promise.then(() => joinItem(space, true)), - Promise.resolve() + Promise.resolve(), ); await roomsToJoin.reduce( (promise, room) => promise.then(() => joinItem(room, false)), - Promise.resolve() + Promise.resolve(), ); } @@ -186,7 +189,7 @@ async function joinRoomsSequentially( export async function autoJoinSpaceChildren( mx: MatrixClient, spaceId: string, - onProgress?: ProgressCallback + onProgress?: ProgressCallback, ): Promise { if (processingSpaces.has(spaceId)) { return; @@ -237,7 +240,7 @@ export function useAutoJoinSpaceRooms(mx: MatrixClient): void { setJoiningProgress({ spaceId, progress: null }); } }, - [mx, settings.autoJoinSpaceRooms, setJoiningProgress] + [mx, settings.autoJoinSpaceRooms, setJoiningProgress], ); useEffect(() => { @@ -295,4 +298,4 @@ export function useAutoJoinOnSpaceVisit(space: Room | undefined): void { cancelled = true; }; }, [space, settings.autoJoinSpaceRooms, mx, setJoiningProgress]); -} \ No newline at end of file +} diff --git a/src/app/hooks/useBackRoute.ts b/src/app/hooks/useBackRoute.ts index 522cbd97..0de541cf 100644 --- a/src/app/hooks/useBackRoute.ts +++ b/src/app/hooks/useBackRoute.ts @@ -20,10 +20,9 @@ import { SPACE_ROOM_PATH, SPACE_SEARCH_PATH, } from '../pages/paths'; -import { ScreenSize } from './useScreenSize'; +import { ScreenSize, useScreenSizeContext } from './useScreenSize'; import { useNavigateWithTransition } from './useViewTransitions'; import { useMatrixClientOptionally } from './useMatrixClient'; -import { useScreenSizeContext } from './useScreenSize'; import { getCanonicalAliasOrRoomId, getCanonicalAliasRoomId, isRoomAlias } from '../utils/matrix'; type BackRouteContext = { @@ -73,7 +72,10 @@ export const getBackRouteTarget = ({ return listPath; } - const atLobby = matchPath({ path: SPACE_LOBBY_PATH, caseSensitive: true, end: false }, pathname); + const atLobby = matchPath( + { path: SPACE_LOBBY_PATH, caseSensitive: true, end: false }, + pathname, + ); if (atLobby) { return listPath; } @@ -83,7 +85,10 @@ export const getBackRouteTarget = ({ return listPath; } - const atSearch = matchPath({ path: SPACE_SEARCH_PATH, caseSensitive: true, end: false }, pathname); + const atSearch = matchPath( + { path: SPACE_SEARCH_PATH, caseSensitive: true, end: false }, + pathname, + ); if (atSearch) { return listPath; } diff --git a/src/app/hooks/useCategoryHandler.ts b/src/app/hooks/useCategoryHandler.ts index 086902d6..e2143df9 100644 --- a/src/app/hooks/useCategoryHandler.ts +++ b/src/app/hooks/useCategoryHandler.ts @@ -11,7 +11,7 @@ type CategoryAction = }; export const useCategoryHandler = ( setAtom: (action: CategoryAction) => void, - closed: (categoryId: string) => boolean + closed: (categoryId: string) => boolean, ) => { const handleCategoryClick: MouseEventHandler = (evt) => { const categoryId = evt.currentTarget.getAttribute('data-category-id'); diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 0b094392..91c4a824 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -231,7 +231,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const rawIds = splitWithSpace(payload); const roomIdOrAliases = rawIds.filter( - (idOrAlias) => isRoomId(idOrAlias) || isRoomAlias(idOrAlias) + (idOrAlias) => isRoomId(idOrAlias) || isRoomAlias(idOrAlias), ); roomIdOrAliases.forEach(async (idOrAlias) => { await mx.joinRoom(idOrAlias); @@ -372,7 +372,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { ...content, displayname: nick, }, - mx.getSafeUserId() + mx.getSafeUserId(), ); }, }, @@ -394,7 +394,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { ...content, avatar_url: payload, }, - mx.getSafeUserId() + mx.getSafeUserId(), ); } }, @@ -445,7 +445,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const startEventId = result.event_id; const path = `/rooms/${encodeURIComponent(room.roomId)}/context/${encodeURIComponent( - startEventId + startEventId, )}`; const eventContext = await mx.http.authedRequest(Method.Get, path, { limit: 0, @@ -459,7 +459,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { token, 20, Direction.Forward, - undefined + undefined, ); const { end, chunk } = response; // remove until the latest event; @@ -469,14 +469,14 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { (roomEvent) => (messageTypes.length > 0 ? messageTypes.includes(roomEvent.type) : true) && users.includes(roomEvent.sender) && - roomEvent.unsigned?.redacted_because === undefined + roomEvent.unsigned?.redacted_because === undefined, ); const eventIds = eventsToDelete.map((roomEvent) => roomEvent.event_id); // eslint-disable-next-line no-await-in-loop await rateLimitedActions(eventIds, (eventId) => - mx.redactEvent(room.roomId, eventId, undefined, { reason }) + mx.redactEvent(room.roomId, eventId, undefined, { reason }), ); } }, @@ -501,7 +501,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const serverAcl = getStateEvent( room, - StateEvent.RoomServerAcl + StateEvent.RoomServerAcl, )?.getContent(); const aclContent: RoomServerAclEventContent = { @@ -520,10 +520,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }); aclContent.allow = aclContent.allow?.filter( - (servername) => !removeAllowList.includes(servername) + (servername) => !removeAllowList.includes(servername), ); aclContent.deny = aclContent.deny?.filter( - (servername) => !removeDenyList.includes(servername) + (servername) => !removeDenyList.includes(servername), ); aclContent.allow?.sort(); @@ -533,7 +533,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }, }, }), - [mx, room, navigateRoom] + [mx, room, navigateRoom], ); return commands; diff --git a/src/app/hooks/useComposingCheck.ts b/src/app/hooks/useComposingCheck.ts index 687a4927..363fb7cc 100644 --- a/src/app/hooks/useComposingCheck.ts +++ b/src/app/hooks/useComposingCheck.ts @@ -13,7 +13,7 @@ export function useCompositionEndTracking(): void { (evt: TimeStamped) => { setLastCompositionEnd(evt.timeStamp); }, - [setLastCompositionEnd] + [setLastCompositionEnd], ); useEffect(() => { @@ -42,6 +42,6 @@ export function useComposingCheck({ (evt.keyCode === 229 && typeof compositionEnd !== 'undefined' && evt.timeStamp - compositionEnd < compositionEndThreshold), - [compositionEndThreshold, compositionEnd] + [compositionEndThreshold, compositionEnd], ); } diff --git a/src/app/hooks/useDateFormat.ts b/src/app/hooks/useDateFormat.ts index 520d4b0d..14ec0aba 100644 --- a/src/app/hooks/useDateFormat.ts +++ b/src/app/hooks/useDateFormat.ts @@ -30,5 +30,5 @@ export const useDateFormatItems = (): DateFormatItem[] => name: 'Custom', }, ], - [] + [], ); diff --git a/src/app/hooks/useDebounce.ts b/src/app/hooks/useDebounce.ts index 5f33976a..df48f3d2 100644 --- a/src/app/hooks/useDebounce.ts +++ b/src/app/hooks/useDebounce.ts @@ -8,7 +8,7 @@ export type DebounceCallback = (...args: T) => void; export function useDebounce( callback: DebounceCallback, - options?: DebounceOptions + options?: DebounceOptions, ): DebounceCallback { const timeoutIdRef = useRef(); const { wait, immediate } = options ?? {}; @@ -27,7 +27,7 @@ export function useDebounce( timeoutIdRef.current = undefined; }, wait); }, - [callback, wait, immediate] + [callback, wait, immediate], ); return debounceCallback; diff --git a/src/app/hooks/useDeviceList.ts b/src/app/hooks/useDeviceList.ts index f89cb3d9..a3162104 100644 --- a/src/app/hooks/useDeviceList.ts +++ b/src/app/hooks/useDeviceList.ts @@ -5,7 +5,7 @@ import { CryptoEvent, CryptoEventHandlerMap } from 'matrix-js-sdk/lib/crypto-api import { useMatrixClient } from './useMatrixClient'; export const useDeviceListChange = ( - onChange: CryptoEventHandlerMap[CryptoEvent.DevicesUpdated] + onChange: CryptoEventHandlerMap[CryptoEvent.DevicesUpdated], ) => { const mx = useMatrixClient(); useEffect(() => { @@ -46,8 +46,8 @@ export function useDeviceList(): [undefined | IMyDevice[], () => Promise] refreshDeviceList(); } }, - [mx, refreshDeviceList] - ) + [mx, refreshDeviceList], + ), ); return [deviceList ?? undefined, refreshDeviceList]; @@ -60,17 +60,17 @@ export const useDeviceIds = (devices: IMyDevice[] | undefined): string[] => { }; export const useSplitCurrentDevice = ( - devices: IMyDevice[] | undefined + devices: IMyDevice[] | undefined, ): [IMyDevice | undefined, IMyDevice[] | undefined] => { const mx = useMatrixClient(); const currentDeviceId = mx.getDeviceId(); const currentDevice = useMemo( () => devices?.find((d) => d.device_id === currentDeviceId), - [devices, currentDeviceId] + [devices, currentDeviceId], ); const otherDevices = useMemo( () => devices?.filter((device) => device.device_id !== currentDeviceId), - [devices, currentDeviceId] + [devices, currentDeviceId], ); return [currentDevice, otherDevices]; diff --git a/src/app/hooks/useDeviceVerificationStatus.ts b/src/app/hooks/useDeviceVerificationStatus.ts index 9e723bd7..01011b4f 100644 --- a/src/app/hooks/useDeviceVerificationStatus.ts +++ b/src/app/hooks/useDeviceVerificationStatus.ts @@ -17,7 +17,7 @@ export const useDeviceVerificationDetect = ( crypto: CryptoApi | undefined, userId: string, deviceId: string | undefined, - callback: (status: VerificationStatus) => void + callback: (status: VerificationStatus) => void, ): void => { const mx = useMatrixClient(); @@ -45,15 +45,15 @@ export const useDeviceVerificationDetect = ( updateStatus(); } }, - [userId, updateStatus] - ) + [userId, updateStatus], + ), ); }; export const useDeviceVerificationStatus = ( crypto: CryptoApi | undefined, userId: string, - deviceId: string | undefined + deviceId: string | undefined, ): VerificationStatus => { const [verificationStatus, setVerificationStatus] = useState(VerificationStatus.Unknown); @@ -65,7 +65,7 @@ export const useDeviceVerificationStatus = ( export const useUnverifiedDeviceCount = ( crypto: CryptoApi | undefined, userId: string, - devices: string[] + devices: string[], ): number | undefined => { const [unverifiedCount, setUnverifiedCount] = useState(); const alive = useAlive(); @@ -94,8 +94,8 @@ export const useUnverifiedDeviceCount = ( updateCount(); } }, - [userId, updateCount] - ) + [userId, updateCount], + ), ); useEffect(() => { diff --git a/src/app/hooks/useElementSizeObserver.ts b/src/app/hooks/useElementSizeObserver.ts index da563c10..d70f2f85 100644 --- a/src/app/hooks/useElementSizeObserver.ts +++ b/src/app/hooks/useElementSizeObserver.ts @@ -3,7 +3,7 @@ import { getResizeObserverEntry, useResizeObserver } from './useResizeObserver'; export const useElementSizeObserver = ( element: () => T | null, - onResize: (width: number, height: number, element: T) => void + onResize: (width: number, height: number, element: T) => void, ) => { useResizeObserver( useCallback( @@ -16,8 +16,8 @@ export const useElementSizeObserver = ( onResize(clientWidth, clientHeight, target); } }, - [element, onResize] + [element, onResize], ), - element + element, ); }; diff --git a/src/app/hooks/useEmailNotifications.ts b/src/app/hooks/useEmailNotifications.ts index 58639394..e9cf7df1 100644 --- a/src/app/hooks/useEmailNotifications.ts +++ b/src/app/hooks/useEmailNotifications.ts @@ -11,7 +11,7 @@ type EmailNotificationResult = { export const useEmailNotifications = (): [ EmailNotificationResult | undefined | null, - RefreshHandler + RefreshHandler, ] => { const mx = useMatrixClient(); @@ -26,7 +26,7 @@ export const useEmailNotifications = (): [ const pushers = (await mx.getPushers())?.pushers; const emailPusher = pushers.find( - (pusher) => pusher.app_id === 'm.email' && emailAddresses.includes(pusher.pushkey) + (pusher) => pusher.app_id === 'm.email' && emailAddresses.includes(pusher.pushkey), ); if (emailPusher?.pushkey) { @@ -40,7 +40,7 @@ export const useEmailNotifications = (): [ enabled: false, email: emailAddresses[0], }; - }, [mx]) + }, [mx]), ); if (emailState.status === AsyncStatus.Success) { diff --git a/src/app/hooks/useEmojiUsage.ts b/src/app/hooks/useEmojiUsage.ts index ddc2538a..84a9c4f7 100644 --- a/src/app/hooks/useEmojiUsage.ts +++ b/src/app/hooks/useEmojiUsage.ts @@ -54,7 +54,7 @@ export function useEmojiUsage() { await mx.setAccountData(PAARROT_EMOJI_USAGE_EVENT, currentUsage); } }, - [mx, emojiUsage] + [mx, emojiUsage], ); /** @@ -92,7 +92,7 @@ export function useEmojiUsage() { }); return entries.slice(0, count).map(([shortcode]) => shortcode); }, - [emojiUsage] + [emojiUsage], ); return { diff --git a/src/app/hooks/useFileDrop.ts b/src/app/hooks/useFileDrop.ts index f6aa29f6..c6c46a8a 100644 --- a/src/app/hooks/useFileDrop.ts +++ b/src/app/hooks/useFileDrop.ts @@ -7,12 +7,12 @@ export const useFileDropHandler = (onDrop: (file: File[]) => void): DragEventHan const files = getDataTransferFiles(evt.dataTransfer); if (files) onDrop(files); }, - [onDrop] + [onDrop], ); export const useFileDropZone = ( zoneRef: RefObject | undefined, - onDrop: (file: File[]) => void + onDrop: (file: File[]) => void, ): boolean => { const dragStateRef = useRef<'start' | 'leave' | 'over'>(); const [active, setActive] = useState(false); diff --git a/src/app/hooks/useFilePasteHandler.ts b/src/app/hooks/useFilePasteHandler.ts index d0715519..c0df2f58 100644 --- a/src/app/hooks/useFilePasteHandler.ts +++ b/src/app/hooks/useFilePasteHandler.ts @@ -29,5 +29,5 @@ export const useFilePasteHandler = (onPaste: (file: File[]) => void): ClipboardE if (clipboardImage) onPaste([clipboardImage]); }); }, - [onPaste] + [onPaste], ); diff --git a/src/app/hooks/useFilePicker.ts b/src/app/hooks/useFilePicker.ts index e772d660..43be2def 100644 --- a/src/app/hooks/useFilePicker.ts +++ b/src/app/hooks/useFilePicker.ts @@ -3,7 +3,7 @@ import { selectFile } from '../utils/dom'; export const useFilePicker = ( onSelect: (file: M extends true ? File[] : File) => void, - multiple?: M + multiple?: M, ) => useCallback( async (accept: string) => { @@ -11,5 +11,5 @@ export const useFilePicker = ( if (!file) return; onSelect(file); }, - [multiple, onSelect] + [multiple, onSelect], ); diff --git a/src/app/hooks/useForceUpdate.js b/src/app/hooks/useForceUpdate.js index bea9b3c7..82b76d45 100644 --- a/src/app/hooks/useForceUpdate.js +++ b/src/app/hooks/useForceUpdate.js @@ -1,10 +1,12 @@ -/* eslint-disable import/prefer-default-export */ import { useState } from 'react'; export function useForceUpdate() { const [data, setData] = useState(null); - return [data, function forceUpdateHook() { - setData({}); - }]; + return [ + data, + function forceUpdateHook() { + setData({}); + }, + ]; } diff --git a/src/app/hooks/useGetRoom.ts b/src/app/hooks/useGetRoom.ts index 05fcf8d3..0f78e48b 100644 --- a/src/app/hooks/useGetRoom.ts +++ b/src/app/hooks/useGetRoom.ts @@ -22,7 +22,7 @@ export const useGetRoom = (rooms: Set): GetRoomCallback => { } return undefined; }, - [mx, rooms] + [mx, rooms], ); return getRoom; diff --git a/src/app/hooks/useImagePackRooms.ts b/src/app/hooks/useImagePackRooms.ts index f04d2f22..5b1ea74b 100644 --- a/src/app/hooks/useImagePackRooms.ts +++ b/src/app/hooks/useImagePackRooms.ts @@ -5,7 +5,7 @@ import { useMatrixClient } from './useMatrixClient'; export const useImagePackRooms = ( roomId: string, - roomToParents: Map> + roomToParents: Map>, ): Room[] => { const mx = useMatrixClient(); diff --git a/src/app/hooks/useImagePacks.ts b/src/app/hooks/useImagePacks.ts index 318d6cba..000f612f 100644 --- a/src/app/hooks/useImagePacks.ts +++ b/src/app/hooks/useImagePacks.ts @@ -26,8 +26,8 @@ export const useUserImagePack = (): ImagePack | undefined => { setUserPack(getUserImagePack(mx)); } }, - [mx] - ) + [mx], + ), ); return userPack; @@ -45,8 +45,8 @@ export const useGlobalImagePacks = (): ImagePack[] => { setGlobalPacks(getGlobalImagePacks(mx)); } }, - [mx] - ) + [mx], + ), ); useStateEventCallback( @@ -59,15 +59,15 @@ export const useGlobalImagePacks = (): ImagePack[] => { if (eventType === StateEvent.PoniesRoomEmotes && roomId && typeof stateKey === 'string') { const global = !!globalPacks.find( (pack) => - pack.address && pack.address.roomId === roomId && pack.address.stateKey === stateKey + pack.address && pack.address.roomId === roomId && pack.address.stateKey === stateKey, ); if (global) { setGlobalPacks(getGlobalImagePacks(mx)); } } }, - [mx, globalPacks] - ) + [mx, globalPacks], + ), ); return globalPacks; @@ -89,8 +89,8 @@ export const useRoomImagePack = (room: Room, stateKey: string): ImagePack | unde setRoomPack(getRoomImagePack(room, stateKey)); } }, - [room, stateKey] - ) + [room, stateKey], + ), ); return roomPack; @@ -111,8 +111,8 @@ export const useRoomImagePacks = (room: Room): ImagePack[] => { setRoomPacks(getRoomImagePacks(room)); } }, - [room] - ) + [room], + ), ); return roomPacks; @@ -133,8 +133,8 @@ export const useRoomsImagePacks = (rooms: Room[]) => { setRoomPacks(rooms.flatMap(getRoomImagePacks)); } }, - [rooms] - ) + [rooms], + ), ); return roomPacks; @@ -151,7 +151,7 @@ export const useRelevantImagePacks = (usage: ImageUsage, rooms: Room[]): ImagePa const relPacks = packs.concat( globalPacks, - roomsPacks.filter((pack) => !globalPackIds.has(pack.id)) + roomsPacks.filter((pack) => !globalPackIds.has(pack.id)), ); return relPacks.filter((pack) => pack.getImages(usage).length > 0); diff --git a/src/app/hooks/useInertialHorizontalScroll.ts b/src/app/hooks/useInertialHorizontalScroll.ts index b1a18ee9..9935b4bc 100644 --- a/src/app/hooks/useInertialHorizontalScroll.ts +++ b/src/app/hooks/useInertialHorizontalScroll.ts @@ -67,12 +67,9 @@ const DEFAULT_OPTIONS: Required = { * Shared hook for drag-scrolling horizontal overflow areas with inertial momentum. */ export function useInertialHorizontalScroll( - options: UseInertialHorizontalScrollOptions = {} + options: UseInertialHorizontalScrollOptions = {}, ): UseInertialHorizontalScrollResult { - const resolvedOptions = useMemo( - () => ({ ...DEFAULT_OPTIONS, ...options }), - [options] - ); + const resolvedOptions = useMemo(() => ({ ...DEFAULT_OPTIONS, ...options }), [options]); const scrollRef = useRef(null); const stateRef = useRef({ @@ -134,23 +131,26 @@ export function useInertialHorizontalScroll( cancelAnimationFrame(animationFrameId); } }, - [] + [], ); - const scrollByStep = useCallback((direction: 1 | -1) => { - const scroll = scrollRef.current; - if (!scroll) return; + const scrollByStep = useCallback( + (direction: 1 | -1) => { + const scroll = scrollRef.current; + if (!scroll) return; - const isHorizontal = resolvedOptions.axis === 'x'; - const currentPrimary = isHorizontal ? scroll.scrollLeft : scroll.scrollTop; - const offsetSize = isHorizontal ? scroll.offsetWidth : scroll.offsetHeight; - scroll.scrollTo({ - ...(isHorizontal - ? { left: currentPrimary + offsetSize / resolvedOptions.scrollStepRatio * direction } - : { top: currentPrimary + offsetSize / resolvedOptions.scrollStepRatio * direction }), - behavior: 'smooth', - }); - }, [resolvedOptions.axis, resolvedOptions.scrollStepRatio]); + const isHorizontal = resolvedOptions.axis === 'x'; + const currentPrimary = isHorizontal ? scroll.scrollLeft : scroll.scrollTop; + const offsetSize = isHorizontal ? scroll.offsetWidth : scroll.offsetHeight; + scroll.scrollTo({ + ...(isHorizontal + ? { left: currentPrimary + (offsetSize / resolvedOptions.scrollStepRatio) * direction } + : { top: currentPrimary + (offsetSize / resolvedOptions.scrollStepRatio) * direction }), + behavior: 'smooth', + }); + }, + [resolvedOptions.axis, resolvedOptions.scrollStepRatio], + ); const stopInertia = useCallback(() => { const state = stateRef.current; @@ -193,133 +193,162 @@ export function useInertialHorizontalScroll( return; } - currentState.velocity *= Math.pow(resolvedOptions.friction, deltaMs / 16.6667); - currentState.animationFrameId = requestAnimationFrame((nextTimestamp) => step(nextTimestamp, timestamp)); + currentState.velocity *= resolvedOptions.friction ** (deltaMs / 16.6667); + currentState.animationFrameId = requestAnimationFrame((nextTimestamp) => + step(nextTimestamp, timestamp), + ); }; stopInertia(); state.animationFrameId = requestAnimationFrame((timestamp) => step(timestamp, timestamp)); - }, [resolvedOptions.axis, resolvedOptions.friction, resolvedOptions.minVelocity, stopInertia, updateScrollState]); + }, [ + resolvedOptions.axis, + resolvedOptions.friction, + resolvedOptions.minVelocity, + stopInertia, + updateScrollState, + ]); - const endDrag = useCallback((pointerId: number | null) => { - const state = stateRef.current; - if (!state.dragging) return; + const endDrag = useCallback( + (pointerId: number | null) => { + const state = stateRef.current; + if (!state.dragging) return; - const scroll = scrollRef.current; - if (scroll && pointerId !== null && scroll.hasPointerCapture(pointerId)) { - scroll.releasePointerCapture(pointerId); - } + const scroll = scrollRef.current; + if (scroll && pointerId !== null && scroll.hasPointerCapture(pointerId)) { + scroll.releasePointerCapture(pointerId); + } - if (state.moved) { - state.suppressClick = true; - startInertia(); - } + if (state.moved) { + state.suppressClick = true; + startInertia(); + } - state.dragging = false; - state.activePointerId = null; - state.moved = false; - state.velocity = 0; - setIsDragging(false); - }, [startInertia]); + state.dragging = false; + state.activePointerId = null; + state.moved = false; + state.velocity = 0; + setIsDragging(false); + }, + [startInertia], + ); - const processPointerMove = useCallback((evt: PointerLikeEvent) => { - const state = stateRef.current; - if (!state.dragging || state.activePointerId !== evt.pointerId) { - return; - } + const processPointerMove = useCallback( + (evt: PointerLikeEvent) => { + const state = stateRef.current; + if (!state.dragging || state.activePointerId !== evt.pointerId) { + return; + } - const scroll = scrollRef.current; - if (!scroll) return; - const isHorizontal = resolvedOptions.axis === 'x'; + const scroll = scrollRef.current; + if (!scroll) return; + const isHorizontal = resolvedOptions.axis === 'x'; - const currentPrimary = isHorizontal ? evt.clientX : evt.clientY; - const deltaPrimary = currentPrimary - state.startPrimary; - const now = evt.timeStamp; - const deltaTime = Math.max(now - state.lastTime, 1); - const hasExceededThreshold = Math.abs(deltaPrimary) >= resolvedOptions.dragThreshold; + const currentPrimary = isHorizontal ? evt.clientX : evt.clientY; + const deltaPrimary = currentPrimary - state.startPrimary; + const now = evt.timeStamp; + const deltaTime = Math.max(now - state.lastTime, 1); + const hasExceededThreshold = Math.abs(deltaPrimary) >= resolvedOptions.dragThreshold; - if (hasExceededThreshold) { - state.moved = true; - } + if (hasExceededThreshold) { + state.moved = true; + } - if (!state.moved) { + if (!state.moved) { + state.lastPrimary = currentPrimary; + state.lastTime = now; + return; + } + + evt.preventDefault?.(); + + if (isHorizontal) { + scroll.scrollLeft = state.startScrollPrimary - deltaPrimary; + } else { + scroll.scrollTop = state.startScrollPrimary - deltaPrimary; + } + + const rawVelocity = (currentPrimary - state.lastPrimary) / deltaTime; + state.velocity = Math.max(Math.min(rawVelocity, 2), -2); state.lastPrimary = currentPrimary; state.lastTime = now; - return; - } + }, + [resolvedOptions.axis, resolvedOptions.dragThreshold], + ); - evt.preventDefault?.(); + const handlePointerDown = useCallback( + (evt: React.PointerEvent) => { + if (evt.button !== 0) return; + if (!evt.isPrimary) return; - if (isHorizontal) { - scroll.scrollLeft = state.startScrollPrimary - deltaPrimary; - } else { - scroll.scrollTop = state.startScrollPrimary - deltaPrimary; - } + const state = stateRef.current; + if (state.dragging && state.activePointerId === evt.pointerId) return; - const rawVelocity = (currentPrimary - state.lastPrimary) / deltaTime; - state.velocity = Math.max(Math.min(rawVelocity, 2), -2); - state.lastPrimary = currentPrimary; - state.lastTime = now; - }, [resolvedOptions.axis, resolvedOptions.dragThreshold]); + const { target } = evt; + if (target instanceof Element && target.closest(TEXT_SELECTION_TARGET_SELECTOR)) { + return; + } - const handlePointerDown = useCallback((evt: React.PointerEvent) => { - if (evt.button !== 0) return; - if (!evt.isPrimary) return; + const scroll = scrollRef.current; + if (!scroll) return; + const isHorizontal = resolvedOptions.axis === 'x'; - const state = stateRef.current; - if (state.dragging && state.activePointerId === evt.pointerId) return; + stopInertia(); - const target = evt.target; - if (target instanceof Element && target.closest(TEXT_SELECTION_TARGET_SELECTOR)) { - return; - } + state.activePointerId = evt.pointerId; + state.startPrimary = isHorizontal ? evt.clientX : evt.clientY; + state.startScrollPrimary = isHorizontal ? scroll.scrollLeft : scroll.scrollTop; + state.lastPrimary = isHorizontal ? evt.clientX : evt.clientY; + state.lastTime = evt.timeStamp; + state.velocity = 0; + state.dragging = true; + state.moved = false; + state.suppressClick = false; - const scroll = scrollRef.current; - if (!scroll) return; - const isHorizontal = resolvedOptions.axis === 'x'; + try { + scroll.setPointerCapture(evt.pointerId); + } catch { + // Ignore capture failures when browser has already ended pointer interaction. + } - stopInertia(); + setIsDragging(true); + }, + [resolvedOptions.axis, stopInertia], + ); - state.activePointerId = evt.pointerId; - state.startPrimary = isHorizontal ? evt.clientX : evt.clientY; - state.startScrollPrimary = isHorizontal ? scroll.scrollLeft : scroll.scrollTop; - state.lastPrimary = isHorizontal ? evt.clientX : evt.clientY; - state.lastTime = evt.timeStamp; - state.velocity = 0; - state.dragging = true; - state.moved = false; - state.suppressClick = false; + const handlePointerMove = useCallback( + (evt: React.PointerEvent) => { + processPointerMove(evt); + }, + [processPointerMove], + ); - try { - scroll.setPointerCapture(evt.pointerId); - } catch { - // Ignore capture failures when browser has already ended pointer interaction. - } + const handlePointerUp = useCallback( + (evt: React.PointerEvent) => { + const state = stateRef.current; + if (state.activePointerId !== evt.pointerId) return; + endDrag(evt.pointerId); + }, + [endDrag], + ); - setIsDragging(true); - }, [resolvedOptions.axis, stopInertia]); + const handlePointerCancel = useCallback( + (evt: React.PointerEvent) => { + const state = stateRef.current; + if (state.activePointerId !== evt.pointerId) return; + endDrag(evt.pointerId); + }, + [endDrag], + ); - const handlePointerMove = useCallback((evt: React.PointerEvent) => { - processPointerMove(evt); - }, [processPointerMove]); - - const handlePointerUp = useCallback((evt: React.PointerEvent) => { - const state = stateRef.current; - if (state.activePointerId !== evt.pointerId) return; - endDrag(evt.pointerId); - }, [endDrag]); - - const handlePointerCancel = useCallback((evt: React.PointerEvent) => { - const state = stateRef.current; - if (state.activePointerId !== evt.pointerId) return; - endDrag(evt.pointerId); - }, [endDrag]); - - const handleLostPointerCapture = useCallback((evt: React.PointerEvent) => { - const state = stateRef.current; - if (state.activePointerId !== evt.pointerId) return; - endDrag(evt.pointerId); - }, [endDrag]); + const handleLostPointerCapture = useCallback( + (evt: React.PointerEvent) => { + const state = stateRef.current; + if (state.activePointerId !== evt.pointerId) return; + endDrag(evt.pointerId); + }, + [endDrag], + ); useEffect(() => { const handleWindowPointerMove = (evt: PointerEvent) => { @@ -399,4 +428,4 @@ export function useInertialHorizontalScroll( onClickCapture: handleClickCapture, }, }; -} \ No newline at end of file +} diff --git a/src/app/hooks/useIntersectionObserver.ts b/src/app/hooks/useIntersectionObserver.ts index 9b0b50e8..be5d175b 100644 --- a/src/app/hooks/useIntersectionObserver.ts +++ b/src/app/hooks/useIntersectionObserver.ts @@ -10,13 +10,13 @@ export type IntersectionObserverOpts = { export const getIntersectionObserverEntry = ( target: Element | Document, - entries: IntersectionObserverEntry[] + entries: IntersectionObserverEntry[], ): IntersectionObserverEntry | undefined => entries.find((entry) => entry.target === target); export const useIntersectionObserver = ( onIntersectionCallback: OnIntersectionCallback, opts?: IntersectionObserverOpts | (() => IntersectionObserverOpts), - observeElement?: Element | null | (() => Element | null) + observeElement?: Element | null | (() => Element | null), ): IntersectionObserver | undefined => { const [intersectionObserver, setIntersectionObserver] = useState(); diff --git a/src/app/hooks/useInterval.ts b/src/app/hooks/useInterval.ts index 161af394..dfc6ff9e 100644 --- a/src/app/hooks/useInterval.ts +++ b/src/app/hooks/useInterval.ts @@ -17,7 +17,7 @@ export const useInterval = (callback: IntervalCallback, ms: number): number | un () => () => { window.clearInterval(id); }, - [id] + [id], ); return id; diff --git a/src/app/hooks/useJoinedRoomId.ts b/src/app/hooks/useJoinedRoomId.ts index 08738867..bd2c4ceb 100644 --- a/src/app/hooks/useJoinedRoomId.ts +++ b/src/app/hooks/useJoinedRoomId.ts @@ -9,9 +9,7 @@ export const useJoinedRoomId = (allRooms: string[], roomIdOrAlias: string): stri const joinedRoomId = useMemo(() => { const decoded = decodeRouteParam(roomIdOrAlias) ?? roomIdOrAlias; - const roomId = isRoomAlias(decoded) - ? getCanonicalAliasRoomId(mx, decoded) - : decoded; + const roomId = isRoomAlias(decoded) ? getCanonicalAliasRoomId(mx, decoded) : decoded; if (roomId && allRooms.includes(roomId)) return roomId; return undefined; diff --git a/src/app/hooks/useKeyBackup.ts b/src/app/hooks/useKeyBackup.ts index e736e8dd..7ea12e5e 100644 --- a/src/app/hooks/useKeyBackup.ts +++ b/src/app/hooks/useKeyBackup.ts @@ -10,7 +10,7 @@ import { useMatrixClient } from './useMatrixClient'; import { useAlive } from './useAlive'; export const useKeyBackupStatusChange = ( - onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupStatus] + onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupStatus], ) => { const mx = useMatrixClient(); @@ -40,7 +40,7 @@ export const useKeyBackupStatus = (crypto: CryptoApi): boolean => { }; export const useKeyBackupSessionsRemainingChange = ( - onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupSessionsRemaining] + onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupSessionsRemaining], ) => { const mx = useMatrixClient(); @@ -53,7 +53,7 @@ export const useKeyBackupSessionsRemainingChange = ( }; export const useKeyBackupFailedChange = ( - onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupFailed] + onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupFailed], ) => { const mx = useMatrixClient(); @@ -66,7 +66,7 @@ export const useKeyBackupFailedChange = ( }; export const useKeyBackupDecryptionKeyCached = ( - onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupDecryptionKeyCached] + onChange: CryptoEventHandlerMap[CryptoEvent.KeyBackupDecryptionKeyCached], ) => { const mx = useMatrixClient(); @@ -86,7 +86,7 @@ export const useKeyBackupSync = (): [number, string | undefined] => { useCallback((count) => { setRemaining(count); setFailure(undefined); - }, []) + }, []), ); useKeyBackupFailedChange( @@ -95,7 +95,7 @@ export const useKeyBackupSync = (): [number, string | undefined] => { setFailure(f); setRemaining(0); } - }, []) + }, []), ); return [remaining, failure]; @@ -126,8 +126,8 @@ export const useKeyBackupInfo = (crypto: CryptoApi): KeyBackupInfo | undefined | fetchInfo(); } }, - [fetchInfo] - ) + [fetchInfo], + ), ); return info; @@ -135,7 +135,7 @@ export const useKeyBackupInfo = (crypto: CryptoApi): KeyBackupInfo | undefined | export const useKeyBackupTrust = ( crypto: CryptoApi, - backupInfo: KeyBackupInfo + backupInfo: KeyBackupInfo, ): BackupTrustInfo | undefined => { const alive = useAlive(); const [trust, setTrust] = useState(); diff --git a/src/app/hooks/useMarkAsRead.ts b/src/app/hooks/useMarkAsRead.ts index 5dc10812..86bc51f4 100644 --- a/src/app/hooks/useMarkAsRead.ts +++ b/src/app/hooks/useMarkAsRead.ts @@ -23,7 +23,7 @@ export function useMarkAsRead(mx: MatrixClient) { // Then send the read receipt to the server await markAsRead(mx, roomId, privateReceipt); }, - [mx, setUnreadAtom] + [mx, setUnreadAtom], ); } @@ -46,6 +46,6 @@ export function useMarkRoomsAsRead(mx: MatrixClient) { // Send read receipts to the server await Promise.all(roomIds.map((roomId) => markAsRead(mx, roomId, privateReceipt))); }, - [mx, setUnreadAtom] + [mx, setUnreadAtom], ); } diff --git a/src/app/hooks/useMatrixEventRenderer.ts b/src/app/hooks/useMatrixEventRenderer.ts index 57d56cc1..fcb942b7 100644 --- a/src/app/hooks/useMatrixEventRenderer.ts +++ b/src/app/hooks/useMatrixEventRenderer.ts @@ -14,7 +14,7 @@ export const useMatrixEventRenderer = ( typeToRenderer: EventRendererOpts, renderStateEvent?: EventRenderer, - renderEvent?: EventRenderer + renderEvent?: EventRenderer, ): RenderMatrixEvent => (eventType, isStateEvent, ...args) => { const renderer = typeToRenderer[eventType]; diff --git a/src/app/hooks/useMemberEventParser.tsx b/src/app/hooks/useMemberEventParser.tsx index a45327d6..b63898de 100644 --- a/src/app/hooks/useMemberEventParser.tsx +++ b/src/app/hooks/useMemberEventParser.tsx @@ -1,7 +1,7 @@ -import { IconSrc, Icons } from '../components/icons'; import React, { ReactNode } from 'react'; import { MatrixEvent } from 'matrix-js-sdk'; +import { IconSrc, Icons } from '../components/icons'; import { IMemberContent, Membership } from '../../types/matrix/room'; import { getMxIdLocalPart } from '../utils/matrix'; import { isMembershipChanged } from '../utils/room'; diff --git a/src/app/hooks/useMemberFilter.ts b/src/app/hooks/useMemberFilter.ts index 2c33c7c8..e34ff121 100644 --- a/src/app/hooks/useMemberFilter.ts +++ b/src/app/hooks/useMemberFilter.ts @@ -45,12 +45,12 @@ export const useMembershipFilterMenu = (): MembershipFilterItem[] => filterFn: MembershipFilter.filterBanned, }, ], - [] + [], ); export const useMembershipFilter = ( index: number, - membershipFilter: MembershipFilterItem[] + membershipFilter: MembershipFilterItem[], ): MembershipFilterItem => { const filter = membershipFilter[index] ?? membershipFilter[0]; return filter; diff --git a/src/app/hooks/useMemberPowerCompare.ts b/src/app/hooks/useMemberPowerCompare.ts index 72163edf..f8e25e1a 100644 --- a/src/app/hooks/useMemberPowerCompare.ts +++ b/src/app/hooks/useMemberPowerCompare.ts @@ -19,7 +19,7 @@ export const useMemberPowerCompare = (creators: Set, powerLevels: IPower return aPower > bPower; }, - [creators, powerLevels] + [creators, powerLevels], ); return { diff --git a/src/app/hooks/useMemberPowerTag.ts b/src/app/hooks/useMemberPowerTag.ts index 31e52aa0..361c58cd 100644 --- a/src/app/hooks/useMemberPowerTag.ts +++ b/src/app/hooks/useMemberPowerTag.ts @@ -12,7 +12,7 @@ export type GetMemberPowerTag = (userId: string) => MemberPowerTag; export const useGetMemberPowerTag = ( room: Room, creators: Set, - powerLevels: IPowerLevels + powerLevels: IPowerLevels, ) => { const creatorsTag = useRoomCreatorsTag(); const powerLevelTags = usePowerLevelTags(room, powerLevels); @@ -26,7 +26,7 @@ export const useGetMemberPowerTag = ( const power = readPowerLevel.user(powerLevels, userId); return getPowerLevelTag(powerLevelTags, power); }, - [creators, creatorsTag, powerLevels, powerLevelTags] + [creators, creatorsTag, powerLevels, powerLevelTags], ); return getMemberPowerTag; @@ -35,16 +35,16 @@ export const useGetMemberPowerTag = ( export const getPowerTagIconSrc = ( mx: MatrixClient, useAuthentication: boolean, - icon: MemberPowerTagIcon + icon: MemberPowerTagIcon, ): string | undefined => icon?.key?.startsWith('mxc://') - ? mx.mxcUrlToHttp(icon.key, 96, 96, 'scale', undefined, undefined, useAuthentication) ?? '🌻' + ? (mx.mxcUrlToHttp(icon.key, 96, 96, 'scale', undefined, undefined, useAuthentication) ?? '🌻') : icon?.key; export const useAccessiblePowerTagColors = ( themeKind: ThemeKind, creatorsTag: MemberPowerTag, - powerLevelTags: PowerLevelTags + powerLevelTags: PowerLevelTags, ): Map => { const accessibleColors: Map = useMemo(() => { const colors: Map = new Map(); @@ -67,7 +67,7 @@ export const useAccessiblePowerTagColors = ( export const useFlattenPowerTagMembers = ( members: RoomMember[], - getTag: GetMemberPowerTag + getTag: GetMemberPowerTag, ): Array => { const PLTagOrRoomMember = useMemo(() => { let prevTag: MemberPowerTag | undefined; diff --git a/src/app/hooks/useMemberSort.ts b/src/app/hooks/useMemberSort.ts index 48d2f605..73f5e2f6 100644 --- a/src/app/hooks/useMemberSort.ts +++ b/src/app/hooks/useMemberSort.ts @@ -39,7 +39,7 @@ export const useMemberSortMenu = (): MemberSortItem[] => sortFn: MemberSort.Oldest, }, ], - [] + [], ); export const useMemberSort = (index: number, memberSort: MemberSortItem[]): MemberSortItem => { @@ -49,7 +49,7 @@ export const useMemberSort = (index: number, memberSort: MemberSortItem[]): Memb export const useMemberPowerSort = ( creators: Set, - getPowerLevel: (userId: string) => number + getPowerLevel: (userId: string) => number, ): MemberSortFn => { const sort: MemberSortFn = useCallback( (a, b) => { @@ -61,7 +61,7 @@ export const useMemberPowerSort = ( return getPowerLevel(b.userId) - getPowerLevel(a.userId); }, - [creators] + [creators], ); return sort; diff --git a/src/app/hooks/useMembership.ts b/src/app/hooks/useMembership.ts index dbdd527e..0124e343 100644 --- a/src/app/hooks/useMembership.ts +++ b/src/app/hooks/useMembership.ts @@ -6,13 +6,13 @@ export const useMembership = (room: Room, userId: string): Membership => { const member = room.getMember(userId); const [membership, setMembership] = useState( - () => (member?.membership as Membership | undefined) ?? Membership.Leave + () => (member?.membership as Membership | undefined) ?? Membership.Leave, ); useEffect(() => { const handleMembershipChange: RoomMemberEventHandlerMap[RoomMemberEvent.Membership] = ( event, - m + m, ) => { if (event.getRoomId() === room.roomId && m.userId === userId) { setMembership((m.membership as Membership | undefined) ?? Membership.Leave); diff --git a/src/app/hooks/useMentionClickHandler.ts b/src/app/hooks/useMentionClickHandler.ts index 9dc81d4e..d8627005 100644 --- a/src/app/hooks/useMentionClickHandler.ts +++ b/src/app/hooks/useMentionClickHandler.ts @@ -40,7 +40,7 @@ export const useMentionClickHandler = (roomId: string): ReactEventHandler(path, { viaServers }) : path); }, - [mx, navigate, navigateRoom, navigateSpace, roomId, space, openProfile] + [mx, navigate, navigateRoom, navigateSpace, roomId, space, openProfile], ); return handleClick; diff --git a/src/app/hooks/useMessageLayout.ts b/src/app/hooks/useMessageLayout.ts index 06fb9a5d..9a124f04 100644 --- a/src/app/hooks/useMessageLayout.ts +++ b/src/app/hooks/useMessageLayout.ts @@ -22,5 +22,5 @@ export const useMessageLayoutItems = (): MessageLayoutItem[] => name: 'Bubble', }, ], - [] + [], ); diff --git a/src/app/hooks/useMessageSpacing.ts b/src/app/hooks/useMessageSpacing.ts index 62325b1e..a4b06d2a 100644 --- a/src/app/hooks/useMessageSpacing.ts +++ b/src/app/hooks/useMessageSpacing.ts @@ -34,5 +34,5 @@ export const useMessageSpacingItems = (): MessageSpacingItem[] => name: 'Large', }, ], - [] + [], ); diff --git a/src/app/hooks/useMutualRooms.ts b/src/app/hooks/useMutualRooms.ts index a7b38938..4afe4dee 100644 --- a/src/app/hooks/useMutualRooms.ts +++ b/src/app/hooks/useMutualRooms.ts @@ -22,8 +22,8 @@ export const useMutualRooms = (userId: string): AsyncState => const [mutualRoomsState] = useAsyncCallbackValue( useCallback( () => (supported ? mx._unstable_getSharedRooms(userId) : Promise.resolve([])), - [mx, userId, supported] - ) + [mx, userId, supported], + ), ); return mutualRoomsState; diff --git a/src/app/hooks/useNotificationMode.ts b/src/app/hooks/useNotificationMode.ts index df90f647..de9f039d 100644 --- a/src/app/hooks/useNotificationMode.ts +++ b/src/app/hooks/useNotificationMode.ts @@ -9,10 +9,10 @@ export enum NotificationMode { export const getNotificationMode = (actions: PushRuleAction[]): NotificationMode => { const soundTweak = actions.find( - (action) => typeof action === 'object' && action.set_tweak === TweakName.Sound + (action) => typeof action === 'object' && action.set_tweak === TweakName.Sound, ); const notify = actions.find( - (action) => typeof action === 'string' && action === PushRuleActionName.Notify + (action) => typeof action === 'string' && action === PushRuleActionName.Notify, ); if (notify && soundTweak) return NotificationMode.NotifyLoud; @@ -26,7 +26,7 @@ export type NotificationModeOptions = { }; export const getNotificationModeActions = ( mode: NotificationMode, - options?: NotificationModeOptions + options?: NotificationModeOptions, ): PushRuleAction[] => { if (mode === NotificationMode.OFF) return []; @@ -51,11 +51,11 @@ export const getNotificationModeActions = ( export type GetNotificationModeCallback = (mode: NotificationMode) => PushRuleAction[]; export const useNotificationModeActions = ( - options?: NotificationModeOptions + options?: NotificationModeOptions, ): GetNotificationModeCallback => { const getAction: GetNotificationModeCallback = useCallback( (mode) => getNotificationModeActions(mode, options), - [options] + [options], ); return getAction; diff --git a/src/app/hooks/useObjectURL.ts b/src/app/hooks/useObjectURL.ts index 8c6cf3f1..836081a3 100644 --- a/src/app/hooks/useObjectURL.ts +++ b/src/app/hooks/useObjectURL.ts @@ -10,7 +10,7 @@ export const useObjectURL = (object?: Blob): string | undefined => { () => () => { if (url) URL.revokeObjectURL(url); }, - [url] + [url], ); return url; diff --git a/src/app/hooks/usePan.ts b/src/app/hooks/usePan.ts index 60d7954f..692db515 100644 --- a/src/app/hooks/usePan.ts +++ b/src/app/hooks/usePan.ts @@ -13,7 +13,7 @@ const INITIAL_PAN = { export const usePan = (active: boolean) => { const [pan, setPan] = useState(INITIAL_PAN); const [cursor, setCursor] = useState<'grab' | 'grabbing' | 'initial'>( - active ? 'grab' : 'initial' + active ? 'grab' : 'initial', ); useEffect(() => { diff --git a/src/app/hooks/useParsedLoginFlows.ts b/src/app/hooks/useParsedLoginFlows.ts index 088a514e..8453fa93 100644 --- a/src/app/hooks/useParsedLoginFlows.ts +++ b/src/app/hooks/useParsedLoginFlows.ts @@ -3,8 +3,7 @@ import { ILoginFlow, IPasswordFlow, ISSOFlow, LoginFlow } from 'matrix-js-sdk/li export const getSSOFlow = (loginFlows: LoginFlow[]): ISSOFlow | undefined => loginFlows.find((flow) => flow.type === 'm.login.sso' || flow.type === 'm.login.cas') as - | ISSOFlow - | undefined; + ISSOFlow | undefined; export const getPasswordFlow = (loginFlows: LoginFlow[]): IPasswordFlow | undefined => loginFlows.find((flow) => flow.type === 'm.login.password') as IPasswordFlow; @@ -25,7 +24,7 @@ export const useParsedLoginFlows = (loginFlows: LoginFlow[]) => { token: getTokenFlow(loginFlows), sso: getSSOFlow(loginFlows), }), - [loginFlows] + [loginFlows], ); return parsedFlow; diff --git a/src/app/hooks/usePasswordEmail.ts b/src/app/hooks/usePasswordEmail.ts index 37e96433..36dc50d0 100644 --- a/src/app/hooks/usePasswordEmail.ts +++ b/src/app/hooks/usePasswordEmail.ts @@ -4,7 +4,7 @@ import { AsyncState, useAsyncCallback } from './useAsyncCallback'; import { RequestEmailTokenCallback, RequestEmailTokenResponse } from './types'; export const usePasswordEmail = ( - mx: MatrixClient + mx: MatrixClient, ): [AsyncState, RequestEmailTokenCallback] => { const sendAttemptRef = useRef(1); @@ -19,7 +19,7 @@ export const usePasswordEmail = ( result, }; }, - [mx] + [mx], ); const [passwordEmailState, passwordEmail] = useAsyncCallback< diff --git a/src/app/hooks/usePowerLevelTags.ts b/src/app/hooks/usePowerLevelTags.ts index 0a6cca50..829e6ea7 100644 --- a/src/app/hooks/usePowerLevelTags.ts +++ b/src/app/hooks/usePowerLevelTags.ts @@ -109,7 +109,7 @@ export const usePowerLevelTags = (room: Room, powerLevels: IPowerLevels): PowerL export const getPowerLevelTag = ( powerLevelTags: PowerLevelTags, - powerLevel: number + powerLevel: number, ): MemberPowerTag => { const tag: MemberPowerTag | undefined = powerLevelTags[powerLevel]; return tag ?? generateFallbackTag(powerLevelTags, powerLevel); diff --git a/src/app/hooks/usePowerLevels.ts b/src/app/hooks/usePowerLevels.ts index e5efddf4..ae141272 100644 --- a/src/app/hooks/usePowerLevels.ts +++ b/src/app/hooks/usePowerLevels.ts @@ -69,7 +69,7 @@ export function usePowerLevels(room: Room): IPowerLevels { const powerLevelsEvent = useStateEvent(room, StateEvent.RoomPowerLevels); const powerLevels: IPowerLevels = useMemo( () => getPowersLevelFromMatrixEvent(powerLevelsEvent), - [powerLevelsEvent] + [powerLevelsEvent], ); return powerLevels; @@ -114,8 +114,8 @@ export const useRoomsPowerLevels = (rooms: Room[]): Map => setRoomToPowerLevels(getRoomsPowerLevels()); } }, - [rooms, getRoomsPowerLevels] - ) + [rooms, getRoomsPowerLevels], + ), ); return roomToPowerLevels; @@ -171,7 +171,7 @@ export const readPowerLevel: ReadPowerLevelAPI = { export const useGetMemberPowerLevel = (powerLevels: IPowerLevels) => { const callback = useCallback( (userId?: string): number => readPowerLevel.user(powerLevels, userId), - [powerLevels] + [powerLevels], ); return callback; @@ -209,7 +209,7 @@ export type PermissionLocation = export const getPermissionPower = ( powerLevels: IPowerLevels, - location: PermissionLocation + location: PermissionLocation, ): number => { if ('user' in location) { return readPowerLevel.user(powerLevels, location.key); @@ -230,7 +230,7 @@ export const getPermissionPower = ( export const applyPermissionPower = ( powerLevels: IPowerLevels, location: PermissionLocation, - power: number + power: number, ): IPowerLevels => { if ('user' in location) { if (typeof location.key === 'string') { diff --git a/src/app/hooks/usePushRule.ts b/src/app/hooks/usePushRule.ts index ec87c217..2f3e6269 100644 --- a/src/app/hooks/usePushRule.ts +++ b/src/app/hooks/usePushRule.ts @@ -20,7 +20,7 @@ export const makePushRuleData = ( conditions?: PushRuleCondition[], pattern?: string, enabled?: boolean, - _default?: boolean + _default?: boolean, ): PushRuleData => ({ kind, pushRule: { @@ -43,7 +43,7 @@ export const orderedPushRuleKinds: PushRuleKind[] = [ export const getPushRule = ( pushRules: IPushRules, - ruleId: RuleId | string + ruleId: RuleId | string, ): PushRuleData | undefined => { const { global } = pushRules; @@ -67,5 +67,5 @@ export const getPushRule = ( export const usePushRule = ( pushRules: IPushRules, - ruleId: RuleId | string + ruleId: RuleId | string, ): PushRuleData | undefined => useMemo(() => getPushRule(pushRules, ruleId), [pushRules, ruleId]); diff --git a/src/app/hooks/useRegisterEmail.ts b/src/app/hooks/useRegisterEmail.ts index d29c9e6d..6bd1d828 100644 --- a/src/app/hooks/useRegisterEmail.ts +++ b/src/app/hooks/useRegisterEmail.ts @@ -4,7 +4,7 @@ import { AsyncState, useAsyncCallback } from './useAsyncCallback'; import { RequestEmailTokenCallback, RequestEmailTokenResponse } from './types'; export const useRegisterEmail = ( - mx: MatrixClient + mx: MatrixClient, ): [AsyncState, RequestEmailTokenCallback] => { const sendAttemptRef = useRef(1); @@ -19,7 +19,7 @@ export const useRegisterEmail = ( result, }; }, - [mx] + [mx], ); const [registerEmailState, registerEmail] = useAsyncCallback< diff --git a/src/app/hooks/useRelations.ts b/src/app/hooks/useRelations.ts index 51978de5..19364ca6 100644 --- a/src/app/hooks/useRelations.ts +++ b/src/app/hooks/useRelations.ts @@ -3,7 +3,7 @@ import { RelationsEvent, type Relations } from 'matrix-js-sdk/lib/models/relatio export const useRelations = ( relations: Relations, - getRelations: (relations: Relations) => T + getRelations: (relations: Relations) => T, ) => { const [data, setData] = useState(() => getRelations(relations)); diff --git a/src/app/hooks/useResizeObserver.ts b/src/app/hooks/useResizeObserver.ts index 707d3487..f1843546 100644 --- a/src/app/hooks/useResizeObserver.ts +++ b/src/app/hooks/useResizeObserver.ts @@ -4,12 +4,12 @@ export type OnResizeCallback = (entries: ResizeObserverEntry[]) => void; export const getResizeObserverEntry = ( target: Element, - entries: ResizeObserverEntry[] + entries: ResizeObserverEntry[], ): ResizeObserverEntry | undefined => entries.find((entry) => entry.target === target); export const useResizeObserver = ( onResizeCallback: OnResizeCallback, - observeElement?: Element | null | (() => Element | null) + observeElement?: Element | null | (() => Element | null), ): ResizeObserver => { const resizeObserver = useMemo(() => new ResizeObserver(onResizeCallback), [onResizeCallback]); diff --git a/src/app/hooks/useRestoreBackupOnVerification.ts b/src/app/hooks/useRestoreBackupOnVerification.ts index 74497b0a..627b36dc 100644 --- a/src/app/hooks/useRestoreBackupOnVerification.ts +++ b/src/app/hooks/useRestoreBackupOnVerification.ts @@ -19,6 +19,6 @@ export const useRestoreBackupOnVerification = () => { setRestoreProgress(progress); }, }); - }, [mx, setRestoreProgress]) + }, [mx, setRestoreProgress]), ); }; diff --git a/src/app/hooks/useRoomAliases.ts b/src/app/hooks/useRoomAliases.ts index 005ff0b6..18613796 100644 --- a/src/app/hooks/useRoomAliases.ts +++ b/src/app/hooks/useRoomAliases.ts @@ -11,7 +11,7 @@ import { getStateEvent } from '../utils/room'; export const usePublishedAliases = (room: Room): [string | undefined, string[]] => { const aliasContent = useStateEvent( room, - StateEvent.RoomCanonicalAlias + StateEvent.RoomCanonicalAlias, )?.getContent(); const canonicalAlias = aliasContent?.alias; @@ -38,7 +38,7 @@ export const useSetMainAlias = (room: Room): ((alias: string | undefined) => Pro async (alias: string | undefined) => { const content = getStateEvent( room, - StateEvent.RoomCanonicalAlias + StateEvent.RoomCanonicalAlias, )?.getContent(); const altAliases: string[] = []; @@ -58,14 +58,14 @@ export const useSetMainAlias = (room: Room): ((alias: string | undefined) => Pro await mx.sendStateEvent(room.roomId, StateEvent.RoomCanonicalAlias as any, newContent); }, - [mx, room] + [mx, room], ); return mainAlias; }; export const usePublishUnpublishAliases = ( - room: Room + room: Room, ): { publishAliases: (aliases: string[]) => Promise; unpublishAliases: (aliases: string[]) => Promise; @@ -75,7 +75,7 @@ export const usePublishUnpublishAliases = ( async (aliases: string[]) => { const content = getStateEvent( room, - StateEvent.RoomCanonicalAlias + StateEvent.RoomCanonicalAlias, )?.getContent(); const altAliases = content?.alt_aliases ?? []; @@ -92,14 +92,14 @@ export const usePublishUnpublishAliases = ( await mx.sendStateEvent(room.roomId, StateEvent.RoomCanonicalAlias as any, newContent); }, - [mx, room] + [mx, room], ); const unpublishAliases = useCallback( async (aliases: string[]) => { const content = getStateEvent( room, - StateEvent.RoomCanonicalAlias + StateEvent.RoomCanonicalAlias, )?.getContent(); const altAliases: string[] = []; @@ -116,7 +116,7 @@ export const usePublishUnpublishAliases = ( await mx.sendStateEvent(room.roomId, StateEvent.RoomCanonicalAlias as any, newContent); }, - [mx, room] + [mx, room], ); return { @@ -126,7 +126,7 @@ export const usePublishUnpublishAliases = ( }; export const useLocalAliases = ( - roomId: string + roomId: string, ): { localAliasesState: AsyncState; addLocalAlias: (alias: string) => Promise; @@ -139,7 +139,7 @@ export const useLocalAliases = ( useCallback(async () => { const content = await mx.getLocalAliases(roomId); return content.aliases; - }, [mx, roomId]) + }, [mx, roomId]), ); useEffect(() => { @@ -151,7 +151,7 @@ export const useLocalAliases = ( await mx.createAlias(alias, roomId); if (alive()) await loadAliases(); }, - [mx, roomId, loadAliases, alive] + [mx, roomId, loadAliases, alive], ); const removeLocalAlias = useCallback( @@ -159,7 +159,7 @@ export const useLocalAliases = ( await mx.deleteAlias(alias); if (alive()) await loadAliases(); }, - [mx, loadAliases, alive] + [mx, loadAliases, alive], ); return { diff --git a/src/app/hooks/useRoomCreators.ts b/src/app/hooks/useRoomCreators.ts index 269d11af..c6da0aed 100644 --- a/src/app/hooks/useRoomCreators.ts +++ b/src/app/hooks/useRoomCreators.ts @@ -32,7 +32,7 @@ export const useRoomCreators = (room: Room): Set => { const creators = useMemo( () => (createEvent ? getRoomCreators(createEvent) : new Set()), - [createEvent] + [createEvent], ); return creators; diff --git a/src/app/hooks/useRoomDirectoryVisibility.ts b/src/app/hooks/useRoomDirectoryVisibility.ts index 6a606013..0e93a400 100644 --- a/src/app/hooks/useRoomDirectoryVisibility.ts +++ b/src/app/hooks/useRoomDirectoryVisibility.ts @@ -10,7 +10,7 @@ export const useRoomDirectoryVisibility = (roomId: string) => { useCallback(async () => { const v = await mx.getRoomDirectoryVisibility(roomId); return v.visibility === Visibility.Public; - }, [mx, roomId]) + }, [mx, roomId]), ); useEffect(() => { @@ -21,11 +21,11 @@ export const useRoomDirectoryVisibility = (roomId: string) => { async (visibility: boolean) => { await mx.setRoomDirectoryVisibility( roomId, - visibility ? Visibility.Public : Visibility.Private + visibility ? Visibility.Public : Visibility.Private, ); await loadVisibility(); }, - [mx, roomId, loadVisibility] + [mx, roomId, loadVisibility], ); return { diff --git a/src/app/hooks/useRoomEmbedFilters.ts b/src/app/hooks/useRoomEmbedFilters.ts index 9dad47c9..b5b75ac5 100644 --- a/src/app/hooks/useRoomEmbedFilters.ts +++ b/src/app/hooks/useRoomEmbedFilters.ts @@ -51,11 +51,11 @@ const getPersonalEmbedFiltersFromRoom = (room: Room): EmbedFiltersContent => { * @returns A tuple of [filters, setFilters] */ export const useRoomEmbedFilters = ( - room: Room + room: Room, ): [EmbedFiltersContent, (filters: EmbedFiltersContent) => Promise] => { const mx = useMatrixClient(); const [filters, setFiltersState] = useState(() => - getPersonalEmbedFiltersFromRoom(room) + getPersonalEmbedFiltersFromRoom(room), ); useEffect(() => { @@ -75,7 +75,7 @@ export const useRoomEmbedFilters = ( async (newFilters: EmbedFiltersContent): Promise => { await mx.setRoomAccountData(room.roomId, EMBED_FILTERS_ACCOUNT_DATA_TYPE, newFilters); }, - [mx, room.roomId] + [mx, room.roomId], ); return [filters, setFilters]; @@ -106,7 +106,7 @@ export const useRoomWideEmbedFilters = (room: Room): EmbedFiltersContent => { * @returns Function to save room-wide filters */ export const useSetRoomWideEmbedFilters = ( - room: Room + room: Room, ): ((filters: EmbedFiltersContent) => Promise) => { const mx = useMatrixClient(); @@ -115,7 +115,7 @@ export const useSetRoomWideEmbedFilters = ( // eslint-disable-next-line @typescript-eslint/no-explicit-any await mx.sendStateEvent(room.roomId, StateEvent.RoomEmbedFilters as any, newFilters); }, - [mx, room.roomId] + [mx, room.roomId], ); return setFilters; @@ -129,7 +129,7 @@ export const useSetRoomWideEmbedFilters = ( */ export const combineEmbedFilters = ( personalFilters: EmbedFiltersContent, - roomWideFilters: EmbedFiltersContent + roomWideFilters: EmbedFiltersContent, ): string[] => { const combined = new Set([ ...personalFilters.disabledPatterns, diff --git a/src/app/hooks/useRoomEvent.ts b/src/app/hooks/useRoomEvent.ts index c2715f1f..2ed5bfd0 100644 --- a/src/app/hooks/useRoomEvent.ts +++ b/src/app/hooks/useRoomEvent.ts @@ -37,7 +37,7 @@ const useFetchEvent = (room: Room, eventId: string) => { export const useRoomEvent = ( room: Room, eventId: string, - getLocally?: () => MatrixEvent | undefined + getLocally?: () => MatrixEvent | undefined, ) => { const event = useMemo(() => { if (getLocally) return getLocally(); diff --git a/src/app/hooks/useRoomEventReaders.ts b/src/app/hooks/useRoomEventReaders.ts index 6222bf92..fa46b005 100644 --- a/src/app/hooks/useRoomEventReaders.ts +++ b/src/app/hooks/useRoomEventReaders.ts @@ -33,7 +33,7 @@ export const useRoomEventReaders = (room: Room, eventId?: string): string[] => { const handleLocalEcho: RoomEventHandlerMap[RoomEvent.LocalEchoUpdated] = ( event, r, - oldEventId + oldEventId, ) => { // update members on local event id replaced // with server generated id diff --git a/src/app/hooks/useRoomListReorder.ts b/src/app/hooks/useRoomListReorder.ts index 815a8407..2171e218 100644 --- a/src/app/hooks/useRoomListReorder.ts +++ b/src/app/hooks/useRoomListReorder.ts @@ -5,7 +5,7 @@ import { MatrixClient, MatrixEvent, Room, RoomEvent, IRoomTimelineData } from 'm * Hook that tracks timeline events across all rooms to trigger re-sorting of room lists. * Returns a counter that increments whenever a message is sent or received in any room. * This can be used as a dependency in useMemo to trigger re-sorting of room lists. - * + * * @param mx - The Matrix client instance * @param roomIds - Optional array of room IDs to track. If not provided, tracks all rooms. * @returns A number that increments on each timeline event @@ -19,18 +19,18 @@ export const useRoomListReorder = (mx: MatrixClient, roomIds?: string[]): number room: Room | undefined, toStartOfTimeline: boolean | undefined, removed: boolean, - data: IRoomTimelineData + data: IRoomTimelineData, ) => { if (!room || !data.liveEvent) return; if (toStartOfTimeline) return; - + if (roomIds && !roomIds.includes(room.roomId)) return; - + setUpdateCounter((prev) => prev + 1); }; mx.on(RoomEvent.Timeline, handleTimelineEvent); - + return () => { mx.removeListener(RoomEvent.Timeline, handleTimelineEvent); }; @@ -42,12 +42,12 @@ export const useRoomListReorder = (mx: MatrixClient, roomIds?: string[]): number /** * Hook that implements FLIP (First, Last, Invert, Play) animation for list reordering. * Tracks element positions before and after reorder, then animates the difference. - * + * * @param items - Array of item IDs in their current order * @returns Ref callback to attach to the list container */ export const useListReorderAnimation = ( - items: T[] + items: T[], ): React.RefCallback => { const positionsRef = useRef>(new Map()); const containerRef = useRef(null); @@ -59,7 +59,9 @@ export const useListReorderAnimation = ( const elements = new Map(); items.forEach((itemId) => { - const element = containerRef.current!.querySelector(`[data-room-id="${itemId}"]`) as HTMLElement; + const element = containerRef.current!.querySelector( + `[data-room-id="${itemId}"]`, + ) as HTMLElement; if (element) { currentPositions.set(itemId, element.offsetTop); elements.set(itemId, element); diff --git a/src/app/hooks/useRoomMediaEvents.ts b/src/app/hooks/useRoomMediaEvents.ts index 7b055332..455c4d38 100644 --- a/src/app/hooks/useRoomMediaEvents.ts +++ b/src/app/hooks/useRoomMediaEvents.ts @@ -1,13 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import to from 'await-to-js'; -import { - Direction, - IRoomEvent, - MatrixEvent, - MsgType, - RelationType, - Room, -} from 'matrix-js-sdk'; +import { Direction, IRoomEvent, MatrixEvent, MsgType, RelationType, Room } from 'matrix-js-sdk'; import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { useMatrixClient } from './useMatrixClient'; @@ -63,7 +56,7 @@ const toMediaItem = (mEvent: MatrixEvent): RoomMediaItem | undefined => { if (relation?.rel_type === RelationType.Replace) return undefined; const content = mEvent.getContent(); - const msgtype = content.msgtype; + const { msgtype } = content; if (msgtype !== MsgType.Image && msgtype !== MsgType.Video) return undefined; const file = content.file as IEncryptedFile | undefined; @@ -118,7 +111,7 @@ const toMediaItem = (mEvent: MatrixEvent): RoomMediaItem | undefined => { */ export const useRoomMediaEvents = (room: Room) => { const mx = useMatrixClient(); - const roomId = room.roomId; + const { roomId } = room; const cacheRef = useRef(getOrCreateCache(roomId)); if (cacheRef.current !== mediaCache.get(roomId)) { cacheRef.current = getOrCreateCache(roomId); @@ -137,7 +130,7 @@ export const useRoomMediaEvents = (room: Room) => { } return mEvent; }, - [mx] + [mx], ); const fetchPages = useCallback(async () => { @@ -149,7 +142,7 @@ export const useRoomMediaEvents = (room: Room) => { roomId, cache.nextToken, PAGE_SIZE, - Direction.Backward + Direction.Backward, ); cache.nextToken = response.end ?? null; diff --git a/src/app/hooks/useRoomNavigate.ts b/src/app/hooks/useRoomNavigate.ts index 7b73029a..fafc8044 100644 --- a/src/app/hooks/useRoomNavigate.ts +++ b/src/app/hooks/useRoomNavigate.ts @@ -33,7 +33,7 @@ export const useRoomNavigate = () => { const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, roomId); navigate(getSpacePath(roomIdOrAlias)); }, - [mx, navigate] + [mx, navigate], ); const navigateRoom = useCallback( @@ -81,7 +81,7 @@ export const useRoomNavigate = () => { navigate( getSpaceRoomPath(pSpaceIdOrAlias, openSpaceTimeline ? roomId : roomIdOrAlias, eventId), - opts + opts, ); return; } @@ -97,7 +97,7 @@ export const useRoomNavigate = () => { roomToParents, mDirects, developerTools, - ] + ], ); return { diff --git a/src/app/hooks/useRoomPermissions.ts b/src/app/hooks/useRoomPermissions.ts index cb6f69a2..de26a5a6 100644 --- a/src/app/hooks/useRoomPermissions.ts +++ b/src/app/hooks/useRoomPermissions.ts @@ -15,7 +15,7 @@ export type RoomPermissionsAPI = { export const getRoomPermissionsAPI = ( creators: Set, - powerLevels: IPowerLevels + powerLevels: IPowerLevels, ): RoomPermissionsAPI => { const api: RoomPermissionsAPI = { event: (type, userId) => { @@ -49,11 +49,11 @@ export const getRoomPermissionsAPI = ( export const useRoomPermissions = ( creators: Set, - powerLevels: IPowerLevels + powerLevels: IPowerLevels, ): RoomPermissionsAPI => { const api: RoomPermissionsAPI = useMemo( () => getRoomPermissionsAPI(creators, powerLevels), - [creators, powerLevels] + [creators, powerLevels], ); return api; diff --git a/src/app/hooks/useRoomSubRooms.ts b/src/app/hooks/useRoomSubRooms.ts index 2cdafdaa..02f591d2 100644 --- a/src/app/hooks/useRoomSubRooms.ts +++ b/src/app/hooks/useRoomSubRooms.ts @@ -13,17 +13,17 @@ export interface PaarrotSubRoomsContent { /** * Hook to get the sub-rooms (child rooms) for a given room. * Sub-rooms are stored in the room's state as im.paarrot.sub_rooms - * + * * @param room - The parent room * @returns Array of child room IDs */ export const useRoomSubRooms = (room: Room): string[] => { const subRoomsEvent = useStateEvent(room, StateEvent.PaarrotSubRooms); - + const subRooms = useMemo(() => { const content = subRoomsEvent?.getContent(); return content?.children ?? []; }, [subRoomsEvent]); - + return subRooms; }; diff --git a/src/app/hooks/useRoomTypingMembers.ts b/src/app/hooks/useRoomTypingMembers.ts index f526cbf1..3b0c3cc3 100644 --- a/src/app/hooks/useRoomTypingMembers.ts +++ b/src/app/hooks/useRoomTypingMembers.ts @@ -18,7 +18,7 @@ const equalTypingMembers = (x: TypingReceipt[], y: TypingReceipt[]): boolean => export const useRoomTypingMember = (roomId: string) => { const selector = useCallback( (roomToTyping: IRoomIdToTypingMembers) => roomToTyping.get(roomId) ?? [], - [roomId] + [roomId], ); const typing = useAtomValue(selectAtom(roomIdToTypingMembersAtom, selector, equalTypingMembers)); diff --git a/src/app/hooks/useRoomUploadFiles.ts b/src/app/hooks/useRoomUploadFiles.ts index 976a71b7..7aa02118 100644 --- a/src/app/hooks/useRoomUploadFiles.ts +++ b/src/app/hooks/useRoomUploadFiles.ts @@ -1,10 +1,7 @@ import { useCallback } from 'react'; import { useSetAtom } from 'jotai'; import { Room } from 'matrix-js-sdk'; -import { - roomIdToUploadItemsAtomFamily, - TUploadItem, -} from '../state/room/roomInputDrafts'; +import { roomIdToUploadItemsAtomFamily, TUploadItem } from '../state/room/roomInputDrafts'; import { encryptFile } from '../utils/matrix'; import { safeFile } from '../utils/mimeTypes'; import { fulfilledPromiseSettledResult } from '../utils/common'; @@ -23,7 +20,7 @@ export const useRoomUploadFiles = (room: Room) => { if (room.hasEncryptionStateEvent()) { const encryptFiles = fulfilledPromiseSettledResult( - await Promise.allSettled(safeFiles.map((f) => encryptFile(f))) + await Promise.allSettled(safeFiles.map((f) => encryptFile(f))), ); encryptFiles.forEach((ef) => fileItems.push({ @@ -31,7 +28,7 @@ export const useRoomUploadFiles = (room: Room) => { metadata: { markedAsSpoiler: false, }, - }) + }), ); } else { safeFiles.forEach((f) => @@ -42,7 +39,7 @@ export const useRoomUploadFiles = (room: Room) => { metadata: { markedAsSpoiler: false, }, - }) + }), ); } @@ -51,7 +48,7 @@ export const useRoomUploadFiles = (room: Room) => { item: fileItems, }); }, - [setSelectedFiles, room] + [setSelectedFiles, room], ); const pickFiles = useFilePicker(handleFiles, true); diff --git a/src/app/hooks/useRoomsNotificationPreferences.ts b/src/app/hooks/useRoomsNotificationPreferences.ts index a126ef97..b29d3b41 100644 --- a/src/app/hooks/useRoomsNotificationPreferences.ts +++ b/src/app/hooks/useRoomsNotificationPreferences.ts @@ -1,6 +1,6 @@ -import { Icons, IconSrc } from '../components/icons'; import { createContext, useCallback, useContext, useMemo } from 'react'; import { ConditionKind, IPushRules, MatrixClient, PushRuleKind } from 'matrix-js-sdk'; +import { Icons, IconSrc } from '../components/icons'; import { AccountDataEvent } from '../../types/matrix/accountData'; import { useAccountData } from './useAccountData'; @@ -20,7 +20,7 @@ export type RoomsNotificationPreferences = { }; const RoomsNotificationPreferencesContext = createContext( - null + null, ); export const RoomsNotificationPreferencesProvider = RoomsNotificationPreferencesContext.Provider; @@ -79,7 +79,7 @@ export enum RoomNotificationMode { export const getRoomNotificationMode = ( preferences: RoomsNotificationPreferences, - roomId: string + roomId: string, ): RoomNotificationMode => { if (preferences.mute.has(roomId)) { return RoomNotificationMode.Mute; @@ -96,7 +96,7 @@ export const getRoomNotificationMode = ( export const useRoomNotificationPreference = ( preferences: RoomsNotificationPreferences, - roomId: string + roomId: string, ): RoomNotificationMode => useMemo(() => getRoomNotificationMode(preferences, roomId), [preferences, roomId]); @@ -111,7 +111,7 @@ export const setRoomNotificationPreference = async ( mx: MatrixClient, roomId: string, mode: RoomNotificationMode, - previousMode: RoomNotificationMode + previousMode: RoomNotificationMode, ): Promise => { // remove the old preference if ( @@ -158,8 +158,8 @@ export const useSetRoomNotificationPreference = (roomId: string) => { useCallback( (mode: RoomNotificationMode, previousMode: RoomNotificationMode) => setRoomNotificationPreference(mx, roomId, mode, previousMode), - [mx, roomId] - ) + [mx, roomId], + ), ); return { diff --git a/src/app/hooks/useScreenSize.ts b/src/app/hooks/useScreenSize.ts index 3e64528d..716d5732 100644 --- a/src/app/hooks/useScreenSize.ts +++ b/src/app/hooks/useScreenSize.ts @@ -21,7 +21,7 @@ export const useScreenSize = (): ScreenSize => { useElementSizeObserver( useCallback(() => document.body, []), - useCallback((width) => setSize(getScreenSize(width)), []) + useCallback((width) => setSize(getScreenSize(width)), []), ); return size; diff --git a/src/app/hooks/useSidebarItems.ts b/src/app/hooks/useSidebarItems.ts index c5d13cc9..75ce0d17 100644 --- a/src/app/hooks/useSidebarItems.ts +++ b/src/app/hooks/useSidebarItems.ts @@ -24,7 +24,7 @@ export type InCinnySpacesContent = { export const parseSidebar = ( mx: MatrixClient, orphanSpaces: string[], - content?: InCinnySpacesContent + content?: InCinnySpacesContent, ) => { const sidebar = content?.sidebar ?? content?.shortcut ?? []; const hiddenSet = new Set(content?.hidden ?? []); @@ -76,10 +76,7 @@ export const parseSidebar = ( /** * Parse hidden spaces from account data */ -export const parseHiddenSpaces = ( - mx: MatrixClient, - content?: InCinnySpacesContent -): string[] => { +export const parseHiddenSpaces = (mx: MatrixClient, content?: InCinnySpacesContent): string[] => { const hidden = content?.hidden ?? []; return hidden.filter((spaceId) => { if (typeof spaceId !== 'string') return false; @@ -90,14 +87,14 @@ export const parseHiddenSpaces = ( }; export const useSidebarItems = ( - orphanSpaces: string[] + orphanSpaces: string[], ): [SidebarItems, Dispatch>] => { const mx = useMatrixClient(); const [sidebarItems, setSidebarItems] = useState(() => { const inCinnySpacesContent = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); return parseSidebar(mx, orphanSpaces, inCinnySpacesContent); }); @@ -105,7 +102,7 @@ export const useSidebarItems = ( useEffect(() => { const inCinnySpacesContent = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); setSidebarItems(parseSidebar(mx, orphanSpaces, inCinnySpacesContent)); }, [mx, orphanSpaces]); @@ -119,8 +116,8 @@ export const useSidebarItems = ( setSidebarItems(parseSidebar(mx, orphanSpaces, newContent)); } }, - [mx, orphanSpaces] - ) + [mx, orphanSpaces], + ), ); return [sidebarItems, setSidebarItems]; @@ -150,7 +147,7 @@ export const sidebarItemWithout = (items: SidebarItems, roomId: string) => { export const makeCinnySpacesContent = ( mx: MatrixClient, - items: SidebarItems + items: SidebarItems, ): InCinnySpacesContent => { const currentInSpaces = getAccountData(mx, AccountDataEvent.CinnySpaces)?.getContent() ?? {}; @@ -172,7 +169,7 @@ export const useHiddenSpaces = (): [string[], Dispatch> const [hiddenSpaces, setHiddenSpaces] = useState(() => { const content = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); return parseHiddenSpaces(mx, content); }); @@ -180,7 +177,7 @@ export const useHiddenSpaces = (): [string[], Dispatch> useEffect(() => { const content = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); setHiddenSpaces(parseHiddenSpaces(mx, content)); }, [mx]); @@ -194,8 +191,8 @@ export const useHiddenSpaces = (): [string[], Dispatch> setHiddenSpaces(parseHiddenSpaces(mx, newContent)); } }, - [mx] - ) + [mx], + ), ); return [hiddenSpaces, setHiddenSpaces]; @@ -204,10 +201,7 @@ export const useHiddenSpaces = (): [string[], Dispatch> /** * Create content for hiding a space */ -export const makeHideSpaceContent = ( - mx: MatrixClient, - spaceId: string -): InCinnySpacesContent => { +export const makeHideSpaceContent = (mx: MatrixClient, spaceId: string): InCinnySpacesContent => { const currentContent = getAccountData(mx, AccountDataEvent.CinnySpaces)?.getContent() ?? {}; @@ -225,10 +219,7 @@ export const makeHideSpaceContent = ( /** * Create content for unhiding a space */ -export const makeUnhideSpaceContent = ( - mx: MatrixClient, - spaceId: string -): InCinnySpacesContent => { +export const makeUnhideSpaceContent = (mx: MatrixClient, spaceId: string): InCinnySpacesContent => { const currentContent = getAccountData(mx, AccountDataEvent.CinnySpaces)?.getContent() ?? {}; @@ -275,7 +266,7 @@ export const useHomeHidden = (): [boolean, Dispatch>] => const [homeHidden, setHomeHidden] = useState(() => { const content = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); return content?.hideHome ?? false; }); @@ -283,7 +274,7 @@ export const useHomeHidden = (): [boolean, Dispatch>] => useEffect(() => { const content = getAccountData( mx, - AccountDataEvent.CinnySpaces + AccountDataEvent.CinnySpaces, )?.getContent(); setHomeHidden(content?.hideHome ?? false); }, [mx]); @@ -297,8 +288,8 @@ export const useHomeHidden = (): [boolean, Dispatch>] => setHomeHidden(newContent?.hideHome ?? false); } }, - [mx] - ) + [mx], + ), ); return [homeHidden, setHomeHidden]; diff --git a/src/app/hooks/useSpaceHierarchy.ts b/src/app/hooks/useSpaceHierarchy.ts index eae4975f..ebb12423 100644 --- a/src/app/hooks/useSpaceHierarchy.ts +++ b/src/app/hooks/useSpaceHierarchy.ts @@ -65,7 +65,7 @@ export function isHierarchySpaceRoom(room: IHierarchyRoom | undefined): boolean export async function fetchAllHierarchyRooms( mx: MatrixClient, spaceId: string, - maxDepth = 3 + maxDepth = 3, ): Promise { const allRooms: IHierarchyRoom[] = []; let nextBatch: string | undefined; @@ -84,7 +84,7 @@ const isChildSpace = ( childId: string, getRoom: GetRoomCallback, spaceRooms: Set, - hierarchySummaries: Map + hierarchySummaries: Map, ): boolean => isSpace(getRoom(childId) ?? null) || spaceRooms.has(childId) || @@ -95,7 +95,7 @@ const getChildRoomsFromSummaries = ( hierarchySummaries: Map, parentByRoomId: Map, spaceRooms: Set, - getRoom: GetRoomCallback + getRoom: GetRoomCallback, ): HierarchyItemRoom[] => { const childItems: HierarchyItemRoom[] = []; hierarchySummaries.forEach((summary, roomId) => { @@ -116,7 +116,7 @@ const getHierarchySpaces = ( rootSpaceId: string, getRoom: GetRoomCallback, spaceRooms: Set, - hierarchySummaries: Map + hierarchySummaries: Map, ): HierarchyItemSpace[] => { const rootSpaceItem: HierarchyItemSpace = { roomId: rootSpaceId, @@ -190,13 +190,13 @@ const getSpaceHierarchy = ( spaceRooms: Set, getRoom: (roomId: string) => Room | undefined, closedCategory: (spaceId: string) => boolean, - hierarchySummaries: Map + hierarchySummaries: Map, ): SpaceHierarchy[] => { const spaceItems: HierarchyItemSpace[] = getHierarchySpaces( rootSpaceId, getRoom, spaceRooms, - hierarchySummaries + hierarchySummaries, ); const parentByRoomId = buildParentByRoomId(hierarchySummaries.values()); @@ -209,7 +209,7 @@ const getSpaceHierarchy = ( hierarchySummaries, parentByRoomId, spaceRooms, - getRoom + getRoom, ); if (summaryRooms.length > 0) { return { @@ -244,7 +244,7 @@ const getSpaceHierarchy = ( hierarchySummaries, parentByRoomId, spaceRooms, - getRoom + getRoom, ); const roomIds = new Set(childItems.map((i) => i.roomId)); summaryRooms.forEach((item) => { @@ -267,19 +267,19 @@ export const useSpaceHierarchy = ( spaceRooms: Set, getRoom: (roomId: string) => Room | undefined, closedCategory: (spaceId: string) => boolean, - hierarchySummaries: Map + hierarchySummaries: Map, ): SpaceHierarchy[] => { const mx = useMatrixClient(); const roomToParents = useAtomValue(roomToParentsAtom); const [hierarchyAtom] = useState(() => - atom(getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries)) + atom(getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries)), ); const [hierarchy, setHierarchy] = useAtom(hierarchyAtom); useEffect(() => { setHierarchy( - getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries) + getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries), ); }, [mx, spaceId, spaceRooms, setHierarchy, getRoom, closedCategory, hierarchySummaries]); @@ -293,12 +293,20 @@ export const useSpaceHierarchy = ( if (spaceId === eventRoomId || getAllParents(roomToParents, eventRoomId).has(spaceId)) { setHierarchy( - getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries) + getSpaceHierarchy(spaceId, spaceRooms, getRoom, closedCategory, hierarchySummaries), ); } }, - [spaceId, roomToParents, setHierarchy, spaceRooms, getRoom, closedCategory, hierarchySummaries] - ) + [ + spaceId, + roomToParents, + setHierarchy, + spaceRooms, + getRoom, + closedCategory, + hierarchySummaries, + ], + ), ); return hierarchy; @@ -308,13 +316,13 @@ const getSpaceJoinedHierarchy = ( rootSpaceId: string, getRoom: GetRoomCallback, excludeRoom: (parentId: string, roomId: string) => boolean, - sortRoomItems: (parentId: string, items: HierarchyItem[]) => HierarchyItem[] + sortRoomItems: (parentId: string, items: HierarchyItem[]) => HierarchyItem[], ): HierarchyItem[] => { const spaceItems: HierarchyItemSpace[] = getHierarchySpaces( rootSpaceId, getRoom, new Set(), - new Map() + new Map(), ); const hierarchy: HierarchyItem[] = spaceItems.flatMap((spaceItem) => { @@ -359,7 +367,7 @@ export const useSpaceJoinedHierarchy = ( spaceId: string, getRoom: GetRoomCallback, excludeRoom: (parentId: string, roomId: string) => boolean, - sortByActivity: (spaceId: string) => boolean + sortByActivity: (spaceId: string) => boolean, ): HierarchyItem[] => { const mx = useMatrixClient(); const roomToParents = useAtomValue(roomToParentsAtom); @@ -373,11 +381,11 @@ export const useSpaceJoinedHierarchy = ( items.sort(hierarchyItemTs).sort(hierarchyItemByOrder); return items; }, - [mx, sortByActivity] + [mx, sortByActivity], ); const [hierarchyAtom] = useState(() => - atom(getSpaceJoinedHierarchy(spaceId, getRoom, excludeRoom, sortRoomItems)) + atom(getSpaceJoinedHierarchy(spaceId, getRoom, excludeRoom, sortRoomItems)), ); const [hierarchy, setHierarchy] = useAtom(hierarchyAtom); @@ -397,8 +405,8 @@ export const useSpaceJoinedHierarchy = ( setHierarchy(getSpaceJoinedHierarchy(spaceId, getRoom, excludeRoom, sortRoomItems)); } }, - [spaceId, roomToParents, setHierarchy, getRoom, excludeRoom, sortRoomItems] - ) + [spaceId, roomToParents, setHierarchy, getRoom, excludeRoom, sortRoomItems], + ), ); return hierarchy; @@ -411,7 +419,7 @@ export type FetchSpaceHierarchyLevelData = { }; export const useFetchSpaceHierarchyLevel = ( roomId: string, - enable: boolean + enable: boolean, ): FetchSpaceHierarchyLevelData => { const mx = useMatrixClient(); const pageNoRef = useRef(0); @@ -422,7 +430,7 @@ export const useFetchSpaceHierarchyLevel = ( string | undefined > = useCallback( ({ pageParam }) => mx.getRoomHierarchy(roomId, PER_PAGE_COUNT, 1, false, pageParam), - [roomId, mx] + [roomId, mx], ); const queryResponse = useInfiniteQuery({ diff --git a/src/app/hooks/useStateEvent.ts b/src/app/hooks/useStateEvent.ts index 7bc66aa2..0a29962a 100644 --- a/src/app/hooks/useStateEvent.ts +++ b/src/app/hooks/useStateEvent.ts @@ -20,13 +20,13 @@ export const useStateEvent = (room: Room, eventType: StateEvent, stateKey = '') forceUpdate(); } }, - [room, eventType, stateKey, forceUpdate] - ) + [room, eventType, stateKey, forceUpdate], + ), ); return useMemo( () => getStateEvent(room, eventType, stateKey), // eslint-disable-next-line react-hooks/exhaustive-deps - [room, eventType, stateKey, updateCount] + [room, eventType, stateKey, updateCount], ); }; diff --git a/src/app/hooks/useStateEventCallback.ts b/src/app/hooks/useStateEventCallback.ts index 85be3aeb..e378b044 100644 --- a/src/app/hooks/useStateEventCallback.ts +++ b/src/app/hooks/useStateEventCallback.ts @@ -4,7 +4,7 @@ import { useEffect } from 'react'; export type StateEventCallback = ( event: MatrixEvent, state: RoomState, - lastStateEvent: MatrixEvent | null + lastStateEvent: MatrixEvent | null, ) => void; export const useStateEventCallback = (mx: MatrixClient, onStateEvent: StateEventCallback) => { diff --git a/src/app/hooks/useStateEvents.ts b/src/app/hooks/useStateEvents.ts index dd085693..43f050b2 100644 --- a/src/app/hooks/useStateEvents.ts +++ b/src/app/hooks/useStateEvents.ts @@ -16,13 +16,13 @@ export const useStateEvents = (room: Room, eventType: StateEvent) => { forceUpdate(); } }, - [room, eventType, forceUpdate] - ) + [room, eventType, forceUpdate], + ), ); return useMemo( () => getStateEvents(room, eventType), // eslint-disable-next-line react-hooks/exhaustive-deps - [room, eventType, updateCount] + [room, eventType, updateCount], ); }; diff --git a/src/app/hooks/useSyncState.ts b/src/app/hooks/useSyncState.ts index be8a6ef2..ab488dac 100644 --- a/src/app/hooks/useSyncState.ts +++ b/src/app/hooks/useSyncState.ts @@ -3,7 +3,7 @@ import { useEffect } from 'react'; export const useSyncState = ( mx: MatrixClient | undefined, - onChange: ClientEventHandlerMap[ClientEvent.Sync] + onChange: ClientEventHandlerMap[ClientEvent.Sync], ): void => { useEffect(() => { mx?.on(ClientEvent.Sync, onChange); diff --git a/src/app/hooks/useTextAreaCodeEditor.ts b/src/app/hooks/useTextAreaCodeEditor.ts index 34c12f28..030aeda9 100644 --- a/src/app/hooks/useTextAreaCodeEditor.ts +++ b/src/app/hooks/useTextAreaCodeEditor.ts @@ -6,7 +6,7 @@ import { GetTarget } from '../plugins/text-area/type'; export const useTextAreaCodeEditor = ( textAreaRef: MutableRefObject, - intentSpaceCount: number + intentSpaceCount: number, ) => { const getTarget: GetTarget = useCallback(() => { const target = textAreaRef.current; diff --git a/src/app/hooks/useTextAreaIntent.ts b/src/app/hooks/useTextAreaIntent.ts index 113316ec..ff9256ed 100644 --- a/src/app/hooks/useTextAreaIntent.ts +++ b/src/app/hooks/useTextAreaIntent.ts @@ -5,7 +5,7 @@ import { Cursor, Intent, Operations, TextArea } from '../plugins/text-area'; export const useTextAreaIntentHandler = ( textArea: TextArea, operations: Operations, - intent: Intent + intent: Intent, ) => { const handler: KeyboardEventHandler = useCallback( (evt) => { @@ -51,7 +51,7 @@ export const useTextAreaIntentHandler = ( operations.select(intent.addPreviousLine(cursor)); } }, - [textArea, operations, intent] + [textArea, operations, intent], ); return handler; diff --git a/src/app/hooks/useTheme.ts b/src/app/hooks/useTheme.ts index 0f9e8c8e..fcf9b315 100644 --- a/src/app/hooks/useTheme.ts +++ b/src/app/hooks/useTheme.ts @@ -2,7 +2,18 @@ import { lightTheme } from 'folds'; import { atom, useAtomValue } from 'jotai'; import { createContext, useContext, useEffect, useMemo, useState } from 'react'; import { onDarkFontWeight, onLightFontWeight } from '../../config.css'; -import { butterTheme, catppuccinMochaTheme, darkTheme, discordTheme, discordDarkerTheme, mochaTheme, silverTheme, stationeryDarkTheme, stationeryTheme, twilightTheme } from '../../colors.css'; +import { + butterTheme, + catppuccinMochaTheme, + darkTheme, + discordTheme, + discordDarkerTheme, + mochaTheme, + silverTheme, + stationeryDarkTheme, + stationeryTheme, + twilightTheme, +} from '../../colors.css'; import { settingsAtom } from '../state/settings'; import { useSetting } from '../state/hooks/settings'; import { pluginRegistry } from '../features/settings/plugins/PluginAPI'; @@ -80,37 +91,54 @@ export const StationeryTheme: Theme = { export const StationeryDarkTheme: Theme = { id: 'stationery-dark-theme', kind: ThemeKind.Dark, - classNames: ['stationery-dark-theme', 'stationery', stationeryDarkTheme, onDarkFontWeight, 'prism-dark'], + classNames: [ + 'stationery-dark-theme', + 'stationery', + stationeryDarkTheme, + onDarkFontWeight, + 'prism-dark', + ], }; export const useThemes = (): Theme[] => { const [pluginThemesUpdate, setPluginThemesUpdate] = useState(0); - + // Force update when plugins change (this is a simple approach) useEffect(() => { const interval = setInterval(() => { - setPluginThemesUpdate(prev => prev + 1); + setPluginThemesUpdate((prev) => prev + 1); }, 1000); return () => clearInterval(interval); }, []); - - const builtInThemes: Theme[] = useMemo(() => [ - LightTheme, SilverTheme, StationeryTheme, StationeryDarkTheme, DarkTheme, ButterTheme, - DiscordTheme, DiscordDarkerTheme, TwilightTheme, - MochaTheme, CatppuccinMochaTheme - ], []); - + + const builtInThemes: Theme[] = useMemo( + () => [ + LightTheme, + SilverTheme, + StationeryTheme, + StationeryDarkTheme, + DarkTheme, + ButterTheme, + DiscordTheme, + DiscordDarkerTheme, + TwilightTheme, + MochaTheme, + CatppuccinMochaTheme, + ], + [], + ); + // Convert plugin themes to Theme format const pluginThemes: Theme[] = useMemo(() => { const themes = pluginRegistry.getPluginThemes(); - return themes.map(pluginTheme => ({ + return themes.map((pluginTheme) => ({ id: pluginTheme.id, kind: pluginTheme.kind === 'dark' ? ThemeKind.Dark : ThemeKind.Light, classNames: [ pluginTheme.className, pluginTheme.kind === 'dark' ? onDarkFontWeight : onLightFontWeight, - pluginTheme.kind === 'dark' ? 'prism-dark' : 'prism-light' - ] + pluginTheme.kind === 'dark' ? 'prism-dark' : 'prism-light', + ], })); }, [pluginThemesUpdate]); @@ -119,14 +147,14 @@ export const useThemes = (): Theme[] => { export const useThemeNames = (): Record => { const [pluginThemesUpdate, setPluginThemesUpdate] = useState(0); - + useEffect(() => { const interval = setInterval(() => { - setPluginThemesUpdate(prev => prev + 1); + setPluginThemesUpdate((prev) => prev + 1); }, 1000); return () => clearInterval(interval); }, []); - + return useMemo(() => { const builtInNames = { [LightTheme.id]: 'Light', @@ -141,13 +169,16 @@ export const useThemeNames = (): Record => { [MochaTheme.id]: 'Mocha', [CatppuccinMochaTheme.id]: 'Catppuccin Mocha', }; - + const pluginThemes = pluginRegistry.getPluginThemes(); - const pluginNames = pluginThemes.reduce((acc, theme) => { - acc[theme.id] = theme.name; - return acc; - }, {} as Record); - + const pluginNames = pluginThemes.reduce( + (acc, theme) => { + acc[theme.id] = theme.name; + return acc; + }, + {} as Record, + ); + return { ...builtInNames, ...pluginNames }; }, [pluginThemesUpdate]); }; @@ -155,7 +186,7 @@ export const useThemeNames = (): Record => { export const useSystemThemeKind = (): ThemeKind => { const darkModeQueryList = useMemo(() => window.matchMedia('(prefers-color-scheme: dark)'), []); const [themeKind, setThemeKind] = useState( - darkModeQueryList.matches ? ThemeKind.Dark : ThemeKind.Light + darkModeQueryList.matches ? ThemeKind.Dark : ThemeKind.Light, ); useEffect(() => { @@ -188,8 +219,8 @@ export const useActiveTheme = (): Theme => { const selectedTheme = systemThemeKind === ThemeKind.Dark - ? themes.find((theme) => theme.id === darkThemeId) ?? DarkTheme - : themes.find((theme) => theme.id === lightThemeId) ?? LightTheme; + ? (themes.find((theme) => theme.id === darkThemeId) ?? DarkTheme) + : (themes.find((theme) => theme.id === lightThemeId) ?? LightTheme); return selectedTheme; }; diff --git a/src/app/hooks/useThrottle.ts b/src/app/hooks/useThrottle.ts index 12b249f2..fd5a878f 100644 --- a/src/app/hooks/useThrottle.ts +++ b/src/app/hooks/useThrottle.ts @@ -9,7 +9,7 @@ export type ThrottleCallback = (...args: T) => void; export function useThrottle( callback: ThrottleCallback, - options?: ThrottleOptions + options?: ThrottleOptions, ): ThrottleCallback { const timeoutIdRef = useRef(); const argsRef = useRef(); @@ -34,7 +34,7 @@ export function useThrottle( timeoutIdRef.current = undefined; }, wait); }, - [callback, wait, immediate] + [callback, wait, immediate], ); return debounceCallback; diff --git a/src/app/hooks/useTimeoutToggle.ts b/src/app/hooks/useTimeoutToggle.ts index 7eda99c1..fe06fe6e 100644 --- a/src/app/hooks/useTimeoutToggle.ts +++ b/src/app/hooks/useTimeoutToggle.ts @@ -30,7 +30,7 @@ export function useTimeoutToggle(duration = 1500, initial = false): [boolean, () () => () => { clear(); }, - [] + [], ); return [active, trigger]; diff --git a/src/app/hooks/useUIAFlows.ts b/src/app/hooks/useUIAFlows.ts index 0e6c0ddc..dd94ba41 100644 --- a/src/app/hooks/useUIAFlows.ts +++ b/src/app/hooks/useUIAFlows.ts @@ -76,7 +76,7 @@ export const useUIAFlow = (authData: IAuthData, uiaFlow: UIAFlow): UIAFlowInterf const hasStage = useCallback( (stageType: string): boolean => uiaFlow.stages.includes(stageType), - [uiaFlow] + [uiaFlow], ); const getStageInfo = useCallback( @@ -85,7 +85,7 @@ export const useUIAFlow = (authData: IAuthData, uiaFlow: UIAFlow): UIAFlowInterf return params[stageType]; }, - [hasStage, params] + [hasStage, params], ); return { @@ -96,7 +96,7 @@ export const useUIAFlow = (authData: IAuthData, uiaFlow: UIAFlow): UIAFlowInterf }; export const useUIAMatrixError = ( - error?: MatrixError + error?: MatrixError, ): [undefined, undefined] | [IAuthData, undefined] | [undefined, MatrixError] => { if (!error) return [undefined, undefined]; if (error.httpStatus === 401) return [error.data as IAuthData, undefined]; diff --git a/src/app/hooks/useUserBanner.ts b/src/app/hooks/useUserBanner.ts index 05f5a784..b858c966 100644 --- a/src/app/hooks/useUserBanner.ts +++ b/src/app/hooks/useUserBanner.ts @@ -15,7 +15,7 @@ import { getProfileAssetUrl } from '../utils/profileAssetCache'; export function useUserBanner(): [ string | undefined, (banner: string | undefined) => Promise, - boolean + boolean, ] { const mx = useMatrixClient(); const [banner, setBanner] = useState(); @@ -58,7 +58,7 @@ export function useUserBanner(): [ await saveBannerUrl(mx, newBanner); setBanner(newBanner); }, - [mx] + [mx], ); return [banner, updateBanner, loading]; diff --git a/src/app/hooks/useUserCollectibles.ts b/src/app/hooks/useUserCollectibles.ts index 94deda05..7ef35d14 100644 --- a/src/app/hooks/useUserCollectibles.ts +++ b/src/app/hooks/useUserCollectibles.ts @@ -9,14 +9,19 @@ import { saveNameplate, saveProfileEffect, } from '../utils/profileFields'; -import { clearProfileCache, getCachedProfileFields, getProfileFields, registerProfileCacheListener } from '../utils/profileCache'; +import { + clearProfileCache, + getCachedProfileFields, + getProfileFields, + registerProfileCacheListener, +} from '../utils/profileCache'; import { getProfileAssetUrl } from '../utils/profileAssetCache'; import { CollectibleKind } from '../utils/discordCollectibles'; export function useUserCollectibles(): [ CollectibleProfileFields, (kind: CollectibleKind, collectible: StoredCollectible | undefined) => Promise, - boolean + boolean, ] { const mx = useMatrixClient(); const [collectibles, setCollectibles] = useState({}); @@ -61,7 +66,7 @@ export function useUserCollectibles(): [ clearProfileCache(mx.getUserId()); setCollectibles((prev) => ({ ...prev, [kind]: collectible })); }, - [mx] + [mx], ); return [collectibles, updateCollectible, loading]; diff --git a/src/app/hooks/useUserColor.ts b/src/app/hooks/useUserColor.ts index 8a6c72d7..e510035a 100644 --- a/src/app/hooks/useUserColor.ts +++ b/src/app/hooks/useUserColor.ts @@ -11,7 +11,11 @@ import { resolveColorForTheme, saveColorPreference, } from '../utils/profileFields'; -import { getCachedProfileFields, getProfileFields, registerProfileCacheListener } from '../utils/profileCache'; +import { + getCachedProfileFields, + getProfileFields, + registerProfileCacheListener, +} from '../utils/profileCache'; /** * Hook to manage the user's MSC4522 color preference on their global profile. @@ -19,7 +23,7 @@ import { getCachedProfileFields, getProfileFields, registerProfileCacheListener export function useUserColorPreference(): [ ColorPreference | undefined, (preference: ColorPreference | undefined) => Promise, - boolean + boolean, ] { const mx = useMatrixClient(); const [preference, setPreference] = useState(); @@ -63,7 +67,7 @@ export function useUserColorPreference(): [ await saveColorPreference(mx, newPreference!); setPreference(newPreference); }, - [mx] + [mx], ); return [preference, updatePreference, loading]; @@ -122,7 +126,7 @@ export function useOtherUserColorPreference(userId: string): ColorPreference | u */ export function useMemberColorPreference(userId: string, room?: Room): ColorPreference | undefined { const [preference, setPreference] = useState(() => - extractMemberColorPreference(room, userId) + extractMemberColorPreference(room, userId), ); useEffect(() => { @@ -147,7 +151,11 @@ export function useOtherUserColor(userId: string, room?: Room): string | undefin /** * Resolve the current user's username color for the active theme. */ -export function useUsernameColor(userId: string, room?: Room, themeKind?: ThemeKind): string | undefined { +export function useUsernameColor( + userId: string, + room?: Room, + themeKind?: ThemeKind, +): string | undefined { const theme = useTheme(); const kind = themeKind ?? theme.kind; const profilePreference = useOtherUserColorPreference(userId); diff --git a/src/app/hooks/useUserPresence.ts b/src/app/hooks/useUserPresence.ts index 65d40089..7d8b47dc 100644 --- a/src/app/hooks/useUserPresence.ts +++ b/src/app/hooks/useUserPresence.ts @@ -61,5 +61,5 @@ export const usePresenceLabel = (): Record => [Presence.Unavailable]: 'Busy', [Presence.Offline]: 'Away', }), - [] + [], ); diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index 1eef1dee..166b9316 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -1,7 +1,11 @@ import { useEffect, useState } from 'react'; import { UserEvent, UserEventHandlerMap } from 'matrix-js-sdk'; import { useMatrixClient } from './useMatrixClient'; -import { getCachedProfileFields, getProfileFields, registerProfileCacheListener } from '../utils/profileCache'; +import { + getCachedProfileFields, + getProfileFields, + registerProfileCacheListener, +} from '../utils/profileCache'; export type UserProfile = { avatarUrl?: string; diff --git a/src/app/hooks/useUserTrustStatusChange.ts b/src/app/hooks/useUserTrustStatusChange.ts index 56a9e385..01b32f32 100644 --- a/src/app/hooks/useUserTrustStatusChange.ts +++ b/src/app/hooks/useUserTrustStatusChange.ts @@ -3,7 +3,7 @@ import { useEffect } from 'react'; import { useMatrixClient } from './useMatrixClient'; export const useUserTrustStatusChange = ( - onChange: CryptoEventHandlerMap[CryptoEvent.UserTrustStatusChanged] + onChange: CryptoEventHandlerMap[CryptoEvent.UserTrustStatusChanged], ) => { const mx = useMatrixClient(); diff --git a/src/app/hooks/useUserTypingVerb.ts b/src/app/hooks/useUserTypingVerb.ts index 160b130a..2e78426f 100644 --- a/src/app/hooks/useUserTypingVerb.ts +++ b/src/app/hooks/useUserTypingVerb.ts @@ -18,7 +18,7 @@ import { export function useUserTypingVerb(): [ string | undefined, (verb: string | undefined) => Promise, - boolean + boolean, ] { const mx = useMatrixClient(); const [verb, setVerb] = useState(); @@ -64,7 +64,7 @@ export function useUserTypingVerb(): [ await saveTypingVerb(mx, parsed); setVerb(parsed); }, - [mx] + [mx], ); return [verb, updateVerb, loading]; diff --git a/src/app/hooks/useVerificationRequest.ts b/src/app/hooks/useVerificationRequest.ts index 5feb5232..f2eecccb 100644 --- a/src/app/hooks/useVerificationRequest.ts +++ b/src/app/hooks/useVerificationRequest.ts @@ -13,7 +13,7 @@ import { import { useMatrixClient } from './useMatrixClient'; export const useVerificationRequestReceived = ( - onRequest: CryptoEventHandlerMap[CryptoEvent.VerificationRequestReceived] + onRequest: CryptoEventHandlerMap[CryptoEvent.VerificationRequestReceived], ) => { const mx = useMatrixClient(); @@ -27,7 +27,7 @@ export const useVerificationRequestReceived = ( export const useVerificationRequestChange = ( request: VerificationRequest, - onChange: VerificationRequestEventHandlerMap[VerificationRequestEvent.Change] + onChange: VerificationRequestEventHandlerMap[VerificationRequestEvent.Change], ) => { useEffect(() => { request.on(VerificationRequestEvent.Change, onChange); @@ -44,7 +44,7 @@ export const useVerificationRequestPhase = (request: VerificationRequest): Verif request, useCallback(() => { setPhase(request.phase); - }, [request]) + }, [request]), ); return phase; @@ -52,7 +52,7 @@ export const useVerificationRequestPhase = (request: VerificationRequest): Verif export const useVerifierCancel = ( verifier: Verifier, - onCallback: VerifierEventHandlerMap[VerifierEvent.Cancel] + onCallback: VerifierEventHandlerMap[VerifierEvent.Cancel], ) => { useEffect(() => { verifier.on(VerifierEvent.Cancel, onCallback); @@ -64,7 +64,7 @@ export const useVerifierCancel = ( export const useVerifierShowSas = ( verifier: Verifier, - onCallback: VerifierEventHandlerMap[VerifierEvent.ShowSas] + onCallback: VerifierEventHandlerMap[VerifierEvent.ShowSas], ) => { useEffect(() => { verifier.on(VerifierEvent.ShowSas, onCallback); @@ -76,7 +76,7 @@ export const useVerifierShowSas = ( export const useVerifierShowReciprocateQr = ( verifier: Verifier, - onCallback: VerifierEventHandlerMap[VerifierEvent.ShowReciprocateQr] + onCallback: VerifierEventHandlerMap[VerifierEvent.ShowReciprocateQr], ) => { useEffect(() => { verifier.on(VerifierEvent.ShowReciprocateQr, onCallback); diff --git a/src/app/hooks/useViewTransitions.ts b/src/app/hooks/useViewTransitions.ts index 342456ef..e3a2c2cc 100644 --- a/src/app/hooks/useViewTransitions.ts +++ b/src/app/hooks/useViewTransitions.ts @@ -33,29 +33,29 @@ export const useViewTransitions = () => { /** * Custom navigate hook that wraps navigation in view transitions - * + * * **USAGE:** * Replace `useNavigate()` with `useNavigateWithTransition()` for smooth transitions - * + * * ```tsx * // Before: * import { useNavigate } from 'react-router-dom'; * const navigate = useNavigate(); - * + * * // After: * import { useNavigateWithTransition } from '../hooks/useViewTransitions'; * const navigate = useNavigateWithTransition(); - * + * * // Usage remains the same: * navigate('/some/path'); * navigate(-1); // Go back * ``` - * + * * This enables smooth animated transitions when navigating between: * - Different spaces * - Different rooms * - Different sections (Home, Inbox, Settings, etc.) - * + * * Falls back to instant navigation on browsers that don't support View Transitions API. */ export const useNavigateWithTransition = () => { @@ -80,6 +80,6 @@ export const useNavigateWithTransition = () => { } }); }, - [navigate] + [navigate], ); }; diff --git a/src/app/hooks/useVirtualPaginator.ts b/src/app/hooks/useVirtualPaginator.ts index cacd6b4d..c533ed26 100644 --- a/src/app/hooks/useVirtualPaginator.ts +++ b/src/app/hooks/useVirtualPaginator.ts @@ -79,7 +79,7 @@ const getDropIndex = ( range: ItemRange, dropDirection: Direction, getItemElement: (index: number) => HTMLElement | undefined, - pageThreshold = 1 + pageThreshold = 1, ): number | undefined => { const fromBackward = dropDirection === Direction.Backward; const items = fromBackward ? generateItems(range) : generateItems(range).reverse(); @@ -116,7 +116,7 @@ type RestoreAnchorData = [number | undefined, HTMLElement | undefined]; const getRestoreAnchor = ( range: ItemRange, getItemElement: (index: number) => HTMLElement | undefined, - direction: Direction + direction: Direction, ): RestoreAnchorData => { let scrollAnchorEl: HTMLElement | undefined; const scrollAnchorItem = ( @@ -146,7 +146,7 @@ const getRestoreScrollData = (scrollTop: number, restoreAnchorData: RestoreAncho const useObserveAnchorHandle = ( intersectionObserver: ReturnType, - anchorType: Direction + anchorType: Direction, ): HandleObserveAnchor => useMemo(() => { let anchor: HTMLElement | null = null; @@ -161,7 +161,7 @@ const useObserveAnchorHandle = ( }, [intersectionObserver, anchorType]); export const useVirtualPaginator = ( - options: VirtualPaginatorOptions + options: VirtualPaginatorOptions, ): VirtualPaginator => { const { count, limit, range, onRangeChange, getScrollElement, getItemElement, onEnd } = options; @@ -225,7 +225,7 @@ export const useVirtualPaginator = ( }); return true; }, - [getScrollElement] + [getScrollElement], ); const scrollToItem = useCallback( @@ -264,7 +264,7 @@ export const useVirtualPaginator = ( } return scrollToElement(itemElement, opts); }, - [getScrollElement, scrollToElement, getItemElement, onRangeChange] + [getScrollElement, scrollToElement, getItemElement, onRangeChange], ); const paginate = useCallback( @@ -282,7 +282,7 @@ export const useVirtualPaginator = ( if (scrollEl) { restoreScrollRef.current = getRestoreScrollData( scrollEl.scrollTop, - getRestoreAnchor({ start, end }, getItemElement, Direction.Backward) + getRestoreAnchor({ start, end }, getItemElement, Direction.Backward), ); } if (scrollEl) { @@ -300,7 +300,7 @@ export const useVirtualPaginator = ( if (scrollEl) { restoreScrollRef.current = getRestoreScrollData( scrollEl.scrollTop, - getRestoreAnchor({ start, end }, getItemElement, Direction.Forward) + getRestoreAnchor({ start, end }, getItemElement, Direction.Forward), ); } end = Math.min(end + currentLimit, currentCount); @@ -315,25 +315,25 @@ export const useVirtualPaginator = ( end, }); }, - [getScrollElement, getItemElement, onEnd, onRangeChange] + [getScrollElement, getItemElement, onEnd, onRangeChange], ); const handlePaginatorElIntersection: OnIntersectionCallback = useCallback( (entries) => { const anchorB = entries.find( - (entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Backward + (entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Backward, ); if (anchorB?.isIntersecting) { paginate(Direction.Backward); } const anchorF = entries.find( - (entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Forward + (entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Forward, ); if (anchorF?.isIntersecting) { paginate(Direction.Forward); } }, - [paginate] + [paginate], ); const intersectionObserver = useIntersectionObserver( @@ -342,8 +342,8 @@ export const useVirtualPaginator = ( () => ({ root: getScrollElement(), }), - [getScrollElement] - ) + [getScrollElement], + ), ); const observeBackAnchor = useObserveAnchorHandle(intersectionObserver, Direction.Backward); @@ -399,10 +399,10 @@ export const useVirtualPaginator = ( const scrollElement = getScrollElement(); if (!scrollElement) return; const backAnchor = scrollElement.querySelector( - `[${PAGINATOR_ANCHOR_ATTR}="${Direction.Backward}"]` + `[${PAGINATOR_ANCHOR_ATTR}="${Direction.Backward}"]`, ) as HTMLElement | null; const frontAnchor = scrollElement.querySelector( - `[${PAGINATOR_ANCHOR_ATTR}="${Direction.Forward}"]` + `[${PAGINATOR_ANCHOR_ATTR}="${Direction.Forward}"]`, ) as HTMLElement | null; if (backAnchor && isIntersectingScrollView(scrollElement, backAnchor)) { diff --git a/src/app/paarrot-api.ts b/src/app/paarrot-api.ts index 33084ca1..6d083400 100644 --- a/src/app/paarrot-api.ts +++ b/src/app/paarrot-api.ts @@ -1,9 +1,9 @@ /** * Paarrot API Handler - * + * * This module handles API actions from the Electron API server. * It receives actions via IPC and executes them on the Matrix client. - * + * * To use this, import and call initPaarrotAPI() early in your app initialization. */ @@ -76,102 +76,100 @@ export function initPaarrotAPI(matrixClient: MatrixClient) { console.log('Paarrot API: Initializing API handler'); // Listen for API actions from the Electron API server - (window as any).electron.api.onAction(async (action: { - action: string; - params: any; - responseChannel: string; - }) => { - console.log('Paarrot API: Received action:', action.action, action.params); + (window as any).electron.api.onAction( + async (action: { action: string; params: any; responseChannel: string }) => { + console.log('Paarrot API: Received action:', action.action, action.params); - try { - let result; + try { + let result; - switch (action.action) { - case 'get-status': - result = await getStatus(matrixClient); - break; + switch (action.action) { + case 'get-status': + result = await getStatus(matrixClient); + break; - case 'toggle-mute': - result = await toggleMute(matrixClient); - break; + case 'toggle-mute': + result = await toggleMute(matrixClient); + break; - case 'set-mute': - result = await setMute(matrixClient, action.params.muted); - break; + case 'set-mute': + result = await setMute(matrixClient, action.params.muted); + break; - case 'toggle-deafen': - result = await toggleDeafen(matrixClient); - break; + case 'toggle-deafen': + result = await toggleDeafen(matrixClient); + break; - case 'set-deafen': - result = await setDeafen(matrixClient, action.params.deafened); - break; + case 'set-deafen': + result = await setDeafen(matrixClient, action.params.deafened); + break; - case 'change-channel': - result = await changeChannel(matrixClient, action.params.roomId); - break; + case 'change-channel': + result = await changeChannel(matrixClient, action.params.roomId); + break; - case 'get-channels': - result = await getChannels(matrixClient); - break; + case 'get-channels': + result = await getChannels(matrixClient); + break; - case 'send-message': - result = await sendMessage(matrixClient, action.params.roomId, action.params.message); - break; + case 'send-message': + result = await sendMessage(matrixClient, action.params.roomId, action.params.message); + break; - case 'send-message-current': - result = await sendMessageCurrent(matrixClient, action.params.message); - break; + case 'send-message-current': + result = await sendMessageCurrent(matrixClient, action.params.message); + break; - case 'get-current-room': - result = await getCurrentRoom(matrixClient); - break; + case 'get-current-room': + result = await getCurrentRoom(matrixClient); + break; - case 'get-messages-groups': - result = await getMessagesByScope(matrixClient, 'groups', action.params.limit); - break; + case 'get-messages-groups': + result = await getMessagesByScope(matrixClient, 'groups', action.params.limit); + break; - case 'get-messages-dms': - result = await getMessagesByScope(matrixClient, 'dms', action.params.limit); - break; + case 'get-messages-dms': + result = await getMessagesByScope(matrixClient, 'dms', action.params.limit); + break; - case 'get-messages-combined': - result = await getMessagesByScope(matrixClient, 'combined', action.params.limit); - break; + case 'get-messages-combined': + result = await getMessagesByScope(matrixClient, 'combined', action.params.limit); + break; - case 'get-unreads-groups': - result = await getUnreadsByScope(matrixClient, 'groups'); - break; + case 'get-unreads-groups': + result = await getUnreadsByScope(matrixClient, 'groups'); + break; - case 'get-unreads-dms': - result = await getUnreadsByScope(matrixClient, 'dms'); - break; + case 'get-unreads-dms': + result = await getUnreadsByScope(matrixClient, 'dms'); + break; - case 'get-unreads-combined': - result = await getUnreadsByScope(matrixClient, 'combined'); - break; + case 'get-unreads-combined': + result = await getUnreadsByScope(matrixClient, 'combined'); + break; - default: - throw new Error(`Unknown action: ${action.action}`); + default: + throw new Error(`Unknown action: ${action.action}`); + } + + // Send success response back + (window as any).electron.api.sendResponse(action.responseChannel, { + success: true, + data: result, + }); + + console.log('Paarrot API: Action completed successfully:', action.action); + } catch (error: any) { + console.error('Paarrot API: Action failed:', action.action, error); + + // Send error response back + (window as any).electron.api.sendResponse(action.responseChannel, { + success: false, + error: error.message || 'Unknown error', + }); } - - // Send success response back - (window as any).electron.api.sendResponse(action.responseChannel, { - success: true, - data: result, - }); - - console.log('Paarrot API: Action completed successfully:', action.action); - } catch (error: any) { - console.error('Paarrot API: Action failed:', action.action, error); - - // Send error response back - (window as any).electron.api.sendResponse(action.responseChannel, { - success: false, - error: error.message || 'Unknown error', - }); - } - }); + }, + ); console.log('Paarrot API: Handler initialized'); } @@ -181,11 +179,11 @@ export function initPaarrotAPI(matrixClient: MatrixClient) { */ async function getStatus(matrixClient: MatrixClient) { const currentRoom = getCurrentRoomId(); - + // Get actual mute/deafen state from CallService if available const callService = getCallService(); const activeCall = callService?.getActiveCall(); - + return { muted: activeCall?.isMuted ?? false, deafened: activeCall?.isDeafened ?? false, @@ -200,14 +198,14 @@ async function getStatus(matrixClient: MatrixClient) { */ async function toggleMute(matrixClient: MatrixClient) { const callService = getCallService(); - + if (!callService) { return { muted: false, message: 'CallService not initialized - no active call', }; } - + const activeCall = callService.getActiveCall(); if (!activeCall) { return { @@ -215,10 +213,10 @@ async function toggleMute(matrixClient: MatrixClient) { message: 'No active call to mute/unmute', }; } - + // Toggle mute state const newMuteState = callService.toggleMute(); - + return { muted: newMuteState, }; @@ -229,14 +227,14 @@ async function toggleMute(matrixClient: MatrixClient) { */ async function setMute(matrixClient: MatrixClient, muted: boolean) { const callService = getCallService(); - + if (!callService) { return { muted, message: 'CallService not initialized - no active call', }; } - + const activeCall = callService.getActiveCall(); if (!activeCall) { return { @@ -244,12 +242,12 @@ async function setMute(matrixClient: MatrixClient, muted: boolean) { message: 'No active call to mute/unmute', }; } - + // Set mute to desired state if it's different if (activeCall.isMuted !== muted) { callService.toggleMute(); } - + return { muted, }; @@ -260,14 +258,14 @@ async function setMute(matrixClient: MatrixClient, muted: boolean) { */ async function toggleDeafen(matrixClient: MatrixClient) { const callService = getCallService(); - + if (!callService) { return { deafened: false, message: 'CallService not initialized - no active call', }; } - + const activeCall = callService.getActiveCall(); if (!activeCall) { return { @@ -275,10 +273,10 @@ async function toggleDeafen(matrixClient: MatrixClient) { message: 'No active call to deafen/undeafen', }; } - + // Toggle deafen state const newDeafenState = callService.toggleDeafen(); - + return { deafened: newDeafenState, }; @@ -289,14 +287,14 @@ async function toggleDeafen(matrixClient: MatrixClient) { */ async function setDeafen(matrixClient: MatrixClient, deafened: boolean) { const callService = getCallService(); - + if (!callService) { return { deafened, message: 'CallService not initialized - no active call', }; } - + const activeCall = callService.getActiveCall(); if (!activeCall) { return { @@ -304,12 +302,12 @@ async function setDeafen(matrixClient: MatrixClient, deafened: boolean) { message: 'No active call to deafen/undeafen', }; } - + // Set deafen to desired state if it's different if (activeCall.isDeafened !== deafened) { callService.toggleDeafen(); } - + return { deafened, }; @@ -325,7 +323,9 @@ async function changeChannel(matrixClient: any, roomId: string) { } if (!navigateFunction) { - throw new Error('Navigate function not registered. Call setPaarrotNavigate from your router setup.'); + throw new Error( + 'Navigate function not registered. Call setPaarrotNavigate from your router setup.', + ); } // Determine the appropriate path based on room type @@ -334,7 +334,7 @@ async function changeChannel(matrixClient: any, roomId: string) { // Check if it's a direct message const isDirect = room.guessDMUserId() !== null; - + if (isDirect) { // Navigate to direct message path = getDirectRoomPath(roomIdOrAlias); @@ -368,11 +368,11 @@ async function getChannels(matrixClient: any) { // Extract server domain from roomId (!localpart:domain.tld) const serverMatch = room.roomId.match(/:(.+)$/); const server = serverMatch ? serverMatch[1] : null; - + return { roomId: room.roomId, name: room.name || 'Unnamed Room', - server: server, + server, isDirect: room.getMyMembership() === 'invite' ? false : room.guessDMUserId() !== null, avatar: room.getMxcAvatarUrl() || null, }; @@ -435,7 +435,7 @@ async function getCurrentRoom(matrixClient: any) { return { roomId: room.roomId, name: room.name || 'Unnamed Room', - server: server, + server, avatar: room.getMxcAvatarUrl() || null, isDirect: room.guessDMUserId() !== null, }; @@ -466,7 +466,7 @@ function parseMessageLimit(limit?: number | string): number { const parsedLimit = Number(limit); return Math.min( Math.max(Number.isFinite(parsedLimit) ? Math.floor(parsedLimit) : DEFAULT_MESSAGE_LIMIT, 1), - MAX_MESSAGE_LIMIT + MAX_MESSAGE_LIMIT, ); } @@ -477,7 +477,7 @@ function parseMessageLimit(limit?: number | string): number { function collectRecentMessages(room: any, limit: number): ApiMessage[] { const liveEvents = room.getLiveTimeline?.()?.getEvents?.() ?? []; const isDirect = isDirectRoom(room); - const roomId = room.roomId; + const { roomId } = room; const roomName = room.name || 'Unnamed Room'; const messages: ApiMessage[] = []; @@ -533,7 +533,7 @@ function collectRecentMessages(room: any, limit: number): ApiMessage[] { function getRoomsForScope(matrixClient: any, scope: MessageScope) { const rooms = (matrixClient?.getRooms?.() || []).filter( - (room: any) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join' + (room: any) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join', ); if (scope === 'groups') { @@ -548,11 +548,7 @@ function getRoomsForScope(matrixClient: any, scope: MessageScope) { /** * Get recent messages across groups, DMs, or both (combined). */ -async function getMessagesByScope( - matrixClient: any, - scope: MessageScope, - limit?: number | string -) { +async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit?: number | string) { const limitNum = parseMessageLimit(limit); const rooms = getRoomsForScope(matrixClient, scope); @@ -650,8 +646,8 @@ function getCurrentRoomId(): string | null { try { // Get the pathname from URL // Support both normal routing and hash routing - let pathname = window.location.pathname; - + let { pathname } = window.location; + // If using hash router, parse from hash if (window.location.hash) { const hashMatch = window.location.hash.match(/#(.+)/); @@ -659,19 +655,19 @@ function getCurrentRoomId(): string | null { pathname = hashMatch[1]; } } - + // URL patterns: // /home/:roomIdOrAlias/:eventId?/ // /direct/:roomIdOrAlias/:eventId?/ // /:spaceIdOrAlias/:roomIdOrAlias/:eventId?/ - + // Try to match room patterns const patterns = [ /^\/home\/([^/]+)/, // /home/:roomIdOrAlias /^\/direct\/([^/]+)/, // /direct/:roomIdOrAlias /^\/[^/]+\/([^/]+)/, // /:spaceIdOrAlias/:roomIdOrAlias (space rooms) ]; - + for (const pattern of patterns) { const match = pathname.match(pattern); if (match && match[1]) { @@ -679,7 +675,7 @@ function getCurrentRoomId(): string | null { return decodeURIComponent(match[1]); } } - + return null; } catch (error) { console.error('Paarrot API: Error getting current room ID:', error); diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index 07ce3e3a..64e390a9 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -42,7 +42,12 @@ import { import { ClientBindAtoms, ClientLayout, ClientRoot } from './client'; import { Home, HomeRouteRoomProvider, HomeSearch } from './client/home'; import { Direct, DirectCreate, DirectRouteRoomProvider, DirectSearch } from './client/direct'; -import { RouteSpaceProvider, SpaceRouteRoomProvider, SpaceSearch, SpaceIndexRedirect } from './client/space'; +import { + RouteSpaceProvider, + SpaceRouteRoomProvider, + SpaceSearch, + SpaceIndexRedirect, +} from './client/space'; import { ForumAwareSpaceLayout } from '../features/forum/ForumAwareSpaceLayout'; import { ForumFeedPage } from '../features/forum/ForumFeedPage'; import { Explore, FeaturedRooms, PublicRooms } from './client/explore'; @@ -109,24 +114,24 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) const addingAccount = url.searchParams.get('add-account') === 'true'; const session = getCurrentSession(); const hasSession = !!session; - + // Log to localStorage for persistence across reloads const debugInfo = { timestamp: new Date().toISOString(), - url: url.toString(), + url: url.toString(), pathname: url.pathname, search: url.search, hash: url.hash, - addingAccount, + addingAccount, hasSession, - willRedirect: hasSession && !addingAccount + willRedirect: hasSession && !addingAccount, }; console.log('[Router] Auth loader:', debugInfo); const debugLog = JSON.parse(localStorage.getItem('debug-router-logs') || '[]'); debugLog.push(debugInfo); if (debugLog.length > 10) debugLog.shift(); // Keep last 10 localStorage.setItem('debug-router-logs', JSON.stringify(debugLog)); - + if (session && !addingAccount) { console.log('[Router] Redirecting to last seen channel for existing session'); return redirect(getStartupPath(session.userId)); @@ -151,7 +156,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) if (!getCurrentSession()) { const afterLoginPath = getAppPathFromHref( getOriginBaseUrl(hashRouter), - window.location.href + window.location.href, ); if (afterLoginPath) setAfterLoginRedirectPath(afterLoginPath); return redirect(getLoginPath()); @@ -317,7 +322,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) Page not found

} /> -
+ , ); if (hashRouter?.enabled) { diff --git a/src/app/pages/auth/AuthFooter.tsx b/src/app/pages/auth/AuthFooter.tsx index 3fb7ec2a..10aa2ae2 100644 --- a/src/app/pages/auth/AuthFooter.tsx +++ b/src/app/pages/auth/AuthFooter.tsx @@ -5,7 +5,13 @@ import * as css from './styles.css'; export function AuthFooter() { return ( - + About { @@ -102,7 +102,7 @@ export function AuthLayout() { generatePath(currentAuthPath(location.pathname), { server, }) + location.search, - { replace: true } + { replace: true }, ); } }, [urlEncodedServer, navigate, location, server]); @@ -115,10 +115,10 @@ export function AuthLayout() { return; } navigate( - generatePath(currentAuthPath(location.pathname), { server: newServer }) + location.search + generatePath(currentAuthPath(location.pathname), { server: newServer }) + location.search, ); }, - [navigate, location, discoveryState, server, discoverServer] + [navigate, location, discoveryState, server, discoverServer], ); const [autoDiscoveryError, autoDiscoveryInfo] = diff --git a/src/app/pages/auth/FiledError.tsx b/src/app/pages/auth/FiledError.tsx index 5cd5bdb0..5f9d6d65 100644 --- a/src/app/pages/auth/FiledError.tsx +++ b/src/app/pages/auth/FiledError.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { Box, color, Text } from 'folds'; import { Icon, Icons } from '../../components/icons'; + export function FieldError({ message }: { message: string }) { return ( diff --git a/src/app/pages/auth/SSOLogin.tsx b/src/app/pages/auth/SSOLogin.tsx index 8942068f..be3cf680 100644 --- a/src/app/pages/auth/SSOLogin.tsx +++ b/src/app/pages/auth/SSOLogin.tsx @@ -44,12 +44,12 @@ export function SSOLogin({ providers, redirectUrl, action, saveScreenSpace }: SS setLaunchingProviderId(null); } }, - [getSSOIdUrl, launchingProviderId] + [getSSOIdUrl, launchingProviderId], ); const withoutIcon = providers ? providers.find( - (provider) => !provider.icon || !mx.mxcUrlToHttp(provider.icon, 96, 96, 'crop', false) + (provider) => !provider.icon || !mx.mxcUrlToHttp(provider.icon, 96, 96, 'crop', false), ) : true; diff --git a/src/app/pages/auth/ServerPicker.tsx b/src/app/pages/auth/ServerPicker.tsx index 1e67cf80..a2067d6c 100644 --- a/src/app/pages/auth/ServerPicker.tsx +++ b/src/app/pages/auth/ServerPicker.tsx @@ -8,8 +8,8 @@ import React, { useState, } from 'react'; import { Header, IconButton, Input, Menu, MenuItem, PopOut, RectCords, Text, config } from 'folds'; -import { Icon, Icons } from '../../components/icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../components/icons'; import { useDebounce } from '../../hooks/useDebounce'; import { stopPropagation } from '../../utils/keyboard'; diff --git a/src/app/pages/auth/login/Login.tsx b/src/app/pages/auth/login/Login.tsx index 2f04a733..02a2a6df 100644 --- a/src/app/pages/auth/login/Login.tsx +++ b/src/app/pages/auth/login/Login.tsx @@ -31,7 +31,7 @@ const useLoginSearchParams = (searchParams: URLSearchParams): LoginPathSearchPar email: searchParams.get('email') ?? undefined, loginToken: searchParams.get('loginToken') ?? undefined, }), - [searchParams] + [searchParams], ); export function Login() { @@ -48,7 +48,7 @@ export function Login() { window.location.replace( withSearchParam(absoluteLoginPath, { loginToken: loginTokenForHashRouter, - }) + }), ); } diff --git a/src/app/pages/auth/login/PasswordLoginForm.tsx b/src/app/pages/auth/login/PasswordLoginForm.tsx index 96d659d5..9b96821a 100644 --- a/src/app/pages/auth/login/PasswordLoginForm.tsx +++ b/src/app/pages/auth/login/PasswordLoginForm.tsx @@ -1,9 +1,24 @@ import React, { FormEventHandler, MouseEventHandler, useCallback, useState } from 'react'; -import { Box, Button, Header, IconButton, Input, Menu, Overlay, OverlayBackdrop, OverlayCenter, PopOut, RectCords, Spinner, Text, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Button, + Header, + IconButton, + Input, + Menu, + Overlay, + OverlayBackdrop, + OverlayCenter, + PopOut, + RectCords, + Spinner, + Text, + config, +} from 'folds'; import FocusTrap from 'focus-trap-react'; import { Link } from 'react-router-dom'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../../utils/matrix'; import { EMAIL_REGEX } from '../../../utils/regex'; import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo'; diff --git a/src/app/pages/auth/login/TokenLogin.tsx b/src/app/pages/auth/login/TokenLogin.tsx index f4590e34..d6f4e81d 100644 --- a/src/app/pages/auth/login/TokenLogin.tsx +++ b/src/app/pages/auth/login/TokenLogin.tsx @@ -1,7 +1,7 @@ import { Box, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, color, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import React, { useCallback, useEffect } from 'react'; import { MatrixError } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { CustomLoginResponse, LoginError, login, useLoginComplete } from './loginUtil'; diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index 45f381c1..5a336222 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -12,7 +12,10 @@ import { import { getHomePath } from '../../pathUtils'; import { getLastActivePath } from '../../../state/lastActivePath'; import { setFallbackSession } from '../../../state/sessions'; -import { getLocalStorageItem, setLocalStorageItem } from '../../../state/utils/atomWithLocalStorage'; +import { + getLocalStorageItem, + setLocalStorageItem, +} from '../../../state/utils/atomWithLocalStorage'; export enum GetBaseUrlError { NotAllow = 'NotAllow', @@ -61,7 +64,7 @@ export type CustomLoginResponse = { }; export const login = async ( serverBaseUrl: string | (() => Promise), - data: LoginRequest + data: LoginRequest, ): Promise => { const [urlError, url] = typeof serverBaseUrl === 'function' ? await to(serverBaseUrl()) : [undefined, serverBaseUrl]; @@ -116,10 +119,10 @@ export const useLoginComplete = (data?: CustomLoginResponse) => { useEffect(() => { if (data) { const { response: loginRes, baseUrl: loginBaseUrl } = data; - + // Add session to sessions list const sessions = getLocalStorageItem('matrixSessions', []); - + const newSession = { baseUrl: loginBaseUrl, userId: loginRes.user_id, @@ -129,25 +132,25 @@ export const useLoginComplete = (data?: CustomLoginResponse) => { refreshToken: loginRes.refresh_token, fallbackSdkStores: false, }; - + // Check if session already exists (by userId AND deviceId to avoid conflicts) const existingIndex = sessions.findIndex( - (s: any) => s.userId === loginRes.user_id && s.deviceId === loginRes.device_id + (s: any) => s.userId === loginRes.user_id && s.deviceId === loginRes.device_id, ); if (existingIndex >= 0) { // Preserve fallbackSdkStores if it was set, but never enable it for new logins const oldSession = sessions[existingIndex]; sessions[existingIndex] = { ...newSession, - fallbackSdkStores: oldSession.fallbackSdkStores === true ? true : false, + fallbackSdkStores: oldSession.fallbackSdkStores === true, }; } else { sessions.push(newSession); } - + setLocalStorageItem('matrixSessions', sessions); setLocalStorageItem('currentSessionUserId', loginRes.user_id); - + const afterLoginRedirectUrl = getAfterLoginRedirectPath(); deleteAfterLoginRedirectPath(); const targetPath = @@ -158,10 +161,10 @@ export const useLoginComplete = (data?: CustomLoginResponse) => { deviceId: loginRes.device_id, isMultiAccount: sessions.length > 1, }); - + // Reload to the target path // For hash router, we need to use just the origin without /login pathname - window.location.href = window.location.origin + '/#' + targetPath; + window.location.href = `${window.location.origin}/#${targetPath}`; } }, [data, navigate]); }; diff --git a/src/app/pages/auth/register/PasswordRegisterForm.tsx b/src/app/pages/auth/register/PasswordRegisterForm.tsx index 092fa773..a0cdf08b 100644 --- a/src/app/pages/auth/register/PasswordRegisterForm.tsx +++ b/src/app/pages/auth/register/PasswordRegisterForm.tsx @@ -112,7 +112,7 @@ function RegisterUIAFlow({ initial_device_display_name: 'Paarrot', }); }, - [onRegister, formData] + [onRegister, formData], ); const handleCancel = useCallback(() => { diff --git a/src/app/pages/auth/register/Register.tsx b/src/app/pages/auth/register/Register.tsx index 7176489b..c9d4e43a 100644 --- a/src/app/pages/auth/register/Register.tsx +++ b/src/app/pages/auth/register/Register.tsx @@ -20,7 +20,7 @@ const useRegisterSearchParams = (searchParams: URLSearchParams): RegisterPathSea email: searchParams.get('email') ?? undefined, token: searchParams.get('token') ?? undefined, }), - [searchParams] + [searchParams], ); export function Register() { diff --git a/src/app/pages/auth/register/registerUtil.ts b/src/app/pages/auth/register/registerUtil.ts index 86a38cb5..3c0ee6c9 100644 --- a/src/app/pages/auth/register/registerUtil.ts +++ b/src/app/pages/auth/register/registerUtil.ts @@ -37,7 +37,7 @@ export type CustomRegisterResponse = { export type RegisterResult = [IAuthData, undefined] | [undefined, CustomRegisterResponse]; export const register = async ( mx: MatrixClient, - requestData: RegisterRequest + requestData: RegisterRequest, ): Promise => { const [err, res] = await to(mx.registerRequest(requestData)); @@ -130,7 +130,7 @@ export const useRegisterComplete = (data?: CustomRegisterResponse) => { withSearchParam(getLoginPath(userServer), { username, }), - { replace: true } + { replace: true }, ); } } diff --git a/src/app/pages/auth/reset-password/PasswordResetForm.tsx b/src/app/pages/auth/reset-password/PasswordResetForm.tsx index 392f45c0..03681700 100644 --- a/src/app/pages/auth/reset-password/PasswordResetForm.tsx +++ b/src/app/pages/auth/reset-password/PasswordResetForm.tsx @@ -120,7 +120,7 @@ export function PasswordResetForm({ defaultEmail }: PasswordResetFormProps) { }, password: formData.password, }, - formData.password + formData.password, ); } }, [ongoingAuthData, flowErrorCode, formData, handleResetPassword]); @@ -161,7 +161,7 @@ export function PasswordResetForm({ defaultEmail }: PasswordResetFormProps) { const { password } = formData; handleResetPassword(authDict, password); }, - [formData, handleResetPassword] + [formData, handleResetPassword], ); return ( diff --git a/src/app/pages/auth/reset-password/ResetPassword.tsx b/src/app/pages/auth/reset-password/ResetPassword.tsx index c5e1d2ad..996efb9d 100644 --- a/src/app/pages/auth/reset-password/ResetPassword.tsx +++ b/src/app/pages/auth/reset-password/ResetPassword.tsx @@ -7,13 +7,13 @@ import { PasswordResetForm } from './PasswordResetForm'; import { ResetPasswordPathSearchParams } from '../../paths'; const useResetPasswordSearchParams = ( - searchParams: URLSearchParams + searchParams: URLSearchParams, ): ResetPasswordPathSearchParams => useMemo( () => ({ email: searchParams.get('email') ?? undefined, }), - [searchParams] + [searchParams], ); export function ResetPassword() { diff --git a/src/app/pages/auth/reset-password/resetPasswordUtil.ts b/src/app/pages/auth/reset-password/resetPasswordUtil.ts index 5eb436fa..b2969b5e 100644 --- a/src/app/pages/auth/reset-password/resetPasswordUtil.ts +++ b/src/app/pages/auth/reset-password/resetPasswordUtil.ts @@ -6,10 +6,10 @@ export type ResetPasswordResult = [IAuthData, undefined] | [undefined, ResetPass export const resetPassword = async ( mx: MatrixClient, authDict: AuthDict, - newPassword: string + newPassword: string, ): Promise => { const [err, res] = await to( - mx.setPassword(authDict, newPassword, false) + mx.setPassword(authDict, newPassword, false), ); if (err) { diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 7fc1a9f6..8525796c 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,5 +1,4 @@ -import { useAtomValue } from 'jotai'; -import { useAtom, useSetAtom } from 'jotai'; +import { useAtomValue, useAtom, useSetAtom } from 'jotai'; import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react'; import { useNavigate } from 'react-router-dom'; import { RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk'; @@ -13,7 +12,12 @@ import { EmojiStyle, settingsAtom } from '../../state/settings'; import { allInvitesAtom } from '../../state/room-list/inviteList'; import { usePreviousValue } from '../../hooks/usePreviousValue'; import { useMatrixClient } from '../../hooks/useMatrixClient'; -import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath, getInboxInvitesPath } from '../pathUtils'; +import { + getDirectRoomPath, + getHomeRoomPath, + getSpaceRoomPath, + getInboxInvitesPath, +} from '../pathUtils'; import { getMemberDisplayName, getNotificationType, @@ -23,7 +27,12 @@ import { guessPerfectParent, } from '../../utils/room'; import { NotificationType, UnreadInfo } from '../../../types/matrix/room'; -import { getMxIdLocalPart, mxcUrlToHttp, getCanonicalAliasOrRoomId } from '../../utils/matrix'; +import { + getMxIdLocalPart, + mxcUrlToHttp, + getCanonicalAliasOrRoomId, + encryptFile, +} from '../../utils/matrix'; import { mDirectAtom } from '../../state/mDirectList'; import { roomToParentsAtom } from '../../state/room/roomToParents'; import { useSelectedRoom } from '../../hooks/router/useSelectedRoom'; @@ -49,7 +58,6 @@ import { roomIdToMsgDraftAtomFamily, roomIdToUploadItemsAtomFamily, } from '../../state/room/roomInputDrafts'; -import { encryptFile } from '../../utils/matrix'; import { AndroidSharePayload, clearPendingAndroidShare, @@ -135,10 +143,11 @@ function InviteNotifications() { (count: number) => { const body = `You have ${count} new invitation request.`; const invitesPath = getInboxInvitesPath(); - + // Flash taskbar icon for desktop notifications (only visible when window is not focused) if (isElectron() && (window as any).electron?.window?.flashFrame) { - (window as any).electron.window.flashFrame(true) + (window as any).electron.window + .flashFrame(true) .then((result: { success: boolean }) => { console.log('[InviteNotifications] flashFrame result:', result); }) @@ -146,7 +155,7 @@ function InviteNotifications() { console.error('[InviteNotifications] flashFrame error:', err); }); } - + if ((isTauri() && !isElectron()) || isCapacitorNative()) { sendNotification({ title: 'Invitation', @@ -175,14 +184,15 @@ function InviteNotifications() { }; } }, - [navigate] + [navigate], ); const playSound = useCallback(() => { console.log('[InviteNotifications] playSound called, isElectron:', isElectron()); if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { console.log('[InviteNotifications] Using Electron audio API'); - (window as any).electron.audio.playNotificationSound('invite') + (window as any).electron.audio + .playNotificationSound('invite') .then((result: any) => console.log('[InviteNotifications] Sound result:', result)) .catch((err: any) => console.error('[InviteNotifications] Sound error:', err)); } else { @@ -275,7 +285,8 @@ function MessageNotifications() { // Flash taskbar icon for desktop notifications (only visible when window is not focused) console.log('[Notifications] Attempting flashFrame'); if (isElectron() && (window as any).electron?.window?.flashFrame) { - (window as any).electron.window.flashFrame(true) + (window as any).electron.window + .flashFrame(true) .then((result: { success: boolean }) => { console.log('[Notifications] flashFrame result:', result); }) @@ -285,7 +296,7 @@ function MessageNotifications() { } else { console.warn('[Notifications] flashFrame not available, isElectron:', isElectron()); } - + if ((isTauri() && !isElectron()) || isCapacitorNative()) { const roomPath = isDm ? getDirectRoomPath(roomId, eventId) @@ -326,14 +337,15 @@ function MessageNotifications() { notifRef.current = noti; } }, - [mx, navigate, mDirects, roomToParents] + [mx, navigate, mDirects, roomToParents], ); const playSound = useCallback(() => { console.log('[MessageNotifications] playSound called, isElectron:', isElectron()); if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { console.log('[MessageNotifications] Using Electron audio API'); - (window as any).electron.audio.playNotificationSound('message') + (window as any).electron.audio + .playNotificationSound('message') .then((result: any) => console.log('[MessageNotifications] Sound result:', result)) .catch((err: any) => console.error('[MessageNotifications] Sound error:', err)); } else { @@ -350,7 +362,7 @@ function MessageNotifications() { room, toStartOfTimeline, removed, - data + data, ) => { if (mx.getSyncState() !== 'SYNCING') return; if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return; @@ -394,7 +406,7 @@ function MessageNotifications() { const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); const content = mEvent.getContent(); - + let messageBody: string | undefined; if (mEvent.getType() === 'm.reaction') { // For reactions, show "reacted with {emoji}" @@ -407,11 +419,11 @@ function MessageNotifications() { } else { messageBody = typeof content.body === 'string' ? content.body : undefined; } - + notify({ roomName: room.name ?? 'Unknown', roomAvatar: avatarMxc - ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) : undefined, username: getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) ?? sender, messageBody, @@ -483,10 +495,10 @@ function PaarrotAPIInitializer() { useEffect(() => { // Register navigate function for Paarrot API setPaarrotNavigate(navigate); - + // Initialize Paarrot API handlers initPaarrotAPI(mx); - + console.log('Paarrot API: Initialized with navigate function'); }, [navigate, mx]); @@ -536,7 +548,7 @@ function AndroidShareIntentHandler() { // Send text message if present const nextParts = [share.subject?.trim(), share.text?.trim()].filter( - (value): value is string => !!value + (value): value is string => !!value, ); if (nextParts.length > 0) { const textContent = { @@ -550,7 +562,7 @@ function AndroidShareIntentHandler() { if (share.files.length > 0) { for (const sharedFile of share.files) { const originalFile = await materializeSharedFile(sharedFile, share.receivedAt); - + let fileToUpload = originalFile; let encInfo: any; @@ -598,7 +610,7 @@ function AndroidShareIntentHandler() { await clearPendingAndroidShare(); return true; }, - [mx] + [mx], ); const handlePickRoom = useCallback( @@ -609,7 +621,7 @@ function AndroidShareIntentHandler() { .then((applied) => { if (applied) { setPendingShare(null); - + // Navigate to the selected room const isDirect = mDirects.has(roomId); if (isDirect) { @@ -630,7 +642,7 @@ function AndroidShareIntentHandler() { setPendingShare(null); }); }, - [applyPendingShare, pendingShare, navigate, mDirects, roomToParents] + [applyPendingShare, pendingShare, navigate, mDirects, roomToParents], ); const handleDismiss = useCallback(() => { @@ -674,13 +686,7 @@ function AndroidShareIntentHandler() { if (!pendingShare) return null; - return ( - - ); + return ; } type ClientNonUIFeaturesProps = { diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index dfbea08b..30902a3f 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -1,5 +1,15 @@ -import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; -import { Icon, Icons } from '../../components/icons'; +import { + Box, + Button, + config, + Dialog, + IconButton, + Menu, + MenuItem, + PopOut, + RectCords, + Text, +} from 'folds'; import { ClientEvent, HttpApiEvent, @@ -8,7 +18,16 @@ import { SyncState, } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; -import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; +import React, { + MouseEventHandler, + ReactNode, + useCallback, + useEffect, + useRef, + useState, +} from 'react'; +import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../components/icons'; import { clearCacheAndReload, clearLoginData, @@ -27,7 +46,6 @@ import { SpecVersions } from './SpecVersions'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { useSyncState } from '../../hooks/useSyncState'; import { stopPropagation } from '../../utils/keyboard'; -import { useAtomValue } from 'jotai'; import { allRoomsAtom, useBindAllRoomsAtom } from '../../state/room-list/roomList'; import { mDirectAtom, useBindMDirectAtom } from '../../state/mDirectList'; import { roomToParentsAtom, useBindRoomToParentsAtom } from '../../state/room/roomToParents'; @@ -69,9 +87,14 @@ const useVisibilitySync = (mx?: MatrixClient) => { console.log('[useVisibilitySync] App became visible, checking sync state'); const syncState = mx.getSyncState(); console.log('[useVisibilitySync] Current sync state:', syncState); - + // If sync is not running or errored, restart it - if (!mx.clientRunning || syncState === SyncState.Error || syncState === SyncState.Stopped || syncState === null) { + if ( + !mx.clientRunning || + syncState === SyncState.Error || + syncState === SyncState.Stopped || + syncState === null + ) { console.log('[useVisibilitySync] Restarting sync...'); startClient(mx).catch((err) => { console.error('[useVisibilitySync] Failed to restart sync:', err); @@ -85,10 +108,10 @@ const useVisibilitySync = (mx?: MatrixClient) => { }; document.addEventListener('visibilitychange', handleVisibilityChange); - + // Also handle resume event for mobile (if available) window.addEventListener('resume', handleVisibilityChange); - + return () => { document.removeEventListener('visibilitychange', handleVisibilityChange); window.removeEventListener('resume', handleVisibilityChange); @@ -189,7 +212,9 @@ export function ClientRoot({ children }: ClientRootProps) { const roomsAtom = useAtomValue(allRoomsAtom); const directsAtom = useAtomValue(mDirectAtom); const chatsReady = - roomsAtom.length > 0 && directsAtom.size > 0 && roomsAtom.some((roomId) => directsAtom.has(roomId)); + roomsAtom.length > 0 && + directsAtom.size > 0 && + roomsAtom.some((roomId) => directsAtom.has(roomId)); const tryHide = useCallback( (reason: string): boolean => { @@ -199,7 +224,7 @@ export function ClientRoot({ children }: ClientRootProps) { } return false; }, - [chatsReady, scheduleHide] + [chatsReady, scheduleHide], ); // The atoms fill in as the store restores the cache; hide as soon as they do. @@ -218,7 +243,7 @@ export function ClientRoot({ children }: ClientRootProps) { throw new Error('No session Found!'); } return initClient(session); - }, []) + }, []), ); const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined; @@ -226,8 +251,8 @@ export function ClientRoot({ children }: ClientRootProps) { mxRef.current = mx; }, [mx]); - useEffect(() => { - return () => { + useEffect( + () => () => { if (splashHoldTimer.current !== undefined) { window.clearTimeout(splashHoldTimer.current); } @@ -237,11 +262,12 @@ export function ClientRoot({ children }: ClientRootProps) { if (splashDeadline.current !== undefined) { window.clearTimeout(splashDeadline.current); } - }; - }, []); + }, + [], + ); const [startState, startMatrix] = useAsyncCallback( - useCallback((m) => startClient(m), []) + useCallback((m) => startClient(m), []), ); useLogoutListener(mx); @@ -273,7 +299,7 @@ export function ClientRoot({ children }: ClientRootProps) { '[ClientRoot] Splash gate:', mx.getSyncState(), `${roomsAtom.length} rooms in atom`, - `${directsAtom.size} m.direct` + `${directsAtom.size} m.direct`, ); // Prepared can fire before this listener attaches, so look at the current @@ -317,79 +343,82 @@ export function ClientRoot({ children }: ClientRootProps) { // window ensures we never block the UI when offline. useSyncState( mx, - useCallback((state, prevState, data) => { - const client = mxRef.current; - if (state === SyncState.Prepared || state === SyncState.Syncing) { - if (state === SyncState.Prepared) { - console.log( - '[ClientRoot] Prepared from', - prevState ?? 'nothing', - data?.fromCache ? '(cache)' : '(network)' - ); - } - - if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) { - return; - } - - if (data?.fromCache) { - // Cache-only prepared: the room list is still being restored, so wait - // for it, but hide anyway once the grace expires so we never block the - // UI when offline. - if (firstNetworkSyncGrace.current === undefined) { - firstNetworkSyncGrace.current = window.setTimeout(() => { - firstNetworkSyncGrace.current = undefined; - scheduleHide('cache grace expired'); - }, 5000); + useCallback( + (state, prevState, data) => { + const client = mxRef.current; + if (state === SyncState.Prepared || state === SyncState.Syncing) { + if (state === SyncState.Prepared) { + console.log( + '[ClientRoot] Prepared from', + prevState ?? 'nothing', + data?.fromCache ? '(cache)' : '(network)', + ); } - } else { - // First network sync completed: whatever we have is what the UI shows. - scheduleHide('first network sync completed'); - } - recoverInFlight.current = false; - return; - } - if (state !== SyncState.Error || !client) { - return; - } + if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) { + return; + } - // Sync failed (no network, first sync never landed). Show whatever the - // cache restored instead of leaving the splash up. - if (client.getRooms().length > 0) scheduleHide('sync error with cached chats'); - - if (recoverInFlight.current) { - return; - } - - recoverInFlight.current = true; - console.warn('[ClientRoot] Sync error after sleep/network blip, soft-recovering...'); - - const recover = () => { - if (!mxRef.current) { + if (data?.fromCache) { + // Cache-only prepared: the room list is still being restored, so wait + // for it, but hide anyway once the grace expires so we never block the + // UI when offline. + if (firstNetworkSyncGrace.current === undefined) { + firstNetworkSyncGrace.current = window.setTimeout(() => { + firstNetworkSyncGrace.current = undefined; + scheduleHide('cache grace expired'); + }, 5000); + } + } else { + // First network sync completed: whatever we have is what the UI shows. + scheduleHide('first network sync completed'); + } recoverInFlight.current = false; return; } - const c = mxRef.current; - if (!c.clientRunning) { - startClient(c) - .catch((err) => console.warn('[ClientRoot] Soft recover startClient failed:', err)) - .finally(() => { - recoverInFlight.current = false; - }); + + if (state !== SyncState.Error || !client) { return; } - try { - c.retryImmediately(); - } catch (err) { - console.warn('[ClientRoot] Soft recover retryImmediately failed:', err); - } - recoverInFlight.current = false; - }; - // Give Wi‑Fi a moment to come back after lid open / resume - window.setTimeout(recover, 1500); - }, [tryHide, scheduleHide]) + // Sync failed (no network, first sync never landed). Show whatever the + // cache restored instead of leaving the splash up. + if (client.getRooms().length > 0) scheduleHide('sync error with cached chats'); + + if (recoverInFlight.current) { + return; + } + + recoverInFlight.current = true; + console.warn('[ClientRoot] Sync error after sleep/network blip, soft-recovering...'); + + const recover = () => { + if (!mxRef.current) { + recoverInFlight.current = false; + return; + } + const c = mxRef.current; + if (!c.clientRunning) { + startClient(c) + .catch((err) => console.warn('[ClientRoot] Soft recover startClient failed:', err)) + .finally(() => { + recoverInFlight.current = false; + }); + return; + } + try { + c.retryImmediately(); + } catch (err) { + console.warn('[ClientRoot] Soft recover retryImmediately failed:', err); + } + recoverInFlight.current = false; + }; + + // Give Wi‑Fi a moment to come back after lid open / resume + window.setTimeout(recover, 1500); + }, + [tryHide, scheduleHide], + ), ); // Also nudge sync when the laptop wakes / network returns @@ -399,7 +428,11 @@ export function ClientRoot({ children }: ClientRootProps) { const nudge = () => { if (document.visibilityState !== 'visible') return; const syncState = mx.getSyncState(); - if (syncState === SyncState.Error || syncState === SyncState.Reconnecting || !mx.clientRunning) { + if ( + syncState === SyncState.Error || + syncState === SyncState.Reconnecting || + !mx.clientRunning + ) { console.log('[ClientRoot] Online/visible again, nudging sync', syncState); if (!mx.clientRunning) { startClient(mx).catch(() => {}); diff --git a/src/app/pages/client/SyncStatus.tsx b/src/app/pages/client/SyncStatus.tsx index 9cd4b0b2..62c16c72 100644 --- a/src/app/pages/client/SyncStatus.tsx +++ b/src/app/pages/client/SyncStatus.tsx @@ -27,7 +27,7 @@ export function SyncStatus({ mx }: SyncStatusProps) { } return { current, previous }; }); - }, []) + }, []), ); if ( diff --git a/src/app/pages/client/WelcomePage.tsx b/src/app/pages/client/WelcomePage.tsx index 37bbb067..c4896fda 100644 --- a/src/app/pages/client/WelcomePage.tsx +++ b/src/app/pages/client/WelcomePage.tsx @@ -1,15 +1,17 @@ import React, { useEffect, useState } from 'react'; import { Box, Button, Text, config, toRem } from 'folds'; +import { getVersion } from '@tauri-apps/api/app'; import { Icon, Icons } from '../../components/icons'; import { Page, PageHero, PageHeroSection } from '../../components/page'; import PaarrotSVG from '../../../../public/res/svg/paarrot.svg'; -import { getVersion } from '@tauri-apps/api/app'; export function WelcomePage() { const [version, setVersion] = useState(''); useEffect(() => { - getVersion().then(setVersion).catch(() => setVersion('')); + getVersion() + .then(setVersion) + .catch(() => setVersion('')); }, []); return ( @@ -25,7 +27,7 @@ export function WelcomePage() { title="Welcome to Paarrot" subTitle={ - Squawk to yer mateys! {' '} + Squawk to yer mateys!{' '} {version && ( void; }; @@ -168,11 +190,7 @@ function InvitesNavItem() { const inviteCount = allInvites.length; return ( - 0} - > + 0}> @@ -233,7 +251,7 @@ export function Direct() { const noRoomToDisplay = directs.length === 0; const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom()); const scrollRef = useRef(null); - + const reorderTrigger = useRoomListReorder(mx, directs); const sortedDirects = useMemo(() => { @@ -254,7 +272,7 @@ export function Direct() { }); const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => - closedCategories.has(categoryId) + closedCategories.has(categoryId), ); return ( @@ -315,44 +333,44 @@ export function Direct() { {sortedDirects.length > 0 && ( -
-
- {virtualizer.getVirtualItems().map((vItem) => { - const roomId = sortedDirects[vItem.index]; - const room = mx.getRoom(roomId); - if (!room) return null; - const selected = selectedRoomId === roomId; +
+
+ {virtualizer.getVirtualItems().map((vItem) => { + const roomId = sortedDirects[vItem.index]; + const room = mx.getRoom(roomId); + if (!room) return null; + const selected = selectedRoomId === roomId; - return ( - - - - ); - })} + return ( + + + + ); + })} +
-
)} diff --git a/src/app/pages/client/direct/RoomProvider.tsx b/src/app/pages/client/direct/RoomProvider.tsx index cee2241a..4b7fc496 100644 --- a/src/app/pages/client/direct/RoomProvider.tsx +++ b/src/app/pages/client/direct/RoomProvider.tsx @@ -29,10 +29,7 @@ export function DirectRouteRoomProvider({ children }: { children: ReactNode }) { if (!room || !isJoinedDirect) { return ( - + ); } diff --git a/src/app/pages/client/explore/Explore.tsx b/src/app/pages/client/explore/Explore.tsx index b5df7786..efaf6a3c 100644 --- a/src/app/pages/client/explore/Explore.tsx +++ b/src/app/pages/client/explore/Explore.tsx @@ -1,7 +1,21 @@ import React, { FormEventHandler, useCallback, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import FocusTrap from 'focus-trap-react'; -import { Avatar, Box, Button, Dialog, Header, IconButton, Input, Overlay, OverlayBackdrop, OverlayCenter, Text, color, config } from 'folds'; +import { + Avatar, + Box, + Button, + Dialog, + Header, + IconButton, + Input, + Overlay, + OverlayBackdrop, + OverlayCenter, + Text, + color, + config, +} from 'folds'; import { Icon, Icons } from '../../../components/icons'; import { NavCategory, @@ -30,7 +44,7 @@ export function AddServer() { const serverInputRef = useRef(null); const [exploreState] = useAsyncCallback( - useCallback((server: string) => mx.publicRooms({ server, limit: 1 }), [mx]) + useCallback((server: string) => mx.publicRooms({ server, limit: 1 }), [mx]), ); const getInputServer = (): string | undefined => { diff --git a/src/app/pages/client/explore/Featured.tsx b/src/app/pages/client/explore/Featured.tsx index 429e6a2f..1268d98b 100644 --- a/src/app/pages/client/explore/Featured.tsx +++ b/src/app/pages/client/explore/Featured.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Box, IconButton, Scroll, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { useClientConfig } from '../../../hooks/useClientConfig'; import { RoomCard, RoomCardGrid } from '../../../components/room-card'; import { allRoomsAtom } from '../../../state/room-list/roomList'; diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index a7a2a1bc..e9c15a06 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -8,13 +8,29 @@ import React, { useRef, useState, } from 'react'; -import { Box, Button, Chip, IconButton, Input, Line, Menu, MenuItem, PopOut, RectCords, Scroll, Spinner, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + Button, + Chip, + IconButton, + Input, + Line, + Menu, + MenuItem, + PopOut, + RectCords, + Scroll, + Spinner, + Text, + config, + toRem, +} from 'folds'; import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import FocusTrap from 'focus-trap-react'; import { useAtomValue } from 'jotai'; import { useQuery } from '@tanstack/react-query'; import { MatrixClient, Method, RoomType } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { RoomTopicViewer } from '../../../components/room-topic-viewer'; @@ -38,7 +54,7 @@ const useServerSearchParams = (searchParams: URLSearchParams): ExploreServerPath type: searchParams.get('type') ?? undefined, instance: searchParams.get('instance') ?? undefined, }), - [searchParams] + [searchParams], ); type RoomTypeFilter = { @@ -61,7 +77,7 @@ const useRoomTypeFilters = (): RoomTypeFilter[] => value: 'null', }, ], - [] + [], ); const FALLBACK_ROOMS_LIMIT = 24; @@ -374,7 +390,7 @@ export function PublicRooms() { room_types: roomType !== undefined ? [roomType] : undefined, }, third_party_instance_id: serverSearchParams.instance, - } + }, ); }, [mx, server, serverSearchParams]); diff --git a/src/app/pages/client/home/Home.tsx b/src/app/pages/client/home/Home.tsx index 3d74c33a..04c44c25 100644 --- a/src/app/pages/client/home/Home.tsx +++ b/src/app/pages/client/home/Home.tsx @@ -1,11 +1,23 @@ import React, { MouseEventHandler, forwardRef, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Avatar, Box, Button, IconButton, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Box, + Button, + IconButton, + Menu, + MenuItem, + PopOut, + RectCords, + Text, + config, + toRem, +} from 'folds'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useAtom, useAtomValue } from 'jotai'; import FocusTrap from 'focus-trap-react'; import { Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { factoryRoomIdByActivity, factoryRoomIdByAtoZ } from '../../../utils/sort'; import { NavButton, @@ -34,7 +46,11 @@ import { import { useHomeRooms } from './useHomeRooms'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { VirtualTile } from '../../../components/virtualizer'; -import { RoomNavCategoryButton, RoomNavItem, UnjoinedSubRoomItem } from '../../../features/room-nav'; +import { + RoomNavCategoryButton, + RoomNavItem, + UnjoinedSubRoomItem, +} from '../../../features/room-nav'; import { makeNavCategoryId } from '../../../state/closedNavCategories'; import { roomToUnreadAtom } from '../../../state/room/roomToUnread'; import { useCategoryHandler } from '../../../hooks/useCategoryHandler'; @@ -108,7 +124,7 @@ const HomeMenu = forwardRef( ); - } + }, ); function HomeHeader() { @@ -117,11 +133,11 @@ function HomeHeader() { const mx = useMatrixClient(); const orphanRooms = useHomeRooms(); - const rooms = useMemo(() => { - return orphanRooms - .map((roomId) => mx.getRoom(roomId)) - .filter((room): room is Room => room !== null); - }, [mx, orphanRooms]); + const rooms = useMemo( + () => + orphanRooms.map((roomId) => mx.getRoom(roomId)).filter((room): room is Room => room !== null), + [mx, orphanRooms], + ); const handleOpenMenu: MouseEventHandler = (evt) => { const cords = evt.currentTarget.getBoundingClientRect(); @@ -223,7 +239,7 @@ function HomeEmpty() { ); } -type RoomListItem = +type RoomListItem = | { type: 'room'; roomId: string; room: Room; depth: number; parentId?: string; isLast?: boolean } | { type: 'unjoined-subroom'; roomId: string; depth: number; parentId: string; isLast?: boolean }; @@ -247,9 +263,9 @@ export function Home() { const items = Array.from(rooms).sort( closedCategories.has(DEFAULT_CATEGORY_ID) ? factoryRoomIdByActivity(mx) - : factoryRoomIdByAtoZ(mx) + : factoryRoomIdByAtoZ(mx), ); - + if (closedCategories.has(DEFAULT_CATEGORY_ID)) { return items.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId); } @@ -261,23 +277,28 @@ export function Home() { const items: RoomListItem[] = []; const processedRooms = new Set(); - const addRoomAndSubRooms = (roomId: string, depth: number = 0, parentId?: string, isLast: boolean = false) => { + const addRoomAndSubRooms = ( + roomId: string, + depth: number = 0, + parentId?: string, + isLast: boolean = false, + ) => { if (processedRooms.has(roomId)) return; // Prevent infinite loops processedRooms.add(roomId); - + const room = mx.getRoom(roomId); - + if (room) { // Joined room - show normally items.push({ type: 'room', roomId, room, depth, parentId, isLast }); - + // Get sub-rooms from room state const subRoomsEvent = room.currentState.getStateEvents(StateEvent.PaarrotSubRooms, ''); const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? []; - + // Filter to only joined sub-rooms - const joinedSubRooms = subRooms.filter(subRoomId => mx.getRoom(subRoomId)); - + const joinedSubRooms = subRooms.filter((subRoomId) => mx.getRoom(subRoomId)); + // Add sub-rooms recursively joinedSubRooms.forEach((subRoomId, index) => { addRoomAndSubRooms(subRoomId, depth + 1, roomId, index === joinedSubRooms.length - 1); @@ -287,17 +308,17 @@ export function Home() { // Build set of all sub-room IDs to identify top-level rooms const allSubRoomIds = new Set(); - sortedRooms.forEach(roomId => { + sortedRooms.forEach((roomId) => { const room = mx.getRoom(roomId); if (room) { const subRoomsEvent = room.currentState.getStateEvents(StateEvent.PaarrotSubRooms, ''); const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? []; - subRooms.forEach(id => allSubRoomIds.add(id)); + subRooms.forEach((id) => allSubRoomIds.add(id)); } }); // Only add top-level rooms (rooms that aren't sub-rooms of another) - sortedRooms.forEach(roomId => { + sortedRooms.forEach((roomId) => { if (!allSubRoomIds.has(roomId)) { addRoomAndSubRooms(roomId); } @@ -314,7 +335,7 @@ export function Home() { }); const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => - closedCategories.has(categoryId) + closedCategories.has(categoryId), ); return ( @@ -366,15 +387,10 @@ export function Home() { onCancel={() => setOpen(false)} onOpen={(roomIdOrAlias, viaServers, eventId) => { setOpen(false); - const searchParams: _RoomSearchParams = { - viaServers: viaServers?.join(',') + const searchParams: _RoomSearchParams = { + viaServers: viaServers?.join(','), }; - navigate( - withSearchParam( - getHomeRoomPath(roomIdOrAlias), - searchParams - ) - ); + navigate(withSearchParam(getHomeRoomPath(roomIdOrAlias), searchParams)); }} /> )} @@ -411,84 +427,92 @@ export function Home() { {listItems.length > 0 && ( -
-
- {virtualizer.getVirtualItems().map((vItem) => { - const item = listItems[vItem.index]; - if (!item) return null; +
+
+ {virtualizer.getVirtualItems().map((vItem) => { + const item = listItems[vItem.index]; + if (!item) return null; - if (item.type === 'unjoined-subroom') { - return ( - - - - ); - } + if (item.type === 'unjoined-subroom') { + return ( + + + + ); + } - const selected = selectedRoomId === item.roomId; - const paddingLeft = item.depth > 0 ? '30px' : undefined; - - let treeIcon = ''; - if (item.depth > 0) { - treeIcon = item.isLast ? '╰' : '├'; - } + const selected = selectedRoomId === item.roomId; + const paddingLeft = item.depth > 0 ? '30px' : undefined; - return ( - -
0 ? '1.5rem' : undefined, - position: 'relative', - }} - > - {treeIcon && ( - - {treeIcon} - - )} -
- 0} - linkPath={getHomeRoomPath(getCanonicalAliasOrRoomId(mx, item.roomId))} - notificationMode={getRoomNotificationMode( - notificationPreferences, - item.room.roomId + let treeIcon = ''; + if (item.depth > 0) { + treeIcon = item.isLast ? '╰' : '├'; + } + + return ( + +
0 ? '1.5rem' : undefined, + position: 'relative', + }} + > + {treeIcon && ( + + {treeIcon} + )} - /> -
-
- - ); - })} +
+ 0} + linkPath={getHomeRoomPath( + getCanonicalAliasOrRoomId(mx, item.roomId), + )} + notificationMode={getRoomNotificationMode( + notificationPreferences, + item.room.roomId, + )} + /> +
+
+
+ ); + })} +
-
)} diff --git a/src/app/pages/client/home/HomeThreadsCategory.tsx b/src/app/pages/client/home/HomeThreadsCategory.tsx index 9677bcc5..62280307 100644 --- a/src/app/pages/client/home/HomeThreadsCategory.tsx +++ b/src/app/pages/client/home/HomeThreadsCategory.tsx @@ -1,10 +1,16 @@ import React, { useCallback, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Avatar, Box, Text, Badge } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtom, useSetAtom } from 'jotai'; import { Room, Thread, ThreadEvent } from 'matrix-js-sdk'; -import { NavCategory, NavCategoryHeader, NavItem, NavItemContent, NavButton } from '../../../components/nav'; +import { Icon, Icons } from '../../../components/icons'; +import { + NavCategory, + NavCategoryHeader, + NavItem, + NavItemContent, + NavButton, +} from '../../../components/nav'; import { RoomNavCategoryButton } from '../../../features/room-nav'; import { makeNavCategoryId } from '../../../state/closedNavCategories'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; @@ -39,8 +45,7 @@ function ThreadNavItem({ room, thread, selected }: ThreadNavItemProps) { const { rootEvent } = thread; const senderId = rootEvent?.getSender() ?? ''; - const senderName = - getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId; + const senderName = getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId; const rootBody = rootEvent?.getContent()?.body ?? ''; const replyCount = thread.length; @@ -69,7 +74,12 @@ function ThreadNavItem({ room, thread, selected }: ThreadNavItemProps) { - + {senderName} @@ -105,18 +115,20 @@ export function HomeThreadsCategory({ rooms }: HomeThreadsCategoryProps) { const mx = useMatrixClient(); const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom()); - const getParticipatedThreads = useCallback((): ThreadEntry[] => - rooms.reduce((acc, roomId) => { - const room = mx.getRoom(roomId); - if (!room) return acc; - return acc.concat( - room - .getThreads() - .filter((t) => t.hasCurrentUserParticipated) - .map((t) => ({ room, thread: t })) - ); - }, []), - [mx, rooms]); + const getParticipatedThreads = useCallback( + (): ThreadEntry[] => + rooms.reduce((acc, roomId) => { + const room = mx.getRoom(roomId); + if (!room) return acc; + return acc.concat( + room + .getThreads() + .filter((t) => t.hasCurrentUserParticipated) + .map((t) => ({ room, thread: t })), + ); + }, []), + [mx, rooms], + ); const [threads, setThreads] = useState(getParticipatedThreads); @@ -148,7 +160,7 @@ export function HomeThreadsCategory({ rooms }: HomeThreadsCategoryProps) { }, [mx, rooms, getParticipatedThreads]); const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => - closedCategories.has(categoryId) + closedCategories.has(categoryId), ); if (threads.length === 0) return null; diff --git a/src/app/pages/client/inbox/Inbox.tsx b/src/app/pages/client/inbox/Inbox.tsx index c0cf5e7c..cedc3a7f 100644 --- a/src/app/pages/client/inbox/Inbox.tsx +++ b/src/app/pages/client/inbox/Inbox.tsx @@ -1,8 +1,14 @@ import React, { useRef } from 'react'; import { Avatar, Box, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; -import { NavCategory, NavCategoryHeader, NavItem, NavItemContent, NavLink } from '../../../components/nav'; +import { Icon, Icons } from '../../../components/icons'; +import { + NavCategory, + NavCategoryHeader, + NavItem, + NavItemContent, + NavLink, +} from '../../../components/nav'; import { getInboxInvitesPath, getInboxNotificationsPath } from '../../pathUtils'; import { useInboxInvitesSelected, diff --git a/src/app/pages/client/inbox/Invites.tsx b/src/app/pages/client/inbox/Invites.tsx index b46c100c..77f2ba50 100644 --- a/src/app/pages/client/inbox/Invites.tsx +++ b/src/app/pages/client/inbox/Invites.tsx @@ -1,10 +1,25 @@ import React, { useCallback, useMemo, useRef, useState } from 'react'; -import { Avatar, Badge, Box, Button, Chip, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Spinner, Text, color, config } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Badge, + Box, + Button, + Chip, + IconButton, + Overlay, + OverlayBackdrop, + OverlayCenter, + Scroll, + Spinner, + Text, + color, + config, +} from 'folds'; import { useAtomValue } from 'jotai'; import { RoomTopicEventContent } from 'matrix-js-sdk/lib/types'; import FocusTrap from 'focus-trap-react'; import { MatrixClient, MatrixError, Room } from 'matrix-js-sdk'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, @@ -91,7 +106,7 @@ const makeInviteData = (mx: MatrixClient, room: Room, useAuthentication: boolean const senderId = memberEvent?.getSender(); const senderName = senderId - ? getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId + ? (getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId) : undefined; const inviteTs = memberEvent?.getTs(); const reason = @@ -161,10 +176,10 @@ function InviteCard({ await addRoomIdToMDirect(mx, invite.roomId, dmUserId); } onNavigate(invite.roomId, invite.isSpace); - }, [mx, invite, userId, onNavigate]) + }, [mx, invite, userId, onNavigate]), ); const [leaveState, leave] = useAsyncCallback, MatrixError, []>( - useCallback(() => mx.leave(invite.roomId), [mx, invite]) + useCallback(() => mx.leave(invite.roomId), [mx, invite]), ); const joining = @@ -464,7 +479,7 @@ function UnknownInvites({ const roomIds = invites.map((invite) => invite.roomId); await rateLimitedActions(roomIds, (roomId) => mx.leave(roomId)); - }, [mx, invites]) + }, [mx, invites]), ); const declining = declineAllStatus.status === AsyncStatus.Loading; @@ -540,7 +555,7 @@ function SpamInvites({ const roomIds = invites.map((invite) => invite.roomId); await rateLimitedActions(roomIds, (roomId) => mx.leave(roomId)); - }, [mx, invites]) + }, [mx, invites]), ); const [reportAllStatus, reportAll] = useAsyncCallback( @@ -548,18 +563,18 @@ function SpamInvites({ const roomIds = invites.map((invite) => invite.roomId); await rateLimitedActions(roomIds, (roomId) => mx.reportRoom(roomId, 'Spam Invite')); - }, [mx, invites]) + }, [mx, invites]), ); const ignoredUsers = useIgnoredUsers(); const unignoredUsers = Array.from(new Set(invites.map((invite) => invite.senderId))).filter( - (user) => !ignoredUsers.includes(user) + (user) => !ignoredUsers.includes(user), ); const [blockAllStatus, blockAll] = useAsyncCallback( useCallback( () => mx.setIgnoredUsers([...ignoredUsers, ...unignoredUsers]), - [mx, ignoredUsers, unignoredUsers] - ) + [mx, ignoredUsers, unignoredUsers], + ), ); const declining = declineAllStatus.status === AsyncStatus.Loading; @@ -714,7 +729,7 @@ export function Invites() { const [compact, setCompact] = useState(document.body.clientWidth <= COMPACT_CARD_WIDTH); useElementSizeObserver( useCallback(() => containerRef.current, []), - useCallback((width) => setCompact(width <= COMPACT_CARD_WIDTH), []) + useCallback((width) => setCompact(width <= COMPACT_CARD_WIDTH), []), ); const screenSize = useScreenSizeContext(); diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index be3217df..22181855 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -1,7 +1,6 @@ /* eslint-disable react/destructuring-assignment */ import React, { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Avatar, Box, Chip, Header, IconButton, Scroll, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useSearchParams } from 'react-router-dom'; import { INotification, @@ -16,6 +15,7 @@ import { useVirtualizer } from '@tanstack/react-virtual'; import { HTMLReactParserOptions } from 'html-react-parser'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { getMxIdLocalPart, mxcUrlToHttp } from '../../../utils/matrix'; @@ -102,7 +102,7 @@ type SilentReloadTimeline = () => Promise; const groupNotifications = ( notifications: INotification[], - allowRooms: Set + allowRooms: Set, ): RoomNotificationsGroup[] => { const groups: RoomNotificationsGroup[] = []; notifications.forEach((notification) => { @@ -124,7 +124,7 @@ const groupNotifications = ( const useNotificationTimeline = ( paginationLimit: number, - onlyHighlight?: boolean + onlyHighlight?: boolean, ): [NotificationTimeline, LoadTimeline, SilentReloadTimeline] => { const mx = useMatrixClient(); const allRooms = useAtomValue(allRoomsAtom); @@ -140,10 +140,10 @@ const useNotificationTimeline = ( return mx.http.authedRequest( Method.Get, '/notifications', - queryParams + queryParams, ); }, - [mx] + [mx], ); const loadTimeline: LoadTimeline = useCallback( @@ -154,7 +154,7 @@ const useNotificationTimeline = ( const data = await fetchNotifications( from, paginationLimit, - onlyHighlight ? 'highlight' : undefined + onlyHighlight ? 'highlight' : undefined, ); const groups = groupNotifications(data.notifications, allJoinedRooms); @@ -168,7 +168,7 @@ const useNotificationTimeline = ( return currentTimeline; }); }, - [paginationLimit, onlyHighlight, fetchNotifications, allJoinedRooms] + [paginationLimit, onlyHighlight, fetchNotifications, allJoinedRooms], ); /** @@ -179,7 +179,7 @@ const useNotificationTimeline = ( const data = await fetchNotifications( undefined, paginationLimit, - onlyHighlight ? 'highlight' : undefined + onlyHighlight ? 'highlight' : undefined, ); const groups = groupNotifications(data.notifications, allJoinedRooms); setNotificationTimeline({ @@ -199,7 +199,9 @@ type NotificationItemProps = { notification: INotification; getMemberPowerTag: ReturnType; accessibleTagColors: Map | undefined; - renderMatrixEvent: ReturnType>; + renderMatrixEvent: ReturnType< + typeof useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]> + >; handleOpenClick: MouseEventHandler; legacyUsernameColor?: boolean; hour24Clock: boolean; @@ -225,16 +227,13 @@ function NotificationItem({ const { event } = notification; const displayName = - getMemberDisplayName(room, event.sender) ?? - getMxIdLocalPart(event.sender) ?? - event.sender; + getMemberDisplayName(room, event.sender) ?? getMxIdLocalPart(event.sender) ?? event.sender; const senderAvatarMxc = getMemberAvatarMxc(room, event.sender); const getContent = (() => event.content) as GetContentCallback; const relation = event.content['m.relates_to']; const replyEventId = relation?.['m.in_reply_to']?.event_id; - const threadRootId = - relation?.rel_type === RelationType.Thread ? relation.event_id : undefined; + const threadRootId = relation?.rel_type === RelationType.Thread ? relation.event_id : undefined; // Get custom user color from avatar metadata const customUserColor = useOtherUserColor(event.sender, room); @@ -248,7 +247,8 @@ function NotificationItem({ : undefined; // Priority: custom user color > tag color (non-legacy) > colorMXID (legacy) - const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor); + const usernameColor = + customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor); return ( ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)) + renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)), ), }), - [mx, room, mentionClickHandler] + [mx, room, mentionClickHandler], ); const htmlReactParserOptions = useMemo( () => @@ -383,7 +377,7 @@ function RoomNotificationsGroupComp({ handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, }), - [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication] + [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication], ); const renderMatrixEvent = useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]>( @@ -445,7 +439,7 @@ function RoomNotificationsGroupComp({ const editedEvent = getEditedEvent( evt.event_id, mEvent, - evtTimeline.getTimelineSet() + evtTimeline.getTimelineSet(), ); const getContent = (() => editedEvent?.getContent()['m.new_content'] ?? @@ -522,7 +516,7 @@ function RoomNotificationsGroupComp({ ); - } + }, ); const handleOpenClick: MouseEventHandler = (evt) => { @@ -586,13 +580,13 @@ function RoomNotificationsGroupComp({ } const useNotificationsSearchParams = ( - searchParams: URLSearchParams + searchParams: URLSearchParams, ): InboxNotificationsPathSearchParams => useMemo( () => ({ only: searchParams.get('only') ?? undefined, }), - [searchParams] + [searchParams], ); const DEFAULT_REFRESH_MS = 7000; @@ -621,7 +615,7 @@ export function Notifications() { setSearchParams( new URLSearchParams({ only: 'highlight', - }) + }), ); return; } @@ -630,7 +624,7 @@ export function Notifications() { const [notificationTimeline, _loadTimeline, silentReloadTimeline] = useNotificationTimeline( 24, - onlyHighlight + onlyHighlight, ); const [timelineState, loadTimeline] = useAsyncCallback(_loadTimeline); @@ -646,12 +640,12 @@ export function Notifications() { useCallback(() => { silentReloadTimeline(); }, [silentReloadTimeline]), - refreshIntervalTime + refreshIntervalTime, ); const handleScrollTopVisibility = useCallback( (onTop: boolean) => setRefreshIntervalTime(onTop ? DEFAULT_REFRESH_MS : -1), - [] + [], ); useEffect(() => { diff --git a/src/app/pages/client/sidebar/CreateTab.tsx b/src/app/pages/client/sidebar/CreateTab.tsx index cf509623..a625220f 100644 --- a/src/app/pages/client/sidebar/CreateTab.tsx +++ b/src/app/pages/client/sidebar/CreateTab.tsx @@ -1,8 +1,8 @@ import React, { MouseEventHandler, useState } from 'react'; import { Box, config, Menu, PopOut, RectCords, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import FocusTrap from 'focus-trap-react'; import { useNavigate } from 'react-router-dom'; +import { Icon, Icons } from '../../../components/icons'; import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar'; import { stopPropagation } from '../../../utils/keyboard'; import { SequenceCard } from '../../../components/sequence-card'; @@ -122,7 +122,7 @@ export function CreateTab() { ? withSearchParam<_RoomSearchParams>(path, { viaServers: encodeSearchParamValueArray(viaServers), }) - : path + : path, ); }} /> diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index d0d09968..8ddd50e6 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -1,9 +1,9 @@ import React, { MouseEventHandler, forwardRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Box, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import FocusTrap from 'focus-trap-react'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import PaarrotSVG from '../../../../../public/res/svg/paarrot.svg'; import PaarrotUnreadSVG from '../../../../../public/res/svg/paarrot-unread.svg'; import PaarrotHighlightSVG from '../../../../../public/res/svg/paarrot-highlight.svg'; @@ -111,8 +111,8 @@ export function DirectTab() { directUnread?.highlight ? PaarrotHighlightSVG : directUnread?.total - ? PaarrotUnreadSVG - : PaarrotSVG + ? PaarrotUnreadSVG + : PaarrotSVG } alt="Direct Messages" style={{ width: '100%', height: '100%', objectFit: 'contain' }} @@ -121,13 +121,15 @@ export function DirectTab() { )} {directUnread && directUnread.total > 0 && ( -
+
0} count={directUnread.total} />
)} diff --git a/src/app/pages/client/sidebar/ExploreTab.tsx b/src/app/pages/client/sidebar/ExploreTab.tsx index f85b1df5..4aa00c6d 100644 --- a/src/app/pages/client/sidebar/ExploreTab.tsx +++ b/src/app/pages/client/sidebar/ExploreTab.tsx @@ -1,8 +1,8 @@ -import { Icon, Icons } from '../../../components/icons'; import React from 'react'; import { useNavigate } from 'react-router-dom'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar'; import { useExploreSelected } from '../../../hooks/router/useExploreSelected'; import { diff --git a/src/app/pages/client/sidebar/HomeTab.tsx b/src/app/pages/client/sidebar/HomeTab.tsx index 61bc8fa6..acece8b5 100644 --- a/src/app/pages/client/sidebar/HomeTab.tsx +++ b/src/app/pages/client/sidebar/HomeTab.tsx @@ -1,10 +1,10 @@ import React, { MouseEventHandler, forwardRef, useState } from 'react'; -import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; import { Box, Line, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; import FocusTrap from 'focus-trap-react'; -import { useOrphanRooms } from '../../../state/hooks/roomList'; +import { Icon, Icons } from '../../../components/icons'; +import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; +import { useOrphanRooms, useOrphanSpaces } from '../../../state/hooks/roomList'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { mDirectAtom } from '../../../state/mDirectList'; import { roomToParentsAtom } from '../../../state/room/roomToParents'; @@ -27,9 +27,14 @@ import { useMarkRoomsAsRead } from '../../../hooks/useMarkAsRead'; import { stopPropagation } from '../../../utils/keyboard'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; -import { makeHideHomeContent, parseHiddenSpaces, parseSidebar, useHiddenSpaces, useSidebarItems } from '../../../hooks/useSidebarItems'; +import { + makeHideHomeContent, + parseHiddenSpaces, + parseSidebar, + useHiddenSpaces, + useSidebarItems, +} from '../../../hooks/useSidebarItems'; import { AccountDataEvent } from '../../../../types/matrix/accountData'; -import { useOrphanSpaces } from '../../../state/hooks/roomList'; type HomeMenuProps = { requestClose: () => void; diff --git a/src/app/pages/client/sidebar/InboxTab.tsx b/src/app/pages/client/sidebar/InboxTab.tsx index 6db95787..635d6433 100644 --- a/src/app/pages/client/sidebar/InboxTab.tsx +++ b/src/app/pages/client/sidebar/InboxTab.tsx @@ -1,8 +1,8 @@ -import { Icon, Icons } from '../../../components/icons'; import React from 'react'; +import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; -import { useAtomValue } from 'jotai'; import { SidebarAvatar, SidebarItem, diff --git a/src/app/pages/client/sidebar/SearchTab.tsx b/src/app/pages/client/sidebar/SearchTab.tsx index 2197545c..6358818d 100644 --- a/src/app/pages/client/sidebar/SearchTab.tsx +++ b/src/app/pages/client/sidebar/SearchTab.tsx @@ -1,7 +1,7 @@ -import { Icon, Icons } from '../../../components/icons'; import React from 'react'; import { useAtom } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar'; import { searchModalAtom } from '../../../state/searchModal'; import * as sidebarCss from '../../../components/sidebar/Sidebar.css'; diff --git a/src/app/pages/client/sidebar/SettingsTab.tsx b/src/app/pages/client/sidebar/SettingsTab.tsx index c6b426fb..dd3cb6e0 100644 --- a/src/app/pages/client/sidebar/SettingsTab.tsx +++ b/src/app/pages/client/sidebar/SettingsTab.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, useState } from 'react'; import { Box, config, Line, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; import { SidebarItem, SidebarAvatar } from '../../../components/sidebar'; import { UserAvatar } from '../../../components/user-avatar'; @@ -37,15 +37,16 @@ export function SettingsTab() { const [customStatusOpen, setCustomStatusOpen] = useState(false); const displayName = profile.displayName ?? getMxIdLocalPart(userId ?? '') ?? userId ?? ''; - const avatarUrl = profile.avatarUrl && userId - ? mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined - : undefined; + const avatarUrl = + profile.avatarUrl && userId + ? (mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined) + : undefined; const { assetUrls } = useOtherUserCollectibles(userId ?? ''); const avatarDecorationUrl = pickAvatarDecorationUrl(assetUrls); const nameplateUrl = pickNameplateUrl(assetUrls); const [sidebarNameplateOpacity] = useSetting(settingsAtom, 'sidebarNameplateOpacity'); const nameplateIsVideo = Boolean( - assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm'] + assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm'], ); const openSettings = () => setSettings(true); @@ -105,7 +106,7 @@ export function SettingsTab() { )}
- + - { setMenuAnchor(undefined); navigate(`${getLoginPath()}?add-account=true`); - }} - size="300" + }} + size="300" radii="300" > @@ -185,12 +186,9 @@ export function SettingsTab() { } /> - - setCustomStatusOpen(false)} - /> - + + setCustomStatusOpen(false)} /> + {settings && ( diff --git a/src/app/pages/client/sidebar/SpaceTabs.tsx b/src/app/pages/client/sidebar/SpaceTabs.tsx index 74d0ba38..9885dc88 100644 --- a/src/app/pages/client/sidebar/SpaceTabs.tsx +++ b/src/app/pages/client/sidebar/SpaceTabs.tsx @@ -9,9 +9,18 @@ import React, { useRef, useState, } from 'react'; -import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; -import { Box, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Box, + IconButton, + Line, + Menu, + MenuItem, + PopOut, + RectCords, + Text, + config, + toRem, +} from 'folds'; import { useAtom, useAtomValue } from 'jotai'; import { Room } from 'matrix-js-sdk'; import { @@ -27,6 +36,8 @@ import { import { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'; import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; +import { useNavigateWithTransition } from '../../../hooks/useViewTransitions'; import { useOrphanRooms, useOrphanSpaces, @@ -118,7 +129,7 @@ const SpaceMenu = forwardRef( const allChild = useSpaceChildren( allRoomsAtom, room.roomId, - useRecursiveChildScopeFactory(mx, roomToParents) + useRecursiveChildScopeFactory(mx, roomToParents), ); const unread = useRoomsUnread(allChild, roomToUnreadAtom); @@ -276,7 +287,7 @@ const SpaceMenu = forwardRef( ); - } + }, ); type InstructionType = Instruction['type']; @@ -291,7 +302,7 @@ const useDraggableItem = ( item: SidebarDraggable, targetRef: RefObject, onDragging: (item?: SidebarDraggable) => void, - dragHandleRef?: RefObject + dragHandleRef?: RefObject, ): boolean => { const [dragging, setDragging] = useState(false); @@ -321,7 +332,7 @@ const useDraggableItem = ( const useDropTarget = ( item: SidebarDraggable, - targetRef: RefObject + targetRef: RefObject, ): Instruction | undefined => { const [dropState, setDropState] = useState(); @@ -348,7 +359,7 @@ const useDropTarget = ( indentPerLevel: 0, mode: 'standard', block, - } + }, ); const instruction: Instruction | null = extractInstruction(insData); @@ -370,7 +381,7 @@ const useDropTarget = ( function useDropTargetInstruction( item: SidebarDraggable, targetRef: RefObject, - instructionType: T + instructionType: T, ): T | undefined { const [dropState, setDropState] = useState(); @@ -406,8 +417,8 @@ const useDnDMonitor = ( onReorder: ( draggable: SidebarDraggable, container: SidebarDraggable, - instruction: InstructionType - ) => void + instruction: InstructionType, + ) => void, ) => { useEffect(() => { const scrollElement = scrollRef.current; @@ -424,15 +435,14 @@ const useDnDMonitor = ( const item = source.data.item as SidebarDraggable; const containerItem = dropTargets[0].data.item as SidebarDraggable; const instructionType = dropTargets[0].data.instructionType as - | InstructionType - | undefined; + InstructionType | undefined; if (!instructionType) return; onReorder(item, containerItem, instructionType); }, }), autoScrollForElements({ element: scrollElement, - }) + }), ); }, [scrollRef, onDragging, onReorder]); }; @@ -469,7 +479,7 @@ function SpaceTab({ spaceId: space.roomId, } : space.roomId, - [folder, space] + [folder, space], ); useDraggableItem(spaceDraggable, targetRef, onDragging); @@ -701,16 +711,18 @@ function HiddenSpacesFolder({ const orphanRooms = useOrphanRooms(mx, allRoomsAtom, mDirects, roomToParents); const homeUnread = useRoomsUnread(orphanRooms, roomToUnreadAtom); - const handleContextMenu = (spaceId: string): MouseEventHandler => (evt) => { - evt.preventDefault(); - const cords = evt.currentTarget.getBoundingClientRect(); - setMenuSpaceId(spaceId); - setMenuIsHome(false); - setMenuAnchor((currentState) => { - if (currentState) return undefined; - return cords; - }); - }; + const handleContextMenu = + (spaceId: string): MouseEventHandler => + (evt) => { + evt.preventDefault(); + const cords = evt.currentTarget.getBoundingClientRect(); + setMenuSpaceId(spaceId); + setMenuIsHome(false); + setMenuAnchor((currentState) => { + if (currentState) return undefined; + return cords; + }); + }; const handleHomeContextMenu: MouseEventHandler = (evt) => { evt.preventDefault(); @@ -752,12 +764,13 @@ function HiddenSpacesFolder({ {(unread) => { // Combine space unreads with home unreads if home is hidden - const totalUnread = homeHidden && homeUnread - ? { - total: (unread?.total ?? 0) + homeUnread.total, - highlight: (unread?.highlight ?? 0) + homeUnread.highlight, - } - : unread; + const totalUnread = + homeHidden && homeUnread + ? { + total: (unread?.total ?? 0) + homeUnread.total, + highlight: (unread?.highlight ?? 0) + homeUnread.highlight, + } + : unread; return ( ( - {nameInitials(space.name, 2)} - )} + renderFallback={() => {nameInitials(space.name, 2)}} /> )} @@ -1044,8 +1055,8 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) { localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent)); mx.setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent); }, - [mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces] - ) + [mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces], + ), ); const selectedSpaceId = useSelectedSpace(); @@ -1090,7 +1101,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) { localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent)); mx.setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent); }, - [mx, sidebarItems, orphanSpaces, localEchoSidebarItem] + [mx, sidebarItems, orphanSpaces, localEchoSidebarItem], ); const handleHide = useCallback( @@ -1100,7 +1111,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) { localEchoHiddenSpaces(parseHiddenSpaces(mx, newContent)); mx.setAccountData(AccountDataEvent.CinnySpaces, newContent); }, - [mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces] + [mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces], ); if (sidebarItems.length === 0) return null; @@ -1226,7 +1237,7 @@ export function HiddenSpacesTabs() { localEchoHiddenSpaces(parseHiddenSpaces(mx, newContent)); mx.setAccountData(AccountDataEvent.CinnySpaces, newContent); }, - [mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces] + [mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces], ); const handleUnhideHome = useCallback(() => { diff --git a/src/app/pages/client/sidebar/UnverifiedTab.tsx b/src/app/pages/client/sidebar/UnverifiedTab.tsx index 759b9a24..699804c3 100644 --- a/src/app/pages/client/sidebar/UnverifiedTab.tsx +++ b/src/app/pages/client/sidebar/UnverifiedTab.tsx @@ -30,7 +30,7 @@ function UnverifiedIndicator() { const verificationStatus = useDeviceVerificationStatus( crypto, mx.getSafeUserId(), - currentDevice?.device_id + currentDevice?.device_id, ); const unverified = verificationStatus === VerificationStatus.Unverified; @@ -38,7 +38,7 @@ function UnverifiedIndicator() { const unverifiedDeviceCount = useUnverifiedDeviceCount( crypto, mx.getSafeUserId(), - otherDevicesId + otherDevicesId, ); const [settings, setSettings] = useState(false); diff --git a/src/app/pages/client/space/RoomProvider.tsx b/src/app/pages/client/space/RoomProvider.tsx index d6870c5e..32621ffb 100644 --- a/src/app/pages/client/space/RoomProvider.tsx +++ b/src/app/pages/client/space/RoomProvider.tsx @@ -33,7 +33,7 @@ export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) { const isJoined = Boolean(room && allRooms.includes(room.roomId)); const isSpaceChild = Boolean(room && getSpaceChildren(space).includes(room.roomId)); const hasParentMapping = Boolean( - room && getAllParents(roomToParents, room.roomId).has(space.roomId) + room && getAllParents(roomToParents, room.roomId).has(space.roomId), ); // roomToParents can lag behind live space state during catch-up sync. @@ -45,14 +45,7 @@ export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) { parent: space.roomId, children: [room.roomId], }); - }, [ - room, - isJoined, - hasParentMapping, - isSpaceChild, - space.roomId, - setRoomToParents, - ]); + }, [room, isJoined, hasParentMapping, isSpaceChild, space.roomId, setRoomToParents]); if (!room || !isJoined) { // room is not joined diff --git a/src/app/pages/client/space/Search.tsx b/src/app/pages/client/space/Search.tsx index 7744f51b..d31c0ae4 100644 --- a/src/app/pages/client/space/Search.tsx +++ b/src/app/pages/client/space/Search.tsx @@ -1,7 +1,7 @@ import React, { useRef } from 'react'; import { Box, Text, Scroll, IconButton } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; import { useAtomValue } from 'jotai'; +import { Icon, Icons } from '../../../components/icons'; import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page'; import { MessageSearch } from '../../../features/message-search'; import { useSpace } from '../../../hooks/useSpace'; @@ -24,7 +24,7 @@ export function SpaceSearch() { const rooms = useSpaceChildren( allRoomsAtom, space.roomId, - useRecursiveChildRoomScopeFactory(mx, mDirects, roomToParents) + useRecursiveChildRoomScopeFactory(mx, mDirects, roomToParents), ); return ( diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index 89c35966..f1d8ce2e 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -7,11 +7,26 @@ import React, { useState, } from 'react'; import { useAtom, useAtomValue } from 'jotai'; -import { Avatar, Box, Button, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Spinner, Text, color, config, toRem } from 'folds'; -import { Icon, Icons } from '../../../components/icons'; +import { + Avatar, + Box, + Button, + IconButton, + Line, + Menu, + MenuItem, + PopOut, + RectCords, + Spinner, + Text, + color, + config, + toRem, +} from 'folds'; import { JoinRule, Room, Thread, ThreadEvent } from 'matrix-js-sdk'; import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types'; import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../../../components/icons'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { mDirectAtom } from '../../../state/mDirectList'; import { @@ -29,7 +44,11 @@ import { useSpaceSearchSelected, } from '../../../hooks/router/useSelectedSpace'; import { useSpace } from '../../../hooks/useSpace'; -import { RoomNavCategoryButton, RoomNavItem, UnjoinedSubRoomItem } from '../../../features/room-nav'; +import { + RoomNavCategoryButton, + RoomNavItem, + UnjoinedSubRoomItem, +} from '../../../features/room-nav'; import { makeNavCategoryId } from '../../../state/closedNavCategories'; import { roomToUnreadAtom } from '../../../state/room/roomToUnread'; import { useCategoryHandler } from '../../../hooks/useCategoryHandler'; @@ -152,7 +171,7 @@ function SpaceNavSection({ linkPath={getToLink(item.roomId)} notificationMode={getRoomNotificationMode( notificationPreferences, - item.roomId + item.roomId, )} />
@@ -171,10 +190,7 @@ function SpaceNavSection({ showAvatar={mDirects.has(item.roomId)} direct={mDirects.has(item.roomId)} linkPath={getToLink(item.roomId)} - notificationMode={getRoomNotificationMode( - notificationPreferences, - room.roomId - )} + notificationMode={getRoomNotificationMode(notificationPreferences, room.roomId)} /> ); })} @@ -192,7 +208,7 @@ function SpaceHeader() { const joinRules = useStateEvent( space, - StateEvent.RoomJoinRules + StateEvent.RoomJoinRules, )?.getContent(); const handleOpenMenu: MouseEventHandler = (evt) => { @@ -259,7 +275,7 @@ export function SpaceTombstone({ roomId, replacementRoomId }: SpaceTombstoneProp return mx.joinRoom(replacementRoomId, { viaServers: via, }); - }, [mx, roomId, replacementRoomId]) + }, [mx, roomId, replacementRoomId]), ); const replacementRoom = mx.getRoom(replacementRoomId); @@ -343,7 +359,7 @@ export function Space() { } return undefined; }, - [mx, allJoinedRooms] + [mx, allJoinedRooms], ); const hierarchy = useSpaceJoinedHierarchy( @@ -358,12 +374,12 @@ export function Space() { if (showRoom) return false; return true; }, - [space.roomId, closedCategories, roomToUnread, selectedRoomId] + [space.roomId, closedCategories, roomToUnread, selectedRoomId], ), useCallback( (sId) => closedCategories.has(makeNavCategoryId(space.roomId, sId)), - [closedCategories, space.roomId] - ) + [closedCategories, space.roomId], + ), ); // Build a global set of all sub-room IDs to filter from hierarchy @@ -379,9 +395,10 @@ export function Space() { }, [mx, allJoinedRooms, hierarchy]); // Filter hierarchy to exclude sub-rooms (they'll be shown nested under their parent) - const filteredHierarchy = useMemo(() => { - return hierarchy.filter((entry) => !globalSubRoomIds.has(entry.roomId)); - }, [hierarchy, globalSubRoomIds]); + const filteredHierarchy = useMemo( + () => hierarchy.filter((entry) => !globalSubRoomIds.has(entry.roomId)), + [hierarchy, globalSubRoomIds], + ); // One paper dropdown per space: space header + its rooms/sub-rooms const navSections = useMemo(() => { @@ -397,7 +414,7 @@ export function Space() { const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? []; const joinedSubRooms = subRooms.filter( - (subRoomId) => !processedSubRooms.has(subRoomId) && mx.getRoom(subRoomId) + (subRoomId) => !processedSubRooms.has(subRoomId) && mx.getRoom(subRoomId), ); joinedSubRooms.forEach((subRoomId, index) => { @@ -434,7 +451,7 @@ export function Space() { if (isSpaceEntry || (room && isSpace(room))) { startSection( entry.roomId, - entry.roomId === space.roomId ? 'Rooms' : room?.name ?? entry.roomId + entry.roomId === space.roomId ? 'Rooms' : (room?.name ?? entry.roomId), ); return; } @@ -453,7 +470,7 @@ export function Space() { }, [mx, filteredHierarchy, space.roomId]); const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => - closedCategories.has(categoryId) + closedCategories.has(categoryId), ); const getToLink = (roomId: string) => diff --git a/src/app/pages/pathSearchParam.ts b/src/app/pages/pathSearchParam.ts index 8e4c93e5..f3c82b61 100644 --- a/src/app/pages/pathSearchParam.ts +++ b/src/app/pages/pathSearchParam.ts @@ -7,7 +7,7 @@ export const getRoomSearchParams: SearchParamsGetter<_RoomSearchParams> = (searc }); export const getDirectCreateSearchParams: SearchParamsGetter = ( - searchParams + searchParams, ) => ({ userId: searchParams.get('userId') ?? undefined, }); diff --git a/src/app/pages/pathUtils.ts b/src/app/pages/pathUtils.ts index 8d676197..1dce693e 100644 --- a/src/app/pages/pathUtils.ts +++ b/src/app/pages/pathUtils.ts @@ -1,4 +1,5 @@ import { generatePath, Path } from 'react-router-dom'; +import type { MatrixClient } from 'matrix-js-sdk'; import { DIRECT_CREATE_PATH, DIRECT_PATH, @@ -31,7 +32,6 @@ import { import { trimLeadingSlash, trimTrailingSlash } from '../utils/common'; import { tryDecodeURIComponent } from '../utils/dom'; import { HashRouterConfig } from '../hooks/useClientConfig'; -import type { MatrixClient } from 'matrix-js-sdk'; import { getCanonicalAliasOrRoomId } from '../utils/matrix'; import { shouldShowForumLobby } from '../utils/room'; @@ -39,7 +39,7 @@ export const joinPathComponent = (path: Path): string => path.pathname + path.se export const withSearchParam = >( path: string, - searchParam: T + searchParam: T, ): string => { const params = new URLSearchParams(searchParam); @@ -171,7 +171,7 @@ export const getSpaceSearchPath = (spaceIdOrAlias: string): string => { export const getSpaceRoomPath = ( spaceIdOrAlias: string, roomIdOrAlias: string, - eventId?: string + eventId?: string, ): string => { const params = { spaceIdOrAlias, diff --git a/src/app/plugins/bad-words.ts b/src/app/plugins/bad-words.ts index bb6073d8..83d8388d 100644 --- a/src/app/plugins/bad-words.ts +++ b/src/app/plugins/bad-words.ts @@ -4,12 +4,12 @@ import { sanitizeForRegex } from '../utils/regex'; const additionalBadWords: string[] = ['torture', 't0rture']; const fullBadWordList = additionalBadWords.concat( - badWords.array.filter((word) => !additionalBadWords.includes(word)) + badWords.array.filter((word) => !additionalBadWords.includes(word)), ); export const BAD_WORDS_REGEX = new RegExp( `(\\b|_)(${fullBadWordList.map((word) => sanitizeForRegex(word)).join('|')})(\\b|_)`, - 'g' + 'g', ); export const testBadWords = (str: string): boolean => !!str.toLowerCase().match(BAD_WORDS_REGEX); diff --git a/src/app/plugins/custom-emoji/PackMetaReader.ts b/src/app/plugins/custom-emoji/PackMetaReader.ts index 537addf4..4c032807 100644 --- a/src/app/plugins/custom-emoji/PackMetaReader.ts +++ b/src/app/plugins/custom-emoji/PackMetaReader.ts @@ -31,7 +31,7 @@ export class PackMetaReader { if (!Array.isArray(this.meta.usage)) return this.fallbackUsage; const knownUsage = this.meta.usage.filter( - (u) => u === ImageUsage.Emoticon || u === ImageUsage.Sticker + (u) => u === ImageUsage.Emoticon || u === ImageUsage.Sticker, ); if (knownUsage.length === 0) return this.fallbackUsage; diff --git a/src/app/plugins/custom-emoji/utils.ts b/src/app/plugins/custom-emoji/utils.ts index cb80bb1c..8b942eac 100644 --- a/src/app/plugins/custom-emoji/utils.ts +++ b/src/app/plugins/custom-emoji/utils.ts @@ -50,8 +50,7 @@ export function getRoomImagePacks(room: Room): ImagePack[] { export function getGlobalImagePacks(mx: MatrixClient): ImagePack[] { const emoteRoomsContent = getAccountData(mx, AccountDataEvent.PoniesEmoteRooms)?.getContent() as - | EmoteRoomsContent - | undefined; + EmoteRoomsContent | undefined; if (typeof emoteRoomsContent !== 'object') return []; const { rooms: roomIdToPackInfo } = emoteRoomsContent; diff --git a/src/app/plugins/markdown/block/runner.ts b/src/app/plugins/markdown/block/runner.ts index 1dc8d8b8..304cfad0 100644 --- a/src/app/plugins/markdown/block/runner.ts +++ b/src/app/plugins/markdown/block/runner.ts @@ -14,7 +14,7 @@ export const runBlockRule = ( text: string, rule: BlockMDRule, parse: BlockMDParser, - parseInline?: (txt: string) => string + parseInline?: (txt: string) => string, ): string | undefined => { const matchResult = rule.match(text); if (matchResult) { diff --git a/src/app/plugins/markdown/block/type.ts b/src/app/plugins/markdown/block/type.ts index 0949eb70..b24f376f 100644 --- a/src/app/plugins/markdown/block/type.ts +++ b/src/app/plugins/markdown/block/type.ts @@ -18,7 +18,7 @@ export type BlockMDParser = (text: string, parseInline?: (txt: string) => string */ export type BlockMatchConverter = ( match: MatchResult, - parseInline?: (txt: string) => string + parseInline?: (txt: string) => string, ) => string; /** diff --git a/src/app/plugins/markdown/inline/rules.ts b/src/app/plugins/markdown/inline/rules.ts index 77bcbd57..56902a47 100644 --- a/src/app/plugins/markdown/inline/rules.ts +++ b/src/app/plugins/markdown/inline/rules.ts @@ -8,7 +8,7 @@ const BOLD_MD_1 = '**'; const BOLD_PREFIX_1 = `${ESC_NEG_LB}\\*{2}`; const BOLD_NEG_LA_1 = '(?!\\*)'; const BOLD_REG_1 = new RegExp( - `${URL_NEG_LB}${BOLD_PREFIX_1}${MIN_ANY}${BOLD_PREFIX_1}${BOLD_NEG_LA_1}` + `${URL_NEG_LB}${BOLD_PREFIX_1}${MIN_ANY}${BOLD_PREFIX_1}${BOLD_NEG_LA_1}`, ); export const BoldRule: InlineMDRule = { match: (text) => text.match(BOLD_REG_1), @@ -22,7 +22,7 @@ const ITALIC_MD_1 = '*'; const ITALIC_PREFIX_1 = `${ESC_NEG_LB}\\*`; const ITALIC_NEG_LA_1 = '(?!\\*)'; const ITALIC_REG_1 = new RegExp( - `${URL_NEG_LB}${ITALIC_PREFIX_1}${MIN_ANY}${ITALIC_PREFIX_1}${ITALIC_NEG_LA_1}` + `${URL_NEG_LB}${ITALIC_PREFIX_1}${MIN_ANY}${ITALIC_PREFIX_1}${ITALIC_NEG_LA_1}`, ); export const ItalicRule1: InlineMDRule = { match: (text) => text.match(ITALIC_REG_1), @@ -36,7 +36,7 @@ const ITALIC_MD_2 = '_'; const ITALIC_PREFIX_2 = `${ESC_NEG_LB}_`; const ITALIC_NEG_LA_2 = '(?!_)'; const ITALIC_REG_2 = new RegExp( - `${URL_NEG_LB}${ITALIC_PREFIX_2}${MIN_ANY}${ITALIC_PREFIX_2}${ITALIC_NEG_LA_2}` + `${URL_NEG_LB}${ITALIC_PREFIX_2}${MIN_ANY}${ITALIC_PREFIX_2}${ITALIC_NEG_LA_2}`, ); export const ItalicRule2: InlineMDRule = { match: (text) => text.match(ITALIC_REG_2), @@ -50,7 +50,7 @@ const UNDERLINE_MD_1 = '__'; const UNDERLINE_PREFIX_1 = `${ESC_NEG_LB}_{2}`; const UNDERLINE_NEG_LA_1 = '(?!_)'; const UNDERLINE_REG_1 = new RegExp( - `${URL_NEG_LB}${UNDERLINE_PREFIX_1}${MIN_ANY}${UNDERLINE_PREFIX_1}${UNDERLINE_NEG_LA_1}` + `${URL_NEG_LB}${UNDERLINE_PREFIX_1}${MIN_ANY}${UNDERLINE_PREFIX_1}${UNDERLINE_NEG_LA_1}`, ); export const UnderlineRule: InlineMDRule = { match: (text) => text.match(UNDERLINE_REG_1), @@ -64,7 +64,7 @@ const STRIKE_MD_1 = '~~'; const STRIKE_PREFIX_1 = `${ESC_NEG_LB}~{2}`; const STRIKE_NEG_LA_1 = '(?!~)'; const STRIKE_REG_1 = new RegExp( - `${URL_NEG_LB}${STRIKE_PREFIX_1}${MIN_ANY}${STRIKE_PREFIX_1}${STRIKE_NEG_LA_1}` + `${URL_NEG_LB}${STRIKE_PREFIX_1}${MIN_ANY}${STRIKE_PREFIX_1}${STRIKE_NEG_LA_1}`, ); export const StrikeRule: InlineMDRule = { match: (text) => text.match(STRIKE_REG_1), @@ -90,7 +90,7 @@ const SPOILER_MD_1 = '||'; const SPOILER_PREFIX_1 = `${ESC_NEG_LB}\\|{2}`; const SPOILER_NEG_LA_1 = '(?!\\|)'; const SPOILER_REG_1 = new RegExp( - `${URL_NEG_LB}${SPOILER_PREFIX_1}${MIN_ANY}${SPOILER_PREFIX_1}${SPOILER_NEG_LA_1}` + `${URL_NEG_LB}${SPOILER_PREFIX_1}${MIN_ANY}${SPOILER_PREFIX_1}${SPOILER_NEG_LA_1}`, ); export const SpoilerRule: InlineMDRule = { match: (text) => text.match(SPOILER_REG_1), diff --git a/src/app/plugins/markdown/inline/runner.ts b/src/app/plugins/markdown/inline/runner.ts index 3a794d25..3fa13d34 100644 --- a/src/app/plugins/markdown/inline/runner.ts +++ b/src/app/plugins/markdown/inline/runner.ts @@ -12,7 +12,7 @@ import { InlineMDParser, InlineMDRule } from './type'; export const runInlineRule = ( text: string, rule: InlineMDRule, - parse: InlineMDParser + parse: InlineMDParser, ): string | undefined => { const matchResult = rule.match(text); if (matchResult) { @@ -34,7 +34,7 @@ export const runInlineRule = ( export const runInlineRules = ( text: string, rules: InlineMDRule[], - parse: InlineMDParser + parse: InlineMDParser, ): string | undefined => { const matchResults = rules.map((rule) => rule.match(text)); diff --git a/src/app/plugins/markdown/internal/utils.ts b/src/app/plugins/markdown/internal/utils.ts index 86bc9d5c..65fbd47b 100644 --- a/src/app/plugins/markdown/internal/utils.ts +++ b/src/app/plugins/markdown/internal/utils.ts @@ -53,7 +53,7 @@ export const replaceMatch = ( text: string, match: MatchResult, content: C, - processPart: (txt: string) => Array + processPart: (txt: string) => Array, ): Array => [ ...processPart(beforeMatch(text, match)), content, diff --git a/src/app/plugins/markdown/utils.ts b/src/app/plugins/markdown/utils.ts index 0038df13..5f4c9cda 100644 --- a/src/app/plugins/markdown/utils.ts +++ b/src/app/plugins/markdown/utils.ts @@ -35,7 +35,7 @@ export const escapeMarkdownInlineSequences = (text: string): string => { const [, g1] = match; return `\\${g1}`; }, - (t) => t + (t) => t, ); return parts.join(''); @@ -52,7 +52,7 @@ export const escapeMarkdownInlineSequences = (text: string): string => { */ export const unescapeMarkdownBlockSequences = ( text: string, - processPart: (text: string) => string + processPart: (text: string) => string, ): string => { const match = text.match(ESC_BLOCK_SEQ); @@ -72,7 +72,7 @@ export const unescapeMarkdownBlockSequences = ( */ export const escapeMarkdownBlockSequences = ( text: string, - processPart: (text: string) => string + processPart: (text: string) => string, ): string => { const match = text.match(UN_ESC_BLOCK_SEQ); diff --git a/src/app/plugins/matrix-to.ts b/src/app/plugins/matrix-to.ts index feeafe05..248b5228 100644 --- a/src/app/plugins/matrix-to.ts +++ b/src/app/plugins/matrix-to.ts @@ -18,7 +18,7 @@ export const getMatrixToRoom = (roomIdOrAlias: string, viaServers?: string[]): s export const getMatrixToRoomEvent = ( roomIdOrAlias: string, eventId: string, - viaServers?: string[] + viaServers?: string[], ): string => { let fragment = `${roomIdOrAlias}/${eventId}`; diff --git a/src/app/plugins/pdfjs-dist.ts b/src/app/plugins/pdfjs-dist.ts index 1b2991f4..19e1e401 100644 --- a/src/app/plugins/pdfjs-dist.ts +++ b/src/app/plugins/pdfjs-dist.ts @@ -9,10 +9,10 @@ export const usePdfJSLoader = () => useCallback(async () => { const pdf = await import('pdfjs-dist'); pdf.GlobalWorkerOptions.workerSrc = `${trimTrailingSlash( - import.meta.env.BASE_URL + import.meta.env.BASE_URL, )}/pdf.worker.min.js`; return pdf; - }, []) + }, []), ); export const usePdfDocumentLoader = (pdfJS: typeof PdfJsDist | undefined, src: string) => @@ -23,13 +23,13 @@ export const usePdfDocumentLoader = (pdfJS: typeof PdfJsDist | undefined, src: s } const doc = await pdfJS.getDocument(src).promise; return doc; - }, [pdfJS, src]) + }, [pdfJS, src]), ); export const createPage = async ( doc: PdfJsDist.PDFDocumentProxy, pNo: number, - opts: GetViewportParameters + opts: GetViewportParameters, ): Promise => { const page = await doc.getPage(pNo); const pageViewport = page.getViewport(opts); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 7d7d66f3..e771c370 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -1,4 +1,3 @@ -/* eslint-disable jsx-a11y/alt-text */ import React, { ComponentPropsWithoutRef, MouseEvent, @@ -32,11 +31,12 @@ import { Text, toRem, } from 'folds'; -import { Icon, Icons } from '../components/icons'; import { IntermediateRepresentation, Opts as LinkifyOpts, OptFn } from 'linkifyjs'; import Linkify from 'linkify-react'; import { ErrorBoundary } from 'react-error-boundary'; import { ChildNode } from 'domhandler'; +import FocusTrap from 'focus-trap-react'; +import { Icon, Icons } from '../components/icons'; import * as css from '../styles/CustomHtml.css'; import { getMxIdLocalPart, @@ -59,12 +59,7 @@ import { copyToClipboard, tryDecodeURIComponent } from '../utils/dom'; import { useTimeoutToggle } from '../hooks/useTimeoutToggle'; import { settingsAtom } from '../state/settings'; import { useSetting } from '../state/hooks/settings'; -import FocusTrap from 'focus-trap-react'; -import { - AUTO_LANGUAGE, - LANGUAGE_OPTIONS, - PLAIN_LANGUAGE, -} from './react-prism/languages'; +import { AUTO_LANGUAGE, LANGUAGE_OPTIONS, PLAIN_LANGUAGE } from './react-prism/languages'; import { AuthenticatedImg } from '../components/authenticated-media'; import { openExternalUrl } from '../utils/tauri'; @@ -75,7 +70,7 @@ const PrismCode = lazy(() => import('./react-prism/PrismCode')); * Click handler for external links - uses Tauri shell on desktop/mobile */ const handleExternalLinkClick = (e: MouseEvent) => { - const href = e.currentTarget.href; + const { href } = e.currentTarget; console.log('[handleExternalLinkClick] clicked link:', href); if (href && (href.startsWith('http://') || href.startsWith('https://'))) { e.preventDefault(); @@ -99,7 +94,7 @@ export const LINKIFY_OPTS: LinkifyOpts = { export const makeMentionCustomProps = ( handleMentionClick?: ReactEventHandler, - content?: string + content?: string, ): ComponentPropsWithoutRef<'a'> => ({ style: { cursor: 'pointer' }, target: '_blank', @@ -115,7 +110,7 @@ export const renderMatrixMention = ( mx: MatrixClient, currentRoomId: string | undefined, href: string, - customProps: ComponentPropsWithoutRef<'a'> + customProps: ComponentPropsWithoutRef<'a'>, ) => { const userId = parseMatrixToUser(href); if (userId) { @@ -140,7 +135,7 @@ export const renderMatrixMention = ( if (matrixToRoom) { const { roomIdOrAlias, viaServers } = matrixToRoom; const mentionRoom = mx.getRoom( - isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias + isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias, ); const fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias; @@ -164,7 +159,7 @@ export const renderMatrixMention = ( if (matrixToRoomEvent) { const { roomIdOrAlias, eventId, viaServers } = matrixToRoomEvent; const mentionRoom = mx.getRoom( - isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias + isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias, ); return ( @@ -189,7 +184,7 @@ export const renderMatrixMention = ( }; export const factoryRenderLinkifyWithMention = ( - mentionRender: (href: string) => JSX.Element | undefined + mentionRender: (href: string) => JSX.Element | undefined, ): OptFn<(ir: IntermediateRepresentation) => any> => { const render: OptFn<(ir: IntermediateRepresentation) => any> = ({ tagName, @@ -201,7 +196,11 @@ export const factoryRenderLinkifyWithMention = ( if (mention) return mention; } - return
{content}; + return ( + + {content} + + ); }; return render; }; @@ -211,13 +210,17 @@ export const scaleSystemEmoji = (text: string): (string | JSX.Element)[] => text, EMOJI_REG_G, (match, pushIndex) => ( - + {match[0]} ), - (txt) => txt + (txt) => txt, ); export const makeHighlightRegex = (highlights: string[]): RegExp | undefined => { @@ -228,7 +231,7 @@ export const makeHighlightRegex = (highlights: string[]): RegExp | undefined => export const highlightText = ( regex: RegExp, - data: (string | JSX.Element)[] + data: (string | JSX.Element)[], ): (string | JSX.Element)[] => data.flatMap((text) => { if (typeof text !== 'string') return text; @@ -241,7 +244,7 @@ export const highlightText = ( {match[0]} ), - (txt) => txt + (txt) => txt, ); }); @@ -296,7 +299,7 @@ export function CodeBlock({ children }: { children: ChildNode[] }) { override === AUTO_LANGUAGE ? language : override === PLAIN_LANGUAGE ? undefined : override; const languageLabel = override === AUTO_LANGUAGE - ? language ?? 'Code' + ? (language ?? 'Code') : (LANGUAGE_OPTIONS.find((option) => option.value === override)?.label ?? override); const handleCopy = () => { @@ -378,8 +381,14 @@ export function CodeBlock({ children }: { children: ChildNode[] }) { copied ? ( ) : ( - - + + ) } @@ -499,8 +508,14 @@ export function InlineCode({ {copied ? ( ) : ( - - + + )} @@ -520,7 +535,7 @@ export const getReactCustomHtmlParser = ( handleSpoilerClick?: ReactEventHandler; handleMentionClick?: ReactEventHandler; useAuthentication?: boolean; - } + }, ): HTMLReactParserOptions => { const opts: HTMLReactParserOptions = { replace: (domNode) => { @@ -634,7 +649,11 @@ export const getReactCustomHtmlParser = ( ); } } else { - return {children}; + return ( + + {children} + + ); } } @@ -650,7 +669,7 @@ export const getReactCustomHtmlParser = ( mx, roomId, href, - makeMentionCustomProps(params.handleMentionClick, content) + makeMentionCustomProps(params.handleMentionClick, content), ); if (mention) return mention; @@ -686,7 +705,12 @@ export const getReactCustomHtmlParser = ( const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication); if (htmlSrc && props.src.startsWith('mxc://') === false) { return ( - + {props.alt || props.title || htmlSrc} ); diff --git a/src/app/plugins/text-area/mods/Intent.ts b/src/app/plugins/text-area/mods/Intent.ts index 35212b95..d03d1f7d 100644 --- a/src/app/plugins/text-area/mods/Intent.ts +++ b/src/app/plugins/text-area/mods/Intent.ts @@ -44,7 +44,7 @@ export class Intent { return new Cursor( cursor.start === linesCursor.start ? cursor.start : cursor.start + this.str.length, cursor.end + addedIntentLength, - cursor.direction + cursor.direction, ); } @@ -62,7 +62,7 @@ export class Intent { const firstLineTrimLength = lines[0].length - intentLines[0].length; const lastLine = this.textArea.cursorLines( - new Cursor(intentCursor.end, intentCursor.end, 'none') + new Cursor(intentCursor.end, intentCursor.end, 'none'), ); const start = Math.max(cursor.start - firstLineTrimLength, linesCursor.start); diff --git a/src/app/plugins/via-servers.ts b/src/app/plugins/via-servers.ts index d825a1fd..118677e4 100644 --- a/src/app/plugins/via-servers.ts +++ b/src/app/plugins/via-servers.ts @@ -62,7 +62,7 @@ export const getViaServers = (room: Room): string[] => { } const serverToPop = getServerToPopulation(); const sortedServers = Object.keys(serverToPop).sort( - (svrA, svrB) => serverToPop[svrB] - serverToPop[svrA] + (svrA, svrB) => serverToPop[svrB] - serverToPop[svrA], ); const mostPop3 = sortedServers.slice(0, 3); if (via.length === 0) return mostPop3; diff --git a/src/app/state/activeThread.ts b/src/app/state/activeThread.ts index 93ea8891..038361e4 100644 --- a/src/app/state/activeThread.ts +++ b/src/app/state/activeThread.ts @@ -7,5 +7,5 @@ const createActiveThreadAtom = () => atom(undefined); export type TActiveThreadAtom = ReturnType; export const activeThreadIdAtomFamily = atomFamily( - createActiveThreadAtom + createActiveThreadAtom, ); diff --git a/src/app/state/backupRestore.ts b/src/app/state/backupRestore.ts index ad14e5d7..94a3c496 100644 --- a/src/app/state/backupRestore.ts +++ b/src/app/state/backupRestore.ts @@ -66,5 +66,5 @@ export const backupRestoreProgressAtom = atom< }, }); } - } + }, ); diff --git a/src/app/state/closedLobbyCategories.ts b/src/app/state/closedLobbyCategories.ts index 9d4d5d17..8f942ada 100644 --- a/src/app/state/closedLobbyCategories.ts +++ b/src/app/state/closedLobbyCategories.ts @@ -36,7 +36,7 @@ export const makeClosedLobbyCategoriesAtom = (userId: string): ClosedLobbyCatego (key, value) => { const arrayValue = Array.from(value); setLocalStorageItem(key, arrayValue); - } + }, ); const closedLobbyCategoriesAtom = atom, [ClosedLobbyCategoriesAction], undefined>( @@ -47,7 +47,7 @@ export const makeClosedLobbyCategoriesAtom = (userId: string): ClosedLobbyCatego baseClosedLobbyCategoriesAtom, produce(get(baseClosedLobbyCategoriesAtom), (draft) => { draft.delete(action.categoryId); - }) + }), ); return; } @@ -56,10 +56,10 @@ export const makeClosedLobbyCategoriesAtom = (userId: string): ClosedLobbyCatego baseClosedLobbyCategoriesAtom, produce(get(baseClosedLobbyCategoriesAtom), (draft) => { draft.add(action.categoryId); - }) + }), ); } - } + }, ); return closedLobbyCategoriesAtom; diff --git a/src/app/state/closedNavCategories.ts b/src/app/state/closedNavCategories.ts index d21187f9..b62b177c 100644 --- a/src/app/state/closedNavCategories.ts +++ b/src/app/state/closedNavCategories.ts @@ -36,7 +36,7 @@ export const makeClosedNavCategoriesAtom = (userId: string): ClosedNavCategories (key, value) => { const arrayValue = Array.from(value); setLocalStorageItem(key, arrayValue); - } + }, ); const closedNavCategoriesAtom = atom, [ClosedNavCategoriesAction], undefined>( @@ -47,7 +47,7 @@ export const makeClosedNavCategoriesAtom = (userId: string): ClosedNavCategories baseClosedNavCategoriesAtom, produce(get(baseClosedNavCategoriesAtom), (draft) => { draft.delete(action.categoryId); - }) + }), ); return; } @@ -56,10 +56,10 @@ export const makeClosedNavCategoriesAtom = (userId: string): ClosedNavCategories baseClosedNavCategoriesAtom, produce(get(baseClosedNavCategoriesAtom), (draft) => { draft.add(action.categoryId); - }) + }), ); } - } + }, ); return closedNavCategoriesAtom; diff --git a/src/app/state/hooks/createRoomModal.ts b/src/app/state/hooks/createRoomModal.ts index 41be120e..6abc38f9 100644 --- a/src/app/state/hooks/createRoomModal.ts +++ b/src/app/state/hooks/createRoomModal.ts @@ -27,7 +27,7 @@ export const useOpenCreateRoomModal = (): OpenCallback => { (spaceId) => { setSettings({ spaceId }); }, - [setSettings] + [setSettings], ); return open; @@ -41,7 +41,7 @@ export const useOpenCreateSubRoomModal = (): OpenSubRoomCallback => { (parentSubRoomId) => { setSettings({ parentSubRoomId }); }, - [setSettings] + [setSettings], ); return open; diff --git a/src/app/state/hooks/createSpaceModal.ts b/src/app/state/hooks/createSpaceModal.ts index ea7cb47a..eb491bc7 100644 --- a/src/app/state/hooks/createSpaceModal.ts +++ b/src/app/state/hooks/createSpaceModal.ts @@ -27,7 +27,7 @@ export const useOpenCreateSpaceModal = (): OpenCallback => { (spaceId) => { setSettings({ spaceId }); }, - [setSettings] + [setSettings], ); return open; diff --git a/src/app/state/hooks/inviteList.ts b/src/app/state/hooks/inviteList.ts index 5e003fb1..8cbc9ad7 100644 --- a/src/app/state/hooks/inviteList.ts +++ b/src/app/state/hooks/inviteList.ts @@ -9,7 +9,7 @@ import { allInvitesAtom } from '../room-list/inviteList'; export const useSpaceInvites = (mx: MatrixClient, invitesAtom: typeof allInvitesAtom) => { const selector = useCallback( (rooms: string[]) => rooms.filter((roomId) => isSpace(mx.getRoom(roomId))), - [mx] + [mx], ); return useAtomValue(selectAtom(invitesAtom, selector, compareRoomsEqual)); }; @@ -17,16 +17,16 @@ export const useSpaceInvites = (mx: MatrixClient, invitesAtom: typeof allInvites export const useRoomInvites = ( mx: MatrixClient, invitesAtom: typeof allInvitesAtom, - mDirects: Set + mDirects: Set, ) => { const selector = useCallback( (rooms: string[]) => rooms.filter( (roomId) => isRoom(mx.getRoom(roomId)) && - !(mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId())) + !(mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId())), ), - [mx, mDirects] + [mx, mDirects], ); return useAtomValue(selectAtom(invitesAtom, selector, compareRoomsEqual)); }; @@ -34,14 +34,14 @@ export const useRoomInvites = ( export const useDirectInvites = ( mx: MatrixClient, invitesAtom: typeof allInvitesAtom, - mDirects: Set + mDirects: Set, ) => { const selector = useCallback( (rooms: string[]) => rooms.filter( - (roomId) => mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId()) + (roomId) => mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId()), ), - [mx, mDirects] + [mx, mDirects], ); return useAtomValue(selectAtom(invitesAtom, selector, compareRoomsEqual)); }; @@ -49,7 +49,7 @@ export const useDirectInvites = ( export const useUnsupportedInvites = (mx: MatrixClient, invitesAtom: typeof allInvitesAtom) => { const selector = useCallback( (rooms: string[]) => rooms.filter((roomId) => isUnsupportedRoom(mx.getRoom(roomId))), - [mx] + [mx], ); return useAtomValue(selectAtom(invitesAtom, selector, compareRoomsEqual)); }; diff --git a/src/app/state/hooks/roomList.ts b/src/app/state/hooks/roomList.ts index d64ecd5b..ff823af6 100644 --- a/src/app/state/hooks/roomList.ts +++ b/src/app/state/hooks/roomList.ts @@ -11,7 +11,7 @@ export type RoomSelector = (roomId: string) => boolean | undefined; export const selectedRoomsAtom = ( roomsAtom: RoomsAtom, - selector: (roomId: string) => boolean | undefined + selector: (roomId: string) => boolean | undefined, ) => selectAtom(roomsAtom, (rooms) => rooms.filter(selector), compareRoomsEqual); export const useSelectedRooms = (roomsAtom: RoomsAtom, selector: RoomSelector) => { @@ -24,55 +24,55 @@ export type SpaceChildSelectorFactory = (parentId: string) => RoomSelector; export const useRecursiveChildScopeFactory = ( mx: MatrixClient, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => isRoom(mx.getRoom(roomId)) && roomToParents.has(roomId) && getAllParents(roomToParents, roomId).has(parentId), - [mx, roomToParents] + [mx, roomToParents], ); export const useChildSpaceScopeFactory = ( mx: MatrixClient, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => isSpace(mx.getRoom(roomId)) && roomToParents.get(roomId)?.has(parentId), - [mx, roomToParents] + [mx, roomToParents], ); export const useRecursiveChildSpaceScopeFactory = ( mx: MatrixClient, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => isSpace(mx.getRoom(roomId)) && roomToParents.has(roomId) && getAllParents(roomToParents, roomId).has(parentId), - [mx, roomToParents] + [mx, roomToParents], ); export const useChildRoomScopeFactory = ( mx: MatrixClient, mDirects: Set, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => isRoom(mx.getRoom(roomId)) && !mDirects.has(roomId) && roomToParents.get(roomId)?.has(parentId), - [mx, mDirects, roomToParents] + [mx, mDirects, roomToParents], ); export const useRecursiveChildRoomScopeFactory = ( mx: MatrixClient, mDirects: Set, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => @@ -80,26 +80,26 @@ export const useRecursiveChildRoomScopeFactory = ( !mDirects.has(roomId) && roomToParents.has(roomId) && getAllParents(roomToParents, roomId).has(parentId), - [mx, mDirects, roomToParents] + [mx, mDirects, roomToParents], ); export const useChildDirectScopeFactory = ( mx: MatrixClient, mDirects: Set, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => isRoom(mx.getRoom(roomId)) && mDirects.has(roomId) && roomToParents.get(roomId)?.has(parentId), - [mx, mDirects, roomToParents] + [mx, mDirects, roomToParents], ); export const useRecursiveChildDirectScopeFactory = ( mx: MatrixClient, mDirects: Set, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): SpaceChildSelectorFactory => useCallback( (parentId: string) => (roomId) => @@ -107,17 +107,17 @@ export const useRecursiveChildDirectScopeFactory = ( mDirects.has(roomId) && roomToParents.has(roomId) && getAllParents(roomToParents, roomId).has(parentId), - [mx, mDirects, roomToParents] + [mx, mDirects, roomToParents], ); export const useSpaceChildren = ( roomsAtom: RoomsAtom, spaceId: string, - selectorFactory: SpaceChildSelectorFactory + selectorFactory: SpaceChildSelectorFactory, ) => { const recursiveChildRoomSelector = useMemo( () => selectorFactory(spaceId), - [selectorFactory, spaceId] + [selectorFactory, spaceId], ); return useSelectedRooms(roomsAtom, recursiveChildRoomSelector); }; @@ -130,11 +130,11 @@ export const useSpaces = (mx: MatrixClient, roomsAtom: RoomsAtom) => { export const useOrphanSpaces = ( mx: MatrixClient, roomsAtom: RoomsAtom, - roomToParents: RoomToParents + roomToParents: RoomToParents, ) => { const selector: RoomSelector = useCallback( (roomId) => isSpace(mx.getRoom(roomId)) && !roomToParents.has(roomId), - [mx, roomToParents] + [mx, roomToParents], ); return useSelectedRooms(roomsAtom, selector); }; @@ -142,7 +142,7 @@ export const useOrphanSpaces = ( export const useRooms = (mx: MatrixClient, roomsAtom: RoomsAtom, mDirects: Set) => { const selector: RoomSelector = useCallback( (roomId: string) => isRoom(mx.getRoom(roomId)) && !mDirects.has(roomId), - [mx, mDirects] + [mx, mDirects], ); return useSelectedRooms(roomsAtom, selector); }; @@ -151,11 +151,11 @@ export const useOrphanRooms = ( mx: MatrixClient, roomsAtom: RoomsAtom, mDirects: Set, - roomToParents: RoomToParents + roomToParents: RoomToParents, ) => { const selector: RoomSelector = useCallback( (roomId) => isRoom(mx.getRoom(roomId)) && !mDirects.has(roomId) && !roomToParents.has(roomId), - [mx, mDirects, roomToParents] + [mx, mDirects, roomToParents], ); return useSelectedRooms(roomsAtom, selector); }; @@ -163,7 +163,7 @@ export const useOrphanRooms = ( export const useDirects = (mx: MatrixClient, roomsAtom: RoomsAtom, mDirects: Set) => { const selector: RoomSelector = useCallback( (roomId) => isRoom(mx.getRoom(roomId)) && mDirects.has(roomId), - [mx, mDirects] + [mx, mDirects], ); return useSelectedRooms(roomsAtom, selector); }; @@ -171,7 +171,7 @@ export const useDirects = (mx: MatrixClient, roomsAtom: RoomsAtom, mDirects: Set export const useUnsupportedRooms = (mx: MatrixClient, roomsAtom: RoomsAtom) => { const selector: RoomSelector = useCallback( (roomId) => isUnsupportedRoom(mx.getRoom(roomId)), - [mx] + [mx], ); return useSelectedRooms(roomsAtom, selector); }; diff --git a/src/app/state/hooks/roomSettings.ts b/src/app/state/hooks/roomSettings.ts index 4d764916..a948d717 100644 --- a/src/app/state/hooks/roomSettings.ts +++ b/src/app/state/hooks/roomSettings.ts @@ -27,7 +27,7 @@ export const useOpenRoomSettings = (): OpenCallback => { (roomId, spaceId, page) => { setSettings({ roomId, spaceId, page }); }, - [setSettings] + [setSettings], ); return open; diff --git a/src/app/state/hooks/settings.ts b/src/app/state/hooks/settings.ts index d90c7664..0cb4a2f5 100644 --- a/src/app/state/hooks/settings.ts +++ b/src/app/state/hooks/settings.ts @@ -4,8 +4,7 @@ import { useMemo } from 'react'; import { Settings, settingsAtom as sAtom } from '../settings'; export type SettingSetter = - | Settings[K] - | ((s: Settings[K]) => Settings[K]); + Settings[K] | ((s: Settings[K]) => Settings[K]); export const useSetSetting = (settingsAtom: typeof sAtom, key: K) => { const setterAtom = useMemo( @@ -15,7 +14,7 @@ export const useSetSetting = (settingsAtom: typeof sAt s[key] = typeof value === 'function' ? value(s[key]) : value; set(settingsAtom, s); }), - [settingsAtom, key] + [settingsAtom, key], ); return useSetAtom(setterAtom); @@ -23,7 +22,7 @@ export const useSetSetting = (settingsAtom: typeof sAt export const useSetting = ( settingsAtom: typeof sAtom, - key: K + key: K, ): [Settings[K], ReturnType>] => { const selector = useMemo(() => (s: Settings) => s[key], [key]); const setting = useAtomValue(selectAtom(settingsAtom, selector)); diff --git a/src/app/state/hooks/spaceSettings.ts b/src/app/state/hooks/spaceSettings.ts index e589d65d..50dc22f3 100644 --- a/src/app/state/hooks/spaceSettings.ts +++ b/src/app/state/hooks/spaceSettings.ts @@ -27,7 +27,7 @@ export const useOpenSpaceSettings = (): OpenCallback => { (roomId, spaceId, page) => { setSettings({ roomId, spaceId, page }); }, - [setSettings] + [setSettings], ); return open; diff --git a/src/app/state/hooks/unread.ts b/src/app/state/hooks/unread.ts index 62386d02..d15d3933 100644 --- a/src/app/state/hooks/unread.ts +++ b/src/app/state/hooks/unread.ts @@ -28,18 +28,18 @@ const getRoomsUnread = (rooms: string[], roomToUnread: RoomToUnread): Unread | u export const useRoomsUnread = ( rooms: string[], - roomToUnreadAtm: typeof roomToUnreadAtom + roomToUnreadAtm: typeof roomToUnreadAtom, ): Unread | undefined => { const selector = useCallback( (roomToUnread: RoomToUnread) => getRoomsUnread(rooms, roomToUnread), - [rooms] + [rooms], ); return useAtomValue(selectAtom(roomToUnreadAtm, selector, compareUnreadEqual)); }; export const useRoomUnread = ( roomId: string, - roomToUnreadAtm: typeof roomToUnreadAtom + roomToUnreadAtm: typeof roomToUnreadAtom, ): Unread | undefined => { const selector = useCallback((roomToUnread: RoomToUnread) => roomToUnread.get(roomId), [roomId]); return useAtomValue(selectAtom(roomToUnreadAtm, selector, compareUnreadEqual)); diff --git a/src/app/state/hooks/userRoomProfile.ts b/src/app/state/hooks/userRoomProfile.ts index 7fed0c08..68546efa 100644 --- a/src/app/state/hooks/userRoomProfile.ts +++ b/src/app/state/hooks/userRoomProfile.ts @@ -25,7 +25,7 @@ type OpenCallback = ( spaceId: string | undefined, userId: string, cords: RectCords, - position?: Position + position?: Position, ) => void; export const useOpenUserRoomProfile = (): OpenCallback => { const setUserRoomProfile = useSetAtom(userRoomProfileAtom); @@ -34,7 +34,7 @@ export const useOpenUserRoomProfile = (): OpenCallback => { (roomId, spaceId, userId, cords, position) => { setUserRoomProfile({ roomId, spaceId, userId, cords, position }); }, - [setUserRoomProfile] + [setUserRoomProfile], ); return open; diff --git a/src/app/state/joiningProgress.ts b/src/app/state/joiningProgress.ts index 5c60af2a..c1ec1727 100644 --- a/src/app/state/joiningProgress.ts +++ b/src/app/state/joiningProgress.ts @@ -33,5 +33,5 @@ export const updateJoiningProgressAtom = atom( } set(joiningProgressAtom, newMap); - } + }, ); diff --git a/src/app/state/list.ts b/src/app/state/list.ts index 4377e532..f8f24d41 100644 --- a/src/app/state/list.ts +++ b/src/app/state/list.ts @@ -6,9 +6,9 @@ export type ListAction = item: T | T[]; } | { - type: 'REPLACE'; - item: T; - replacement: T; + type: 'REPLACE'; + item: T; + replacement: T; } | { type: 'DELETE'; @@ -25,7 +25,7 @@ export const createListAtom = () => { if (action.type === 'DELETE') { set( baseListAtom, - items.filter((item) => !newItems.includes(item)) + items.filter((item) => !newItems.includes(item)), ); return; } @@ -34,9 +34,12 @@ export const createListAtom = () => { return; } if (action.type === 'REPLACE') { - set(baseListAtom, items.map((item) => item === action.item ? action.replacement : item)); + set( + baseListAtom, + items.map((item) => (item === action.item ? action.replacement : item)), + ); } - } + }, ); }; -export type TListAtom = ReturnType>; \ No newline at end of file +export type TListAtom = ReturnType>; diff --git a/src/app/state/mDirectList.ts b/src/app/state/mDirectList.ts index 95165255..0adaf750 100644 --- a/src/app/state/mDirectList.ts +++ b/src/app/state/mDirectList.ts @@ -14,7 +14,7 @@ export const mDirectAtom = atom, [MDirectAction], undefined>( (get) => get(baseMDirectAtom), (get, set, action) => { set(baseMDirectAtom, action.rooms); - } + }, ); export const useBindMDirectAtom = (mx: MatrixClient, mDirect: typeof mDirectAtom) => { diff --git a/src/app/state/mediaDimensionCache.ts b/src/app/state/mediaDimensionCache.ts index 73c216a3..01da4674 100644 --- a/src/app/state/mediaDimensionCache.ts +++ b/src/app/state/mediaDimensionCache.ts @@ -72,12 +72,7 @@ const touchEntry = (mxcUrl: string, patch: Partial): void => { blurHash: patch.blurHash ?? prev?.blurHash, }; if (next.w <= 0 || next.h <= 0) return; - if ( - prev && - prev.w === next.w && - prev.h === next.h && - prev.blurHash === next.blurHash - ) { + if (prev && prev.w === next.w && prev.h === next.h && prev.blurHash === next.blurHash) { return; } if (prev) delete cache[mxcUrl]; @@ -97,7 +92,7 @@ export const resolveAttachmentBoxSize = ( mxcUrl: string | undefined, w?: number, h?: number, - maxSize: number = ATTACHMENT_MAX_SIZE + maxSize: number = ATTACHMENT_MAX_SIZE, ): { width: number; height: number } => { const cached = mxcUrl && (!w || !h) ? getMediaDimensions(mxcUrl) : undefined; const naturalW = w && w > 0 ? w : cached?.w; @@ -115,7 +110,12 @@ export const getMediaBlurHash = (mxcUrl: string): string | undefined => { return validBlurHash(loadCache()[mxcUrl]?.blurHash); }; -export const setMediaBlurHash = (mxcUrl: string, blurHash: string, w?: number, h?: number): void => { +export const setMediaBlurHash = ( + mxcUrl: string, + blurHash: string, + w?: number, + h?: number, +): void => { const hash = validBlurHash(blurHash); if (!mxcUrl || !hash) return; const cache = loadCache(); @@ -132,20 +132,16 @@ export const setMediaBlurHash = (mxcUrl: string, blurHash: string, w?: number, h /** Encode + cache a blurhash from a loaded image/video (idle, non-blocking). */ export const rememberMediaBlurHash = ( mxcUrl: string, - media: HTMLImageElement | HTMLVideoElement + media: HTMLImageElement | HTMLVideoElement, ): void => { if (!mxcUrl || typeof window === 'undefined') return; const run = () => { try { const w = - media instanceof HTMLVideoElement - ? media.videoWidth - : media.naturalWidth || media.width; + media instanceof HTMLVideoElement ? media.videoWidth : media.naturalWidth || media.width; const h = - media instanceof HTMLVideoElement - ? media.videoHeight - : media.naturalHeight || media.height; + media instanceof HTMLVideoElement ? media.videoHeight : media.naturalHeight || media.height; if (w <= 0 || h <= 0) return; setMediaDimensions(mxcUrl, w, h); diff --git a/src/app/state/navToActivePath.ts b/src/app/state/navToActivePath.ts index affc313d..66a6863b 100644 --- a/src/app/state/navToActivePath.ts +++ b/src/app/state/navToActivePath.ts @@ -38,7 +38,7 @@ export const makeNavToActivePathAtom = (userId: string): NavToActivePathAtom => (key, value) => { const obj: Record = Object.fromEntries(value); setLocalStorageItem(key, obj); - } + }, ); const navToActivePathAtom = atom( @@ -49,7 +49,7 @@ export const makeNavToActivePathAtom = (userId: string): NavToActivePathAtom => baseNavToActivePathAtom, produce(get(baseNavToActivePathAtom), (draft) => { draft.delete(action.navId); - }) + }), ); return; } @@ -58,10 +58,10 @@ export const makeNavToActivePathAtom = (userId: string): NavToActivePathAtom => baseNavToActivePathAtom, produce(get(baseNavToActivePathAtom), (draft) => { draft.set(action.navId, action.path); - }) + }), ); } - } + }, ); return navToActivePathAtom; diff --git a/src/app/state/openedSidebarFolder.ts b/src/app/state/openedSidebarFolder.ts index 743160d4..2da66804 100644 --- a/src/app/state/openedSidebarFolder.ts +++ b/src/app/state/openedSidebarFolder.ts @@ -36,7 +36,7 @@ export const makeOpenedSidebarFolderAtom = (userId: string): OpenedSidebarFolder (key, value) => { const arrayValue = Array.from(value); setLocalStorageItem(key, arrayValue); - } + }, ); const openedSidebarFolderAtom = atom, [OpenedSidebarFolderAction], undefined>( @@ -47,7 +47,7 @@ export const makeOpenedSidebarFolderAtom = (userId: string): OpenedSidebarFolder baseOpenedSidebarFolderAtom, produce(get(baseOpenedSidebarFolderAtom), (draft) => { draft.delete(action.id); - }) + }), ); return; } @@ -56,10 +56,10 @@ export const makeOpenedSidebarFolderAtom = (userId: string): OpenedSidebarFolder baseOpenedSidebarFolderAtom, produce(get(baseOpenedSidebarFolderAtom), (draft) => { draft.add(action.id); - }) + }), ); } - } + }, ); return openedSidebarFolderAtom; diff --git a/src/app/state/releaseNotes.ts b/src/app/state/releaseNotes.ts index 2c071eea..9c610801 100644 --- a/src/app/state/releaseNotes.ts +++ b/src/app/state/releaseNotes.ts @@ -31,7 +31,7 @@ export function storePendingReleaseNotes(version: string, releaseNotes: unknown) try { localStorage.setItem( PENDING_RELEASE_NOTES_KEY, - JSON.stringify({ version, releaseNotes } satisfies PendingReleaseNotes) + JSON.stringify({ version, releaseNotes } satisfies PendingReleaseNotes), ); } catch { // ignore quota errors diff --git a/src/app/state/room-list/inviteList.ts b/src/app/state/room-list/inviteList.ts index 4fa97be4..7a2fe3d6 100644 --- a/src/app/state/room-list/inviteList.ts +++ b/src/app/state/room-list/inviteList.ts @@ -17,16 +17,16 @@ export const allInvitesAtom = atom( if (action.type === 'PUT') newIds.push(action.roomId); return newIds; }); - } + }, ); export const useBindAllInvitesAtom = ( mx: MatrixClient, - allRooms: WritableAtom + allRooms: WritableAtom, ) => { useBindRoomsWithMembershipsAtom( mx, allRooms, - useMemo(() => [Membership.Invite], []) + useMemo(() => [Membership.Invite], []), ); }; diff --git a/src/app/state/room-list/roomList.ts b/src/app/state/room-list/roomList.ts index 736a0bc2..05ae9200 100644 --- a/src/app/state/room-list/roomList.ts +++ b/src/app/state/room-list/roomList.ts @@ -17,12 +17,12 @@ export const allRoomsAtom = atom( if (action.type === 'PUT') newIds.push(action.roomId); return newIds; }); - } + }, ); export const useBindAllRoomsAtom = (mx: MatrixClient, allRooms: typeof allRoomsAtom) => { useBindRoomsWithMembershipsAtom( mx, allRooms, - useMemo(() => [Membership.Join], []) + useMemo(() => [Membership.Join], []), ); }; diff --git a/src/app/state/room-list/utils.ts b/src/app/state/room-list/utils.ts index 1ca7e7de..3222f165 100644 --- a/src/app/state/room-list/utils.ts +++ b/src/app/state/room-list/utils.ts @@ -16,7 +16,7 @@ export type RoomsAction = export const useBindRoomsWithMembershipsAtom = ( mx: MatrixClient, roomsAtom: WritableAtom, - memberships: Membership[] + memberships: Membership[], ) => { const setRoomsAtom = useSetAtom(roomsAtom); diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index 5d8ec8c7..3c316729 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -20,9 +20,7 @@ export type TUploadItem = { export type TUploadListAtom = ReturnType>; -export const roomIdToUploadItemsAtomFamily = atomFamily( - createListAtom -); +export const roomIdToUploadItemsAtomFamily = atomFamily(createListAtom); export const roomUploadAtomFamily = createUploadAtomFamily(); @@ -40,7 +38,7 @@ export type RoomIdToMsgAction = const createMsgDraftAtom = () => atom([]); export type TMsgDraftAtom = ReturnType; export const roomIdToMsgDraftAtomFamily = atomFamily(() => - createMsgDraftAtom() + createMsgDraftAtom(), ); export type IReplyDraft = { @@ -53,5 +51,5 @@ export type IReplyDraft = { const createReplyDraftAtom = () => atom(undefined); export type TReplyDraftAtom = ReturnType; export const roomIdToReplyDraftAtomFamily = atomFamily(() => - createReplyDraftAtom() + createReplyDraftAtom(), ); diff --git a/src/app/state/room/roomToParents.ts b/src/app/state/room/roomToParents.ts index ac824acd..c50395c5 100644 --- a/src/app/state/room/roomToParents.ts +++ b/src/app/state/room/roomToParents.ts @@ -46,7 +46,7 @@ export const roomToParentsAtom = atom { mapParentWithChildren(draftRoomToParents, action.parent, action.children); - }) + }), ); return; } @@ -61,15 +61,15 @@ export const roomToParentsAtom = atom draftRoomToParents.delete(room)); - }) + }), ); } - } + }, ); export const useBindRoomToParentsAtom = ( mx: MatrixClient, - roomToParents: typeof roomToParentsAtom + roomToParents: typeof roomToParentsAtom, ) => { const setRoomToParents = useSetAtom(roomToParents); diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 13b997a3..08140f97 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -53,7 +53,7 @@ export const unreadInfoToUnread = (unreadInfo: UnreadInfo): Unread => ({ const putUnreadInfo = ( roomToUnread: RoomToUnread, allParents: Set, - unreadInfo: UnreadInfo + unreadInfo: UnreadInfo, ) => { const oldUnread = roomToUnread.get(unreadInfo.roomId) ?? { highlight: 0, total: 0, from: null }; roomToUnread.set(unreadInfo.roomId, unreadInfoToUnread(unreadInfo)); @@ -125,7 +125,7 @@ export const roomToUnreadAtom = atom { @@ -191,8 +191,8 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }); } }, - [mx, setUnreadAtom] - ) + [mx, setUnreadAtom], + ), ); useEffect(() => { @@ -201,7 +201,7 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo room: Room | undefined, toStartOfTimeline: boolean | undefined, removed: boolean, - data: IRoomTimelineData + data: IRoomTimelineData, ) => { if (!room || !data.liveEvent || room.isSpaceRoom() || !isNotificationEvent(mEvent)) return; if (getNotificationType(mx, room.roomId) === NotificationType.Mute) { @@ -230,8 +230,8 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo const isMyReceipt = Object.keys(content).find((eventId) => (Object.keys(content[eventId]) as ReceiptType[]).find( - (receiptType) => content[eventId][receiptType][myUserId] - ) + (receiptType) => content[eventId][receiptType][myUserId], + ), ); if (isMyReceipt) { setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); @@ -276,7 +276,7 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }); } }, - [mx, setUnreadAtom] - ) + [mx, setUnreadAtom], + ), ); }; diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index b61da404..0c93be42 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -33,7 +33,7 @@ export function setFallbackSession( accessToken: string, deviceId: string, userId: string, - baseUrl: string + baseUrl: string, ) { localStorage.setItem('cinny_access_token', accessToken); localStorage.setItem('cinny_device_id', deviceId); @@ -104,7 +104,7 @@ const baseSessionsAtom = atomWithLocalStorage( const fallbackWithoutStoreFlag = { ...fallbackSession, fallbackSdkStores: false }; // Check if this session already exists (by userId + deviceId) const exists = sessions.some( - s => s.userId === fallbackSession.userId && s.deviceId === fallbackSession.deviceId + (s) => s.userId === fallbackSession.userId && s.deviceId === fallbackSession.deviceId, ); if (!exists) { sessions.push(fallbackWithoutStoreFlag); @@ -115,7 +115,7 @@ const baseSessionsAtom = atomWithLocalStorage( }, (key, value) => { setLocalStorageItem(key, value); - } + }, ); export type SessionsAction = @@ -134,7 +134,8 @@ export const sessionsAtom = atom( if (action.type === 'PUT') { const sessions = [...get(baseSessionsAtom)]; const sessionIndex = sessions.findIndex( - (session) => session.userId === action.session.userId && session.deviceId === action.session.deviceId + (session) => + session.userId === action.session.userId && session.deviceId === action.session.deviceId, ); if (sessionIndex === -1) { sessions.push(action.session); @@ -146,11 +147,14 @@ export const sessionsAtom = atom( } if (action.type === 'DELETE') { const sessions = get(baseSessionsAtom).filter( - (session) => !(session.userId === action.session.userId && session.deviceId === action.session.deviceId) + (session) => + !( + session.userId === action.session.userId && session.deviceId === action.session.deviceId + ), ); set(baseSessionsAtom, sessions); } - } + }, ); // Current selected session @@ -158,7 +162,7 @@ export const CURRENT_SESSION_KEY = 'currentSessionUserId'; export const currentSessionAtom = atomWithLocalStorage( CURRENT_SESSION_KEY, (key) => getLocalStorageItem(key, undefined), - (key, value) => setLocalStorageItem(key, value) + (key, value) => setLocalStorageItem(key, value), ); // Helper to get current session from sessions list @@ -168,13 +172,13 @@ export const getCurrentSession = (): Session | undefined => { // Fallback to old session for migration return getFallbackSession(); } - + const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); - return sessions.find(s => s.userId === currentUserId); + return sessions.find((s) => s.userId === currentUserId); }; // Helper to get a session by userId export const getSessionByUserId = (userId: string): Session | undefined => { const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); - return sessions.find(s => s.userId === userId); + return sessions.find((s) => s.userId === userId); }; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 1839691b..cccbcc24 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -65,7 +65,7 @@ export interface Settings { developerTools: boolean; autoJoinSpaceRooms: boolean; - + scrollToLatestBehavior: ScrollToLatestBehavior; } @@ -111,22 +111,22 @@ const defaultSettings: Settings = { developerTools: false, autoJoinSpaceRooms: true, - + scrollToLatestBehavior: ScrollToLatestBehavior.Always, }; export const getSettings = () => { const settings = localStorage.getItem(STORAGE_KEY); if (settings === null) return defaultSettings; - + const parsed = JSON.parse(settings) as Settings & { twitterEmoji?: boolean }; - + // Migrate old twitterEmoji boolean to new emojiStyle enum if ('twitterEmoji' in parsed && parsed.emojiStyle === undefined) { parsed.emojiStyle = parsed.twitterEmoji ? EmojiStyle.Twemoji : EmojiStyle.Apple; delete parsed.twitterEmoji; } - + return { ...defaultSettings, ...parsed, @@ -143,5 +143,5 @@ export const settingsAtom = atom( (get, set, update) => { set(baseSettings, update); setSettings(update); - } + }, ); diff --git a/src/app/state/spaceRooms.ts b/src/app/state/spaceRooms.ts index 572fade3..7196decd 100644 --- a/src/app/state/spaceRooms.ts +++ b/src/app/state/spaceRooms.ts @@ -17,7 +17,7 @@ const baseSpaceRoomsAtom = atomWithLocalStorage>( (key, value) => { const arrayValue = Array.from(value); setLocalStorageItem(key, arrayValue); - } + }, ); type SpaceRoomsAction = @@ -41,7 +41,7 @@ export const spaceRoomsAtom = atom, [SpaceRoomsAction], undefined>( baseSpaceRoomsAtom, produce(current, (draft) => { roomIds.forEach((roomId) => draft.delete(roomId)); - }) + }), ); return; } @@ -52,8 +52,8 @@ export const spaceRoomsAtom = atom, [SpaceRoomsAction], undefined>( baseSpaceRoomsAtom, produce(current, (draft) => { newEntries.forEach((roomId) => draft.add(roomId)); - }) + }), ); } - } + }, ); diff --git a/src/app/state/typingMembers.ts b/src/app/state/typingMembers.ts index 8331828a..b278381a 100644 --- a/src/app/state/typingMembers.ts +++ b/src/app/state/typingMembers.ts @@ -30,7 +30,7 @@ const baseRoomIdToTypingMembersAtom = atom(new Map()); const putTypingMember = ( roomToMembers: IRoomIdToTypingMembers, - action: TypingMemberPutAction + action: TypingMemberPutAction, ): IRoomIdToTypingMembers => { let typingMembers = roomToMembers.get(action.roomId) ?? []; @@ -45,7 +45,7 @@ const putTypingMember = ( const deleteTypingMember = ( roomToMembers: IRoomIdToTypingMembers, - action: TypingMemberDeleteAction + action: TypingMemberDeleteAction, ): IRoomIdToTypingMembers => { let typingMembers = roomToMembers.get(action.roomId) ?? []; @@ -62,7 +62,7 @@ const timeoutReceipt = ( roomToMembers: IRoomIdToTypingMembers, roomId: string, userId: string, - timeout: number + timeout: number, ): boolean | undefined => { const typingMembers = roomToMembers.get(roomId) ?? []; @@ -84,7 +84,7 @@ export const roomIdToTypingMembersAtom = atom< if (action.type === 'PUT') { set( baseRoomIdToTypingMembersAtom, - produce(rToTyping, (draft) => putTypingMember(draft, action)) + produce(rToTyping, (draft) => putTypingMember(draft, action)), ); // remove typing receipt after some timeout @@ -95,7 +95,7 @@ export const roomIdToTypingMembersAtom = atom< get(baseRoomIdToTypingMembersAtom), roomId, userId, - TYPING_TIMEOUT_MS + TYPING_TIMEOUT_MS, ); if (timeout) { set( @@ -105,8 +105,8 @@ export const roomIdToTypingMembersAtom = atom< type: 'DELETE', roomId, userId, - }) - ) + }), + ), ); } }, TYPING_TIMEOUT_MS); @@ -118,15 +118,15 @@ export const roomIdToTypingMembersAtom = atom< ) { set( baseRoomIdToTypingMembersAtom, - produce(rToTyping, (draft) => deleteTypingMember(draft, action)) + produce(rToTyping, (draft) => deleteTypingMember(draft, action)), ); } - } + }, ); export const useBindRoomIdToTypingMembersAtom = ( mx: MatrixClient, - typingMembersAtom: typeof roomIdToTypingMembersAtom + typingMembersAtom: typeof roomIdToTypingMembersAtom, ) => { const setTypingMembers = useSetAtom(typingMembersAtom); const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); @@ -134,7 +134,7 @@ export const useBindRoomIdToTypingMembersAtom = ( useEffect(() => { const handleTypingEvent: RoomMemberEventHandlerMap[RoomMemberEvent.Typing] = ( event, - member + member, ) => { if (hideActivity) { return; diff --git a/src/app/state/upload.ts b/src/app/state/upload.ts index 810c0d2e..b1311376 100644 --- a/src/app/state/upload.ts +++ b/src/app/state/upload.ts @@ -92,7 +92,7 @@ export const createUploadAtom = (file: TUploadContent) => { error: update.error, }); } - } + }, ); }; export type TUploadAtom = ReturnType; @@ -100,14 +100,14 @@ export type TUploadAtom = ReturnType; export const useBindUploadAtom = ( mx: MatrixClient, uploadAtom: TUploadAtom, - hideFilename?: boolean + hideFilename?: boolean, ) => { const [upload, setUpload] = useAtom(uploadAtom); const { file } = upload; const handleProgress = useThrottle( useCallback((progress: UploadProgress) => setUpload({ progress }), [setUpload]), - { immediate: true, wait: 200 } + { immediate: true, wait: 200 }, ); const startUpload = useCallback( @@ -119,7 +119,7 @@ export const useBindUploadAtom = ( onSuccess: (mxc) => setUpload({ mxc }), onError: (error) => setUpload({ error }), }), - [mx, file, hideFilename, setUpload, handleProgress] + [mx, file, hideFilename, setUpload, handleProgress], ); const cancelUpload = useCallback(async () => { @@ -141,6 +141,6 @@ export type TUploadAtomFamily = ReturnType; export const createUploadFamilyObserverAtom = ( uploadFamily: TUploadAtomFamily, - uploads: TUploadContent[] + uploads: TUploadContent[], ) => atom((get) => uploads.map((upload) => get(uploadFamily(upload)))); export type TUploadFamilyObserverAtom = ReturnType; diff --git a/src/app/state/utils/atomWithLocalStorage.ts b/src/app/state/utils/atomWithLocalStorage.ts index f17d3a3d..26b8dae8 100644 --- a/src/app/state/utils/atomWithLocalStorage.ts +++ b/src/app/state/utils/atomWithLocalStorage.ts @@ -21,7 +21,7 @@ export type SetLocalStorageItem = (key: string, value: T) => void; export const atomWithLocalStorage = ( key: string, getItem: GetLocalStorageItem, - setItem: SetLocalStorageItem + setItem: SetLocalStorageItem, ) => { const value = getItem(key); @@ -44,7 +44,7 @@ export const atomWithLocalStorage = ( (get, set, newValue) => { set(baseAtom, newValue); setItem(key, newValue); - } + }, ); return localStorageAtom; diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index 61b2481a..745e2e0b 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -39,7 +39,7 @@ export class ASCIILexicalTable { console.warn( `[!] Warning: ASCIILexicalTable size is larger than the Number.MAX_SAFE_INTEGER: ${this.size()} > ${ Number.MAX_SAFE_INTEGER - }` + }`, ); } } @@ -333,7 +333,7 @@ export class ASCIILexicalTable { const findNextFilledKey = ( fromIndex: number, - keys: Array + keys: Array, ): [number, string] | [-1, undefined] => { for (let j = fromIndex; j < keys.length; j += 1) { const key = keys[j]; @@ -347,11 +347,11 @@ const findNextFilledKey = ( export const orderKeys = ( lex: ASCIILexicalTable, - keys: Array + keys: Array, ): Array | undefined => { const newKeys: string[] = []; - for (let i = 0; i < keys.length; ) { + for (let i = 0; i < keys.length;) { const key = keys[i]; const collectedKeys: string[] = []; const [nextKeyIndex, nextKey] = findNextFilledKey(i + 1, keys); @@ -368,7 +368,7 @@ export const orderKeys = ( const generatedKeys = lex.nBetween( keyToGenerateCount, key ?? lex.first(), - nextKey ?? lex.last() + nextKey ?? lex.last(), ); if (generatedKeys) { collectedKeys.push(...generatedKeys); diff --git a/src/app/utils/AsyncSearch.ts b/src/app/utils/AsyncSearch.ts index 4baacf04..66098445 100644 --- a/src/app/utils/AsyncSearch.ts +++ b/src/app/utils/AsyncSearch.ts @@ -14,18 +14,18 @@ export type AsyncSearchOption = { export type MatchHandler = ( item: TSearchItem, - query: string + query: string, ) => boolean; export type ResultHandler = ( results: TSearchItem[], - query: string + query: string, ) => void; export type AsyncSearchHandler = (query: string) => void; export type TerminateAsyncSearch = () => void; export const normalize = (str: string, options?: NormalizeOption) => { - let nStr = str.normalize(options?.normalizeUnicode ?? true ? 'NFKC' : 'NFC'); + let nStr = str.normalize((options?.normalizeUnicode ?? true) ? 'NFKC' : 'NFC'); if (!options?.caseSensitive) nStr = nStr.toLocaleLowerCase(); if (options?.ignoreWhitespace ?? true) nStr = nStr.replace(/\s/g, ''); return nStr; @@ -40,7 +40,7 @@ export const AsyncSearch = ( list: TSearchItem[], match: MatchHandler, onResult: ResultHandler, - options?: AsyncSearchOption + options?: AsyncSearchOption, ): [AsyncSearchHandler, TerminateAsyncSearch] => { let resultList: TSearchItem[] = []; diff --git a/src/app/utils/androidShare.ts b/src/app/utils/androidShare.ts index 441228f9..3361b940 100644 --- a/src/app/utils/androidShare.ts +++ b/src/app/utils/androidShare.ts @@ -30,7 +30,7 @@ interface AndroidShareHandlerPlugin { clearPendingShare(): Promise; addListener( eventName: 'shareReceived', - listenerFunc: (payload: AndroidSharePayload) => void + listenerFunc: (payload: AndroidSharePayload) => void, ): Promise; } @@ -41,7 +41,8 @@ const getAndroidShareHandler = async (): Promise => { /** Returns true when the Android share bridge is available. */ export const isAndroidShareSupported = (): boolean => { - const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }).Capacitor; + const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }) + .Capacitor; return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android'); }; @@ -62,7 +63,7 @@ export const clearPendingAndroidShare = async (): Promise => { /** Subscribes to new incoming native share payloads. */ export const listenForAndroidShares = async ( - listener: (payload: AndroidSharePayload) => void + listener: (payload: AndroidSharePayload) => void, ): Promise => { if (!isAndroidShareSupported()) return undefined; const AndroidShareHandler = await getAndroidShareHandler(); @@ -72,7 +73,7 @@ export const listenForAndroidShares = async ( /** Converts a cached native shared file into a browser File for upload. */ export const materializeSharedFile = async ( sharedFile: AndroidSharedFile, - receivedAt: number + receivedAt: number, ): Promise => { const { Capacitor } = await loadCapacitorCore(); const fileUrl = Capacitor.convertFileSrc(sharedFile.path); @@ -86,4 +87,4 @@ export const materializeSharedFile = async ( type: sharedFile.mimeType || blob.type, lastModified: receivedAt, }); -}; \ No newline at end of file +}; diff --git a/src/app/utils/animatedStickerConverter.ts b/src/app/utils/animatedStickerConverter.ts index f057d15b..f5206aa9 100644 --- a/src/app/utils/animatedStickerConverter.ts +++ b/src/app/utils/animatedStickerConverter.ts @@ -1,8 +1,7 @@ -// eslint-disable-next-line import/no-extraneous-dependencies import lottie from 'lottie-web/build/player/lottie_light'; -// eslint-disable-next-line import/no-extraneous-dependencies + import { inflate } from 'pako'; -// eslint-disable-next-line import/no-extraneous-dependencies + import GIF from 'gif.js'; /** Animation item type from lottie-web */ @@ -18,7 +17,7 @@ const GIF_QUALITY = 10; const MAX_GIF_SIZE = 256; /** Transparency key color (magenta) - this color becomes transparent in the GIF */ -const TRANSPARENT_COLOR = 0xFF00FF; +const TRANSPARENT_COLOR = 0xff00ff; /** * Decompress a TGS file (gzipped Lottie JSON) @@ -40,7 +39,7 @@ function decompressTgs(tgsData: ArrayBuffer): object { async function renderLottieToGif( animationData: object, width: number, - height: number + height: number, ): Promise { return new Promise((resolve, reject) => { // Create a hidden container for rendering @@ -130,7 +129,7 @@ async function renderLottieToGif( // Calculate the animation frame to seek to const progress = frameIndex / framesToCapture; const animFrame = Math.floor(progress * totalFrames); - + animation.goToAndStop(animFrame, true); // Get the SVG content and render to canvas @@ -194,7 +193,7 @@ async function renderLottieToGif( export async function tgsToGif( tgsBlob: Blob, targetWidth = 256, - targetHeight = 256 + targetHeight = 256, ): Promise { // eslint-disable-next-line no-console console.log('tgsToGif: Starting conversion, blob size:', tgsBlob.size); @@ -218,7 +217,7 @@ export async function tgsToGif( export async function webmToGif( webmBlob: Blob, targetWidth = 256, - targetHeight = 256 + targetHeight = 256, ): Promise { // eslint-disable-next-line no-console console.log('webmToGif: Starting conversion, blob size:', webmBlob.size); @@ -226,7 +225,7 @@ export async function webmToGif( const video = document.createElement('video'); video.muted = true; video.playsInline = true; - + const canvas = document.createElement('canvas'); const width = Math.min(targetWidth, MAX_GIF_SIZE); const height = Math.min(targetHeight, MAX_GIF_SIZE); diff --git a/src/app/utils/auth.ts b/src/app/utils/auth.ts index 70626901..9dc7b61d 100644 --- a/src/app/utils/auth.ts +++ b/src/app/utils/auth.ts @@ -38,7 +38,7 @@ export function getGlobalMatrixClient(): MatrixClient | null { export function updateSessionToken(userId: string, newToken: string): void { const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); const sessionIndex = sessions.findIndex((s: Session) => s.userId === userId); - + if (sessionIndex >= 0) { sessions[sessionIndex] = { ...sessions[sessionIndex], @@ -53,7 +53,7 @@ export function updateSessionToken(userId: string, newToken: string): void { * Prioritizes the token from the active MatrixClient instance (most up-to-date), * then falls back to localStorage. This ensures we always use the freshest token, * even if it's been refreshed by the SDK. - * + * * @returns The current access token or undefined if no session is active */ export function getCurrentAccessToken(): string | undefined { @@ -65,31 +65,31 @@ export function getCurrentAccessToken(): string | undefined { return clientToken; } } - + // Fall back to localStorage if MatrixClient is not available or doesn't have a token const currentUserId = getLocalStorageItem(CURRENT_SESSION_KEY, undefined); - + if (!currentUserId) { // Fallback to old single-account storage for migration return localStorage.getItem('cinny_access_token') ?? undefined; } - + const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); const currentSession = sessions.find((s: Session) => s.userId === currentUserId); - + return currentSession?.accessToken; } /** * Get the access token for a specific user. * Useful when you need to fetch data for a non-active account. - * + * * @param userId - The Matrix user ID * @returns The access token for the specified user or undefined */ export function getAccessTokenForUser(userId: string): string | undefined { const sessions = getLocalStorageItem(MATRIX_SESSIONS_KEY, []); const session = sessions.find((s: Session) => s.userId === userId); - + return session?.accessToken; } diff --git a/src/app/utils/authenticatedMediaCache.ts b/src/app/utils/authenticatedMediaCache.ts index ada3251f..c4c8619e 100644 --- a/src/app/utils/authenticatedMediaCache.ts +++ b/src/app/utils/authenticatedMediaCache.ts @@ -9,8 +9,7 @@ const inflight = new Map>(); export const isAuthenticatedMediaUrl = (url: string): boolean => url.includes('/_matrix/client/v1/media/download') || url.includes('/_matrix/client/v1/media/thumbnail') || - (url.includes('/_matrix/media/') && - (url.includes('/download/') || url.includes('/thumbnail/'))); + (url.includes('/_matrix/media/') && (url.includes('/download/') || url.includes('/thumbnail/'))); export const getCachedAuthenticatedMediaUrl = (src: string | undefined): string | undefined => { if (!src) return undefined; @@ -56,7 +55,7 @@ const fetchBlobUrl = async (src: string): Promise => { */ export const resolveAuthenticatedMediaUrl = async ( src: string, - useAuthentication: boolean + useAuthentication: boolean, ): Promise => { if (!useAuthentication || !isAuthenticatedMediaUrl(src)) { return src; diff --git a/src/app/utils/backgroundSync.ts b/src/app/utils/backgroundSync.ts index 2939f587..96ab56d5 100644 --- a/src/app/utils/backgroundSync.ts +++ b/src/app/utils/backgroundSync.ts @@ -62,15 +62,15 @@ interface MatrixBackgroundSyncPlugin { resolveUnifiedPushGateway(options: { endpoint: string }): Promise<{ gatewayUrl: string }>; addListener( eventName: 'unifiedPushNewEndpoint', - listenerFunc: (event: UnifiedPushEndpointEvent) => void + listenerFunc: (event: UnifiedPushEndpointEvent) => void, ): Promise; addListener( eventName: 'unifiedPushUnregistered', - listenerFunc: (event: UnifiedPushUnregisteredEvent) => void + listenerFunc: (event: UnifiedPushUnregisteredEvent) => void, ): Promise; addListener( eventName: 'unifiedPushRegistrationFailed', - listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void + listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void, ): Promise; } @@ -79,13 +79,15 @@ type StoredPusherState = { appId: string; }; -const DEFAULT_UNIFIED_PUSH_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify'; +const DEFAULT_UNIFIED_PUSH_GATEWAY = + 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify'; const PUSHER_APP_ID_BASE = 'com.paarrot.app.android'; const PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush'; /** Returns true when the current platform is Android Capacitor. */ export const isBackgroundSyncSupported = (): boolean => { - const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }).Capacitor; + const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] }) + .Capacitor; return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android'); }; @@ -99,7 +101,7 @@ const buildPusherAppId = (deviceId: string | null): string => { const loadStoredPusherState = ( userId: string | null, - deviceId: string | null + deviceId: string | null, ): StoredPusherState | undefined => { if (typeof window === 'undefined' || !window.localStorage) return undefined; @@ -116,7 +118,7 @@ const loadStoredPusherState = ( const saveStoredPusherState = ( userId: string | null, deviceId: string | null, - state: StoredPusherState + state: StoredPusherState, ): void => { if (typeof window === 'undefined' || !window.localStorage) return; window.localStorage.setItem(getStoredPusherKey(userId, deviceId), JSON.stringify(state)); @@ -196,8 +198,13 @@ class AndroidUnifiedPushManager { const { Capacitor, registerPlugin } = await loadCapacitorCore(); const MatrixBackgroundSync = registerPlugin('MatrixBackgroundSync'); - console.log('[BackgroundSync] start() called, platform:', Capacitor.getPlatform(), 'isNative:', Capacitor.isNativePlatform()); - + console.log( + '[BackgroundSync] start() called, platform:', + Capacitor.getPlatform(), + 'isNative:', + Capacitor.isNativePlatform(), + ); + if (!isBackgroundSyncSupported()) { console.log('[BackgroundSync] Background sync not supported on this platform'); return; @@ -208,7 +215,12 @@ class AndroidUnifiedPushManager { const userId = mx.getUserId(); const deviceId = mx.getDeviceId(); - console.log('[BackgroundSync] Credentials check:', { userId, deviceId, hasToken: !!accessToken, hasUrl: !!homeserverUrl }); + console.log('[BackgroundSync] Credentials check:', { + userId, + deviceId, + hasToken: !!accessToken, + hasUrl: !!homeserverUrl, + }); if (!homeserverUrl || !accessToken || !userId) { console.warn('[BackgroundSync] Missing credentials, not starting'); @@ -246,7 +258,7 @@ class AndroidUnifiedPushManager { const { registerPlugin } = await loadCapacitorCore(); const MatrixBackgroundSync = registerPlugin('MatrixBackgroundSync'); - const client = this.client; + const { client } = this; if (client) { const deviceId = client.getDeviceId(); const userId = client.getUserId(); @@ -269,7 +281,7 @@ class AndroidUnifiedPushManager { /** Update the Matrix pusher when a new native endpoint is published. */ private async handleNewEndpoint(event: UnifiedPushEndpointEvent): Promise { - const client = this.client; + const { client } = this; if (!client) return; if (event.previousEndpoint) { @@ -281,7 +293,7 @@ class AndroidUnifiedPushManager { /** Remove the Matrix pusher when UnifiedPush unregisters this instance. */ private async handleUnregistered(event: UnifiedPushUnregisteredEvent): Promise { - const client = this.client; + const { client } = this; if (!client) return; const stored = loadStoredPusherState(client.getUserId(), client.getDeviceId()); @@ -311,7 +323,8 @@ class AndroidUnifiedPushManager { private async tryRequestDistributorSetup(): Promise { try { const { registerPlugin } = await loadCapacitorCore(); - const MatrixBackgroundSync = registerPlugin('MatrixBackgroundSync'); + const MatrixBackgroundSync = + registerPlugin('MatrixBackgroundSync'); const setupResult = await MatrixBackgroundSync.requestDistributorSetup(); console.warn('[BackgroundSync] requestDistributorSetup result:', setupResult); const status = await this.safeGetStatus(); @@ -319,7 +332,7 @@ class AndroidUnifiedPushManager { const distributors = normalizeDistributors(status?.distributors ?? []); if (distributors.length === 0) { console.error( - '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.' + '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.', ); this.showNoDistributorPrompt(); } @@ -336,7 +349,7 @@ class AndroidUnifiedPushManager { const distributors = normalizeDistributors(status.distributors); if (!status.registered && distributors.length === 0) { console.error( - '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.' + '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.', ); this.showNoDistributorPrompt(); } @@ -395,7 +408,7 @@ class AndroidUnifiedPushManager { /** Reconcile an already-persisted native endpoint after app startup. */ private async syncExistingEndpoint(): Promise { - const client = this.client; + const { client } = this; if (!client) return; const { registerPlugin } = await loadCapacitorCore(); @@ -457,7 +470,7 @@ class AndroidUnifiedPushManager { private async removePusher( mx: MatrixClient, endpoint: string, - appId = buildPusherAppId(mx.getDeviceId()) + appId = buildPusherAppId(mx.getDeviceId()), ): Promise { try { await mx.setPusher({ @@ -474,7 +487,8 @@ class AndroidUnifiedPushManager { private async safeGetStatus(): Promise { try { const { registerPlugin } = await loadCapacitorCore(); - const MatrixBackgroundSync = registerPlugin('MatrixBackgroundSync'); + const MatrixBackgroundSync = + registerPlugin('MatrixBackgroundSync'); return await MatrixBackgroundSync.getStatus(); } catch (err) { console.warn('[BackgroundSync] Failed to read UnifiedPush status:', err); diff --git a/src/app/utils/blurHash.ts b/src/app/utils/blurHash.ts index 566f6d18..582c1e3e 100644 --- a/src/app/utils/blurHash.ts +++ b/src/app/utils/blurHash.ts @@ -3,7 +3,7 @@ import { encode, isBlurhashValid } from 'blurhash'; export const encodeBlurHash = ( img: HTMLImageElement | HTMLVideoElement, width?: number, - height?: number + height?: number, ): string | undefined => { const imgWidth = img instanceof HTMLVideoElement ? img.videoWidth : img.width; const imgHeight = img instanceof HTMLVideoElement ? img.videoHeight : img.height; diff --git a/src/app/utils/collectibleAssets.ts b/src/app/utils/collectibleAssets.ts index 8ce9ed74..2d3e232c 100644 --- a/src/app/utils/collectibleAssets.ts +++ b/src/app/utils/collectibleAssets.ts @@ -1,6 +1,8 @@ import { DiscordCollectibleItem } from './discordCollectibles'; -function introDurationFromEffectMeta(effect: Record | undefined): number | undefined { +function introDurationFromEffectMeta( + effect: Record | undefined, +): number | undefined { if (!effect) return undefined; const raw = effect.duration ?? effect.durationMs; if (typeof raw !== 'number' || raw <= 0) return undefined; @@ -49,19 +51,21 @@ export function pickCatalogProfileEffectLoopUrl(item: DiscordCollectibleItem): s return catalogAssetUrl(item, 'effect_1', 'effect_0', 'effect_2', 'effect_3'); } -export function catalogProfileEffectIntroDurationMs(item: DiscordCollectibleItem): number | undefined { +export function catalogProfileEffectIntroDurationMs( + item: DiscordCollectibleItem, +): number | undefined { const effect = item.effect?.effects?.[0] as Record | undefined; return introDurationFromEffectMeta(effect); } export function pickStoredProfileEffectIntroUrl( - assetUrls: Record + assetUrls: Record, ): string | undefined { return assetUrls['profile_effect:effect_0']; } export function pickStoredProfileEffectLoopUrl( - assetUrls: Record + assetUrls: Record, ): string | undefined { return ( assetUrls['profile_effect:effect_1'] || @@ -76,7 +80,7 @@ export function isCatalogVideoPreview(url?: string): boolean { } export function pickNameplateUrl( - assetUrls: Record + assetUrls: Record, ): string | undefined { return ( assetUrls['nameplate:animated'] || @@ -87,16 +91,13 @@ export function pickNameplateUrl( } export function pickAvatarDecorationUrl( - assetUrls: Record + assetUrls: Record, ): string | undefined { return assetUrls['avatar_decoration:animated'] || assetUrls['avatar_decoration:animated.png']; } export function pickProfileEffectUrl( - assetUrls: Record + assetUrls: Record, ): string | undefined { - return ( - pickStoredProfileEffectLoopUrl(assetUrls) || - assetUrls['profile_effect:reduced_motion'] - ); + return pickStoredProfileEffectLoopUrl(assetUrls) || assetUrls['profile_effect:reduced_motion']; } diff --git a/src/app/utils/common.ts b/src/app/utils/common.ts index a5573e52..c84a3bca 100644 --- a/src/app/utils/common.ts +++ b/src/app/utils/common.ts @@ -1,6 +1,5 @@ import { IconName, IconSrc } from '../components/icons'; - export const bytesToSize = (bytes: number): string => { const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0KB'; @@ -53,7 +52,7 @@ export const fulfilledPromiseSettledResult = (prs: PromiseSettledResult[]) }, []); export const promiseFulfilledResult = ( - settledResult: PromiseSettledResult + settledResult: PromiseSettledResult, ): T | undefined => { if (settledResult.status === 'fulfilled') return settledResult.value; return undefined; @@ -92,7 +91,7 @@ export const fitMediaSize = ( w: number, h: number, maxW: number, - maxH: number + maxH: number, ): { width: number; height: number } => { if (w <= 0 || h <= 0) { return { width: maxW, height: Math.round(maxW * 0.75) }; @@ -170,15 +169,18 @@ export const stripAlphaFromColor = (color: string): string => { const b = parseInt(rgbaMatch[3], 10).toString(16).padStart(2, '0'); return `#${r}${g}${b}`.toUpperCase(); } - + // Handle hex format let hex = color.replace('#', ''); - + // Convert shorthand #RGB or #RGBA to full form if (hex.length === 3 || hex.length === 4) { - hex = hex.split('').map(c => c + c).join(''); + hex = hex + .split('') + .map((c) => c + c) + .join(''); } - + // Take only the first 6 characters (RGB), ignore alpha if present return `#${hex.substring(0, 6).toUpperCase()}`; }; @@ -191,15 +193,15 @@ export const stripAlphaFromColor = (color: string): string => { export const getContrastingTextColor = (bgColor: string): string => { // Remove # if present const hex = bgColor.replace('#', ''); - + // Parse RGB values (ignore alpha if present) const r = parseInt(hex.substring(0, 2), 16); const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); - + // Calculate relative luminance using WCAG formula const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; - + // Return black for light backgrounds, white for dark backgrounds return luminance > 0.5 ? '#000000' : '#FFFFFF'; }; @@ -212,15 +214,15 @@ export const getContrastingTextColor = (bgColor: string): string => { export const getTextShadowColor = (textColor: string): string => { // Remove # if present const hex = textColor.replace('#', ''); - + // Parse RGB values (ignore alpha if present) const r = parseInt(hex.substring(0, 2), 16); const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); - + // Calculate relative luminance using WCAG formula const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; - + // Return white shadow only for very dark text (luminance < 0.2) return luminance < 0.2 ? '#FFFFFF' : '#000000'; }; diff --git a/src/app/utils/copyHandler.ts b/src/app/utils/copyHandler.ts index fc691c1a..95767512 100644 --- a/src/app/utils/copyHandler.ts +++ b/src/app/utils/copyHandler.ts @@ -3,13 +3,13 @@ import { timeHourMinute } from './time'; /** * Processes selected text from the chat timeline and formats it as: * "Username - Time: Message" - * + * * This intercepts the copy event on the timeline and reformats the copied text. */ export const setupCopyHandler = ( containerRef: React.RefObject, getMessageData: (eventId: string) => { sender: string; ts: number; content: string } | null, - hour24Clock: boolean + hour24Clock: boolean, ): (() => void) => { const container = containerRef.current; if (!container) return () => {}; @@ -20,16 +20,16 @@ export const setupCopyHandler = ( const range = selection.getRangeAt(0); const selectedContainer = range.commonAncestorContainer; - + // Only process if selection is within our container if (!container.contains(selectedContainer)) return; // Find all message elements within the selection const messages: Array<{ sender: string; time: string; content: string }> = []; - + // Get all message elements in the container const messageElements = Array.from(container.querySelectorAll('[data-message-id]')); - + messageElements.forEach((msgEl) => { const eventId = msgEl.getAttribute('data-message-id'); if (!eventId) return; @@ -38,8 +38,10 @@ export const setupCopyHandler = ( if (!data) return; // Find content elements within the message (skip headers, timestamps, etc.) - const contentEl = msgEl.querySelector('[class*="MessageTextBody"], [class*="message-content"], [class*="MessageBody"]') as HTMLElement; - + const contentEl = msgEl.querySelector( + '[class*="MessageTextBody"], [class*="message-content"], [class*="MessageBody"]', + ) as HTMLElement; + if (!contentEl) return; // Check if the content element intersects with the selection @@ -47,12 +49,8 @@ export const setupCopyHandler = ( let isSelected = false; try { // Try to detect if this node or its children are in the selection - const walker = document.createTreeWalker( - contentEl, - NodeFilter.SHOW_TEXT, - null - ); - + const walker = document.createTreeWalker(contentEl, NodeFilter.SHOW_TEXT, null); + let textNode = walker.nextNode(); while (textNode && !isSelected) { if (range.intersectsNode(textNode)) { @@ -69,17 +67,17 @@ export const setupCopyHandler = ( // Format the time const timeStr = timeHourMinute(data.ts, hour24Clock); - + // Extract the selected text from within this message's content let selectedText = ''; - + // Create a range for this message's content const contentRange = document.createRange(); contentRange.selectNodeContents(contentEl); - + // Clone the selection range to avoid modifying it const extractRange = range.cloneRange(); - + // Constrain the extract range to be within the content element // If selection starts before content, move start to content start if (contentRange.compareBoundaryPoints(Range.START_TO_START, extractRange) > 0) { @@ -89,9 +87,9 @@ export const setupCopyHandler = ( if (contentRange.compareBoundaryPoints(Range.END_TO_END, extractRange) < 0) { extractRange.setEnd(contentRange.endContainer, contentRange.endOffset); } - + selectedText = extractRange.toString().trim(); - + if (selectedText) { messages.push({ sender: data.sender, @@ -106,7 +104,7 @@ export const setupCopyHandler = ( const formattedText = messages .map((msg) => `${msg.sender} - ${msg.time}: ${msg.content}`) .join('\n'); - + event.preventDefault(); event.clipboardData?.setData('text/plain', formattedText); } diff --git a/src/app/utils/discordCollectibles.ts b/src/app/utils/discordCollectibles.ts index fe575474..c592cdde 100644 --- a/src/app/utils/discordCollectibles.ts +++ b/src/app/utils/discordCollectibles.ts @@ -51,7 +51,9 @@ type PublishedCatalog = { items: DiscordCollectibleItem[]; }; -function isPublishedCatalog(value: unknown): value is { schema_version: number; items: DiscordCollectibleItem[] } { +function isPublishedCatalog( + value: unknown, +): value is { schema_version: number; items: DiscordCollectibleItem[] } { if (!value || typeof value !== 'object') return false; const catalog = value as Record; return ( @@ -62,7 +64,7 @@ function isPublishedCatalog(value: unknown): value is { schema_version: number; item && typeof item === 'object' && typeof (item as DiscordCollectibleItem).id === 'string' && - Array.isArray((item as DiscordCollectibleItem).assets) + Array.isArray((item as DiscordCollectibleItem).assets), ) ); } @@ -94,7 +96,7 @@ function saveCachedCatalog(catalog: PublishedCatalog): void { } export async function fetchPublishedCollectiblesCatalog( - force = false + force = false, ): Promise { const cached = loadCachedCatalog(); if (!force && cached) return cached.items; @@ -107,7 +109,7 @@ export async function fetchPublishedCollectiblesCatalog( const catalog = await response.json(); if (!isPublishedCatalog(catalog)) throw new Error('Catalog has an unsupported schema.'); return catalog; - }) + }), ); const items = documents.flatMap((catalog) => catalog.items); if (items.length === 0) throw new Error('Catalog is empty.'); @@ -148,7 +150,7 @@ function replaceCdnUrls(value: T, urlToMxc: Map): T { } export async function downloadCollectibleAssets( - assets: DiscordCollectibleAsset[] + assets: DiscordCollectibleAsset[], ): Promise { const api = window.electron?.discordCollectibles; if (api) { @@ -169,19 +171,20 @@ export async function downloadCollectibleAssets( assets.map(async (asset) => { if (!isCdnUrl(asset.url)) throw new Error('Collectible asset URL is not a Discord CDN URL.'); const response = await fetch(asset.url); - if (!response.ok) throw new Error(`Failed to download ${asset.filename}: HTTP ${response.status}.`); + if (!response.ok) + throw new Error(`Failed to download ${asset.filename}: HTTP ${response.status}.`); return { ...asset, data: new Uint8Array(await response.arrayBuffer()), }; - }) + }), ); } export async function uploadCollectibleToMatrix( mx: MatrixClient, item: DiscordCollectibleItem, - onProgress?: (message: string) => void + onProgress?: (message: string) => void, ): Promise { onProgress?.('Downloading from Discord…'); const downloaded = await downloadCollectibleAssets(item.assets); @@ -287,7 +290,7 @@ export function groupCollectibleItems(items: DiscordCollectibleItem[]): Collecti return [...map.entries()] .map(([id, groupItems]) => { const items = dedupeVariantItems(groupItems).sort((a, b) => - variantItemLabel(a).localeCompare(variantItemLabel(b)) + variantItemLabel(a).localeCompare(variantItemLabel(b)), ); return { id, diff --git a/src/app/utils/disposable.ts b/src/app/utils/disposable.ts index 74424154..b07a8acf 100644 --- a/src/app/utils/disposable.ts +++ b/src/app/utils/disposable.ts @@ -4,13 +4,13 @@ export type DisposeCallback = (...args: DisposableArgs) => DisposeCallback; export const disposable = < DisposableArgs extends unknown[], DisposeArgs extends unknown[] = [], - DisposeReturn = void + DisposeReturn = void, >( - context: DisposableContext + context: DisposableContext, ) => context; diff --git a/src/app/utils/dom.ts b/src/app/utils/dom.ts index 0e9bc11a..20f2f59b 100644 --- a/src/app/utils/dom.ts +++ b/src/app/utils/dom.ts @@ -13,7 +13,7 @@ export const editableActiveElement = (): boolean => export const isIntersectingScrollView = ( scrollElement: HTMLElement, - childElement: HTMLElement + childElement: HTMLElement, ): boolean => { const scrollTop = scrollElement.offsetTop + scrollElement.scrollTop; const scrollBottom = scrollTop + scrollElement.offsetHeight; @@ -38,7 +38,7 @@ export const isInScrollView = (scrollElement: HTMLElement, childElement: HTMLEle export const canFitInScrollView = ( scrollElement: HTMLElement, - childElement: HTMLElement + childElement: HTMLElement, ): boolean => childElement.offsetHeight < scrollElement.offsetHeight; export type FilesOrFile = T extends true ? File[] : File; @@ -56,7 +56,7 @@ export const getFilesFromFileList = (fileList: FileList): File[] => { export const selectFile = ( accept: string, - multiple?: M + multiple?: M, ): Promise | undefined> => new Promise((resolve) => { const input = document.createElement('input'); @@ -147,7 +147,7 @@ export const getThumbnail = ( img: HTMLImageElement | SVGImageElement | HTMLVideoElement, width: number, height: number, - thumbnailMimeType?: string + thumbnailMimeType?: string, ): Promise => new Promise((resolve) => { const canvas = document.createElement('canvas'); @@ -193,7 +193,7 @@ export const scrollToPosition = (scrollEl: HTMLElement, position: ScrollPosition */ export const scrollElementIntoView = ( element: HTMLElement, - options?: ScrollIntoViewOptions + options?: ScrollIntoViewOptions, ): void => { element.scrollIntoView(options); }; @@ -230,11 +230,7 @@ export const isScrolledToBottom = (scrollEl: HTMLElement, threshold = 50): boole * Shared auto-scroll behavior for chat-like timelines that should stay pinned to bottom. * Only scrolls if already near the bottom unless a call site explicitly forces it. */ -export const autoScrollToBottom = ( - scrollEl: HTMLElement, - smooth = false, - force = false -): void => { +export const autoScrollToBottom = (scrollEl: HTMLElement, smooth = false, force = false): void => { if (force || isScrolledToBottom(scrollEl)) { scrollToBottom(scrollEl, smooth ? 'smooth' : 'instant'); } diff --git a/src/app/utils/emoticonConverter.ts b/src/app/utils/emoticonConverter.ts index c6f5a1e2..29ff4259 100644 --- a/src/app/utils/emoticonConverter.ts +++ b/src/app/utils/emoticonConverter.ts @@ -14,13 +14,13 @@ const EMOTICON_MAP: Record = { '=)': '😊', ':]': '😊', ':>': '😊', - + // Sad faces ':(': '☹️', ':-(': '☹️', '=[': '☹️', ':<': '☹️', - + // Other emotions ';)': '😉', ';-)': '😉', @@ -28,8 +28,8 @@ const EMOTICON_MAP: Record = { ':-P': '😛', ':p': '😛', ':-p': '😛', - 'xD': '😆', - 'XD': '😆', + xD: '😆', + XD: '😆', ':|': '😐', ':-|': '😐', ':O': '😮', @@ -42,21 +42,21 @@ const EMOTICON_MAP: Record = { ':-*': '😘', '<3': '❤️', ' = { */ export function convertEmoticons(text: string): string { let result = text; - + // Sort emoticons by length (longest first) to handle overlapping patterns // e.g., :-) before :) const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length); - + for (const emoticon of emoticons) { // Escape special regex characters const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&'); - + // Match emoticons with optional backslash escape // Matches either \:) (escaped) or :) (not escaped, and not preceded by backslash) - const regex = new RegExp( - `(^|\\s)(\\\\)?(${escapedEmoticon})(?=\\s|$)`, - 'g' - ); - + const regex = new RegExp(`(^|\\s)(\\\\)?(${escapedEmoticon})(?=\\s|$)`, 'g'); + result = result.replace(regex, (match, prefix, backslash, emote) => { // If backslash is present, remove it but keep the emoticon literal if (backslash) { @@ -97,7 +94,7 @@ export function convertEmoticons(text: string): string { return prefix + EMOTICON_MAP[emoticon]; }); } - + return result; } @@ -110,26 +107,21 @@ export function convertEmoticons(text: string): string { */ export function convertEmoticonsInHtml(html: string): string { let result = html; - + // Sort emoticons by length (longest first) to handle overlapping patterns const emoticons = Object.keys(EMOTICON_MAP).sort((a, b) => b.length - a.length); - + for (const emoticon of emoticons) { // Convert emoticon to HTML entity version (for < and >) - const htmlEmoticon = emoticon - .replace(//g, '>'); - + const htmlEmoticon = emoticon.replace(//g, '>'); + // Escape special regex characters const escapedEmoticon = htmlEmoticon.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - + // Match emoticons at start of string, after whitespace, or after HTML tags // With optional backslash escape - const regex = new RegExp( - `(^|\\s|>)(\\\\)?(${escapedEmoticon})(?=\\s|<|$)`, - 'g' - ); - + const regex = new RegExp(`(^|\\s|>)(\\\\)?(${escapedEmoticon})(?=\\s|<|$)`, 'g'); + result = result.replace(regex, (match, prefix, backslash, emote) => { // If backslash is present, remove it but keep the emoticon literal if (backslash) { @@ -139,7 +131,7 @@ export function convertEmoticonsInHtml(html: string): string { return prefix + EMOTICON_MAP[emoticon]; }); } - + return result; } @@ -150,15 +142,15 @@ export function convertEmoticonsInHtml(html: string): string { */ export function containsEmoticons(text: string): boolean { const emoticons = Object.keys(EMOTICON_MAP); - + for (const emoticon of emoticons) { const escapedEmoticon = emoticon.replace(/[.*+?^${}()|[\]\\<>]/g, '\\$&'); const regex = new RegExp(`(^|\\s)(${escapedEmoticon})(?=\\s|$)`); - + if (regex.test(text)) { return true; } } - + return false; } diff --git a/src/app/utils/findAndReplace.ts b/src/app/utils/findAndReplace.ts index c76efa66..d83765eb 100644 --- a/src/app/utils/findAndReplace.ts +++ b/src/app/utils/findAndReplace.ts @@ -1,6 +1,6 @@ export type ReplaceCallback = ( match: RegExpExecArray | RegExpMatchArray, - pushIndex: number + pushIndex: number, ) => R; export type ConvertPartCallback = (text: string, pushIndex: number) => R; @@ -8,7 +8,7 @@ export const findAndReplace = ( text: string, regex: RegExp, replace: ReplaceCallback, - convertPart: ConvertPartCallback + convertPart: ConvertPartCallback, ): Array => { const result: Array = []; let lastEnd = 0; diff --git a/src/app/utils/fuzzy.ts b/src/app/utils/fuzzy.ts index 1dc3ee34..4a651329 100644 --- a/src/app/utils/fuzzy.ts +++ b/src/app/utils/fuzzy.ts @@ -80,7 +80,10 @@ export function fuzzyMatch(query: string, text: string): FuzzyMatch | null { } /** Best fuzzy match across multiple strings (title, keywords, etc.). */ -export function fuzzyMatchAny(query: string, texts: Array): FuzzyMatch | null { +export function fuzzyMatchAny( + query: string, + texts: Array, +): FuzzyMatch | null { let best: FuzzyMatch | null = null; for (const text of texts) { if (!text) continue; @@ -95,7 +98,7 @@ export function fuzzyMatchAny(query: string, texts: Array( items: T[], query: string, - getTexts: (item: T) => Array + getTexts: (item: T) => Array, ): Array<{ item: T; score: number }> { const q = query.trim(); if (!q) { diff --git a/src/app/utils/gifMetadata.ts b/src/app/utils/gifMetadata.ts index 814a7286..b5aaf3cb 100644 --- a/src/app/utils/gifMetadata.ts +++ b/src/app/utils/gifMetadata.ts @@ -1,14 +1,14 @@ /** * Utilities for reading and writing GIF metadata (Application Extension blocks) * Used to embed user color in avatar images - * + * * GIF structure: * - Header: GIF87a or GIF89a (6 bytes) * - Logical Screen Descriptor (7 bytes) * - Optional Global Color Table * - Extension blocks and image data * - Trailer: 0x3B - * + * * Application Extension format: * - 0x21 (Extension Introducer) * - 0xFF (Application Extension Label) @@ -20,7 +20,7 @@ /* eslint-disable no-bitwise */ /* eslint-disable no-plusplus */ -/* eslint-disable no-console */ + /* eslint-disable no-restricted-syntax */ /* eslint-disable no-continue */ @@ -33,14 +33,14 @@ const PAARROT_APP_ID = 'PAARROT\0'; // 8 bytes, null-padded const PAARROT_APP_ID_BYTES = new TextEncoder().encode(PAARROT_APP_ID); /** Application authentication code (3 bytes) */ -const PAARROT_AUTH_CODE = new Uint8Array([0x31, 0x2E, 0x30]); // "1.0" +const PAARROT_AUTH_CODE = new Uint8Array([0x31, 0x2e, 0x30]); // "1.0" /** * Check if data is a valid GIF file */ function isGIF(data: Uint8Array): boolean { if (data.length < 6) return false; - + // Check GIF87a let is87a = true; for (let i = 0; i < 6; i++) { @@ -50,7 +50,7 @@ function isGIF(data: Uint8Array): boolean { } } if (is87a) return true; - + // Check GIF89a let is89a = true; for (let i = 0; i < 6; i++) { @@ -71,15 +71,18 @@ function getGlobalColorTableSize(data: Uint8Array): number { const packedByte = data[10]; const hasGCT = (packedByte & 0x80) !== 0; if (!hasGCT) return 0; - + const gctSize = packedByte & 0x07; - return 3 * (2 ** (gctSize + 1)); + return 3 * 2 ** (gctSize + 1); } /** * Find all Application Extension blocks */ -function findAppExtensions(data: Uint8Array, startOffset: number): Array<{ +function findAppExtensions( + data: Uint8Array, + startOffset: number, +): Array<{ offset: number; length: number; appId: string; @@ -93,37 +96,37 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{ authCode: Uint8Array; dataBlocks: Uint8Array[]; }> = []; - + let offset = startOffset; - + while (offset < data.length - 1) { // Look for Extension Introducer (0x21) - if (data[offset] === 0x21 && data[offset + 1] === 0xFF) { + if (data[offset] === 0x21 && data[offset + 1] === 0xff) { // Application Extension const blockSize = data[offset + 2]; - if (blockSize !== 0x0B) { + if (blockSize !== 0x0b) { offset++; continue; } - + const appId = new TextDecoder().decode(data.slice(offset + 3, offset + 11)); const authCode = data.slice(offset + 11, offset + 14); - + // Read data sub-blocks let subOffset = offset + 14; const dataBlocks: Uint8Array[] = []; let totalLength = 14; // header length - + while (subOffset < data.length && data[subOffset] !== 0x00) { const subBlockSize = data[subOffset]; dataBlocks.push(data.slice(subOffset + 1, subOffset + 1 + subBlockSize)); subOffset += 1 + subBlockSize; totalLength += 1 + subBlockSize; } - + // Add terminator totalLength += 1; - + extensions.push({ offset, length: totalLength, @@ -131,16 +134,16 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{ authCode, dataBlocks, }); - + offset = subOffset + 1; - } else if (data[offset] === 0x3B) { + } else if (data[offset] === 0x3b) { // Trailer - end of GIF break; } else { offset++; } } - + return extensions; } @@ -149,33 +152,33 @@ function findAppExtensions(data: Uint8Array, startOffset: number): Array<{ */ function createPaarrotExtension(color: string): Uint8Array { const colorBytes = new TextEncoder().encode(color); - + // Calculate total size // 0x21 + 0xFF + 0x0B + appId(8) + authCode(3) + sub-block(1 + colorBytes.length) + 0x00 const totalSize = 2 + 1 + 8 + 3 + 1 + colorBytes.length + 1; const extension = new Uint8Array(totalSize); - + let offset = 0; extension[offset++] = 0x21; // Extension Introducer - extension[offset++] = 0xFF; // Application Extension Label - extension[offset++] = 0x0B; // Block size (always 11) - + extension[offset++] = 0xff; // Application Extension Label + extension[offset++] = 0x0b; // Block size (always 11) + // Application Identifier (8 bytes) extension.set(PAARROT_APP_ID_BYTES, offset); offset += 8; - + // Application Authentication Code (3 bytes) extension.set(PAARROT_AUTH_CODE, offset); offset += 3; - + // Data sub-block extension[offset++] = colorBytes.length; extension.set(colorBytes, offset); offset += colorBytes.length; - + // Block terminator extension[offset] = 0x00; - + return extension; } @@ -184,16 +187,16 @@ function createPaarrotExtension(color: string): Uint8Array { */ export function extractColorFromGIF(imageData: ArrayBuffer | Uint8Array): string | undefined { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isGIF(data)) { return undefined; } - + const gctSize = getGlobalColorTableSize(data); const startOffset = 13 + gctSize; // Header(6) + LSD(7) + GCT - + const extensions = findAppExtensions(data, startOffset); - + for (const ext of extensions) { if (ext.appId.startsWith('PAARROT')) { if (ext.dataBlocks.length > 0) { @@ -202,25 +205,28 @@ export function extractColorFromGIF(imageData: ArrayBuffer | Uint8Array): string } } } - + return undefined; } /** * Embed paarrot color into GIF image data */ -export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null { +export function embedColorInGIF( + imageData: ArrayBuffer | Uint8Array, + color: string, +): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isGIF(data)) { return null; } - + const gctSize = getGlobalColorTableSize(data); const insertOffset = 13 + gctSize; // After Header + LSD + GCT - + const extensions = findAppExtensions(data, insertOffset); - + // Find existing PAARROT extension let existingExt: { offset: number; length: number } | null = null; for (const ext of extensions) { @@ -229,12 +235,12 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri break; } } - + // Create new extension const newExtension = createPaarrotExtension(color); - + let newData: Uint8Array; - + if (existingExt) { // Replace existing extension newData = new Uint8Array(data.length - existingExt.length + newExtension.length); @@ -242,7 +248,7 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri newData.set(newExtension, existingExt.offset); newData.set( data.slice(existingExt.offset + existingExt.length), - existingExt.offset + newExtension.length + existingExt.offset + newExtension.length, ); } else { // Insert after GCT (before any other blocks) @@ -251,7 +257,7 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri newData.set(newExtension, insertOffset); newData.set(data.slice(insertOffset), insertOffset + newExtension.length); } - + return newData; } @@ -260,16 +266,16 @@ export function embedColorInGIF(imageData: ArrayBuffer | Uint8Array, color: stri */ export function removeColorFromGIF(imageData: ArrayBuffer | Uint8Array): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isGIF(data)) { return null; } - + const gctSize = getGlobalColorTableSize(data); const startOffset = 13 + gctSize; - + const extensions = findAppExtensions(data, startOffset); - + // Find existing PAARROT extension let existingExt: { offset: number; length: number } | null = null; for (const ext of extensions) { @@ -278,18 +284,15 @@ export function removeColorFromGIF(imageData: ArrayBuffer | Uint8Array): Uint8Ar break; } } - + if (!existingExt) { return data; } - + // Remove the extension const newData = new Uint8Array(data.length - existingExt.length); newData.set(data.slice(0, existingExt.offset), 0); - newData.set( - data.slice(existingExt.offset + existingExt.length), - existingExt.offset - ); - + newData.set(data.slice(existingExt.offset + existingExt.length), existingExt.offset); + return newData; } diff --git a/src/app/utils/imageMetadata.ts b/src/app/utils/imageMetadata.ts index 01cf7eb9..54b99bfb 100644 --- a/src/app/utils/imageMetadata.ts +++ b/src/app/utils/imageMetadata.ts @@ -43,8 +43,7 @@ class LRUCache { set(key: K, value: V): void { if (this.cache.has(key)) { this.cache.delete(key); - } - else if (this.cache.size >= this.maxSize) { + } else if (this.cache.size >= this.maxSize) { const firstKey = this.cache.keys().next().value; if (firstKey !== undefined) { this.cache.delete(firstKey); @@ -90,7 +89,7 @@ const RIFF_SIGNATURE = [0x52, 0x49, 0x46, 0x46]; // "RIFF" const WEBP_OFFSET_SIGNATURE = [0x57, 0x45, 0x42, 0x50]; // "WEBP" at offset 8 /** JPEG signature */ -const JPEG_SIGNATURE = [0xFF, 0xD8]; +const JPEG_SIGNATURE = [0xff, 0xd8]; /** GIF signatures */ const GIF87A_SIGNATURE = [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]; // "GIF87a" @@ -103,9 +102,9 @@ export type ImageFormat = 'png' | 'webp' | 'jpeg' | 'gif' | 'unknown'; */ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { const bytes = data instanceof Uint8Array ? data : new Uint8Array(data); - + if (bytes.length < 12) return 'unknown'; - + // Check PNG signature let isPNG = true; for (let i = 0; i < 8; i++) { @@ -115,7 +114,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { } } if (isPNG) return 'png'; - + // Check WebP signature (RIFF + WEBP) let isRIFF = true; for (let i = 0; i < 4; i++) { @@ -134,12 +133,12 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { } if (isWebP) return 'webp'; } - + // Check JPEG signature (FFD8) if (bytes[0] === JPEG_SIGNATURE[0] && bytes[1] === JPEG_SIGNATURE[1]) { return 'jpeg'; } - + // Check GIF signatures let isGIF87a = true; for (let i = 0; i < 6; i++) { @@ -149,7 +148,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { } } if (isGIF87a) return 'gif'; - + let isGIF89a = true; for (let i = 0; i < 6; i++) { if (bytes[i] !== GIF89A_SIGNATURE[i]) { @@ -158,7 +157,7 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { } } if (isGIF89a) return 'gif'; - + return 'unknown'; } @@ -169,9 +168,9 @@ export function detectImageFormat(data: ArrayBuffer | Uint8Array): ImageFormat { */ export function extractColorFromImage(imageData: ArrayBuffer | Uint8Array): string | undefined { const format = detectImageFormat(imageData); - + console.log('[extractColorFromImage] Detected format:', format); - + switch (format) { case 'png': return extractColorFromPNG(imageData); @@ -194,7 +193,7 @@ export function extractColorFromImage(imageData: ArrayBuffer | Uint8Array): stri */ export function extractBannerFromImage(imageData: ArrayBuffer | Uint8Array): string | undefined { const format = detectImageFormat(imageData); - + switch (format) { case 'png': return extractBannerFromPNG(imageData); @@ -212,9 +211,9 @@ export function extractBannerFromImage(imageData: ArrayBuffer | Uint8Array): str */ export function extractMetadataFromImage(imageData: ArrayBuffer | Uint8Array): ImageMetadata { const format = detectImageFormat(imageData); - + console.log('[extractMetadataFromImage] Detected format:', format); - + switch (format) { case 'png': const pngMetadata = extractMetadataFromPNG(imageData); @@ -240,9 +239,12 @@ export function extractMetadataFromImage(imageData: ArrayBuffer | Uint8Array): I * @param color - The color string to embed (e.g., '#ff5500') * @returns New image data with embedded color, or null if not a supported format */ -export function embedColorInImage(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null { +export function embedColorInImage( + imageData: ArrayBuffer | Uint8Array, + color: string, +): Uint8Array | null { const format = detectImageFormat(imageData); - + switch (format) { case 'png': return embedColorInPNG(imageData, color); @@ -269,7 +271,7 @@ export function needsPngForMetadata(metadata: ImageMetadata): boolean { * Convert image data to PNG via canvas (needed for banner/border/gradient metadata). */ export async function convertImageDataToPng( - imageData: ArrayBuffer | Uint8Array + imageData: ArrayBuffer | Uint8Array, ): Promise { const bytes = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); const format = detectImageFormat(bytes); @@ -320,7 +322,7 @@ export function uint8ArrayToBlob(data: Uint8Array, type: string): Blob { */ export function embedMetadataInImage( imageData: ArrayBuffer | Uint8Array, - metadata: ImageMetadata + metadata: ImageMetadata, ): Uint8Array | null { const format = detectImageFormat(imageData); const bytes = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); @@ -335,7 +337,7 @@ export function embedMetadataInImage( if (needsPngForMetadata(metadata)) { console.warn( '[embedMetadataInImage] Banner/border/gradient require PNG; convert with convertImageDataToPng first. Got:', - format + format, ); return null; } @@ -357,7 +359,7 @@ export function embedMetadataInImage( */ export function removeColorFromImage(imageData: ArrayBuffer | Uint8Array): Uint8Array | null { const format = detectImageFormat(imageData); - + switch (format) { case 'png': return removeColorFromPNG(imageData); @@ -410,7 +412,9 @@ export function getExtension(format: ImageFormat): string { } // LRU cache for avatar metadata to avoid refetching -const avatarMetadataCache = new LRUCache(100); +const avatarMetadataCache = new LRUCache( + 100, +); const METADATA_CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes // In-flight fetch tracking to prevent duplicate parallel requests @@ -423,7 +427,10 @@ const inflightMetadataFetches = new Map>(); * @param accessToken - Optional access token for authenticated media * @returns The color string if found, or undefined */ -export async function fetchAndExtractColor(url: string, accessToken?: string | null): Promise { +export async function fetchAndExtractColor( + url: string, + accessToken?: string | null, +): Promise { // Check if full metadata is cached const cached = avatarMetadataCache.get(url); if (cached && Date.now() - cached.timestamp < METADATA_CACHE_TTL_MS) { @@ -440,27 +447,27 @@ export async function fetchAndExtractColor(url: string, accessToken?: string | n } console.log('[fetchAndExtractColor] Fetching and extracting color from', url); - + const fetchPromise = (async () => { try { const response = await fetch(url, { method: 'GET', headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined, }); - + console.log('[fetchAndExtractColor] Fetch response status:', response.ok, response.status); - + if (!response.ok) return undefined; - + const data = await response.arrayBuffer(); console.log('[fetchAndExtractColor] Downloaded', data.byteLength, 'bytes'); - + const color = extractColorFromImage(data); console.log('[fetchAndExtractColor] Extracted color:', color); - + // Don't cache here - fetchAndExtractMetadata will cache full metadata // This avoids cache collision where color-only fetch overwrites full metadata - + return color; } catch (error) { console.error('[fetchAndExtractColor] Error fetching/extracting color:', error); @@ -480,7 +487,10 @@ export async function fetchAndExtractColor(url: string, accessToken?: string | n * @param accessToken - Optional access token for authenticated media * @returns Object with color and banner if found */ -export async function fetchAndExtractMetadata(url: string, accessToken?: string | null): Promise { +export async function fetchAndExtractMetadata( + url: string, + accessToken?: string | null, +): Promise { // Check cache first const cached = avatarMetadataCache.get(url); if (cached && Date.now() - cached.timestamp < METADATA_CACHE_TTL_MS) { @@ -504,23 +514,23 @@ export async function fetchAndExtractMetadata(url: string, accessToken?: string method: 'GET', headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined, }); - + console.log('[fetchAndExtractMetadata] Fetch response status:', response.ok, response.status); - + if (!response.ok) return {}; - + const data = await response.arrayBuffer(); console.log('[fetchAndExtractMetadata] Downloaded', data.byteLength, 'bytes'); - + const metadata = extractMetadataFromImage(data); console.log('[fetchAndExtractMetadata] Extracted metadata:', metadata); - + // Cache the result - avatarMetadataCache.set(url, { - metadata, - timestamp: Date.now() + avatarMetadataCache.set(url, { + metadata, + timestamp: Date.now(), }); - + return metadata; } catch { return {}; diff --git a/src/app/utils/jpegMetadata.ts b/src/app/utils/jpegMetadata.ts index 757ba32d..e0d4561c 100644 --- a/src/app/utils/jpegMetadata.ts +++ b/src/app/utils/jpegMetadata.ts @@ -1,7 +1,7 @@ /** * Utilities for reading and writing JPEG metadata (XMP/APP1 segments) * Used to embed user color in avatar images - * + * * JPEG structure: * - Starts with FFD8 (SOI marker) * - Contains segments: FF + marker type + length (2 bytes BE) + data @@ -11,12 +11,12 @@ /* eslint-disable no-bitwise */ /* eslint-disable no-plusplus */ -/* eslint-disable no-console */ + /* eslint-disable no-restricted-syntax */ /* eslint-disable no-continue */ /** JPEG signature bytes */ -const JPEG_SOI = new Uint8Array([0xFF, 0xD8]); // Start of Image +const JPEG_SOI = new Uint8Array([0xff, 0xd8]); // Start of Image /** XMP namespace identifier in APP1 segment */ const XMP_NAMESPACE = 'http://ns.adobe.com/xap/1.0/\0'; @@ -31,7 +31,7 @@ const PAARROT_XMP_END = ''; */ function isJPEG(data: Uint8Array): boolean { if (data.length < 2) return false; - return data[0] === 0xFF && data[1] === 0xD8; + return data[0] === 0xff && data[1] === 0xd8; } /** @@ -77,50 +77,52 @@ function extractColorFromXMP(xmpData: string): string | undefined { /** * Parse JPEG segments */ -function parseSegments(data: Uint8Array): Array<{ marker: number; data: Uint8Array; offset: number; length: number }> { +function parseSegments( + data: Uint8Array, +): Array<{ marker: number; data: Uint8Array; offset: number; length: number }> { const segments: Array<{ marker: number; data: Uint8Array; offset: number; length: number }> = []; let offset = 2; // Skip SOI marker - + while (offset < data.length - 1) { // Find next marker (0xFF followed by non-zero, non-0xFF byte) - if (data[offset] !== 0xFF) { + if (data[offset] !== 0xff) { offset++; continue; } - + const marker = data[offset + 1]; - + // Skip padding bytes (0xFF) - if (marker === 0xFF || marker === 0x00) { + if (marker === 0xff || marker === 0x00) { offset++; continue; } - + // EOI (End of Image) or SOS (Start of Scan) - stop parsing - if (marker === 0xD9 || marker === 0xDA) { + if (marker === 0xd9 || marker === 0xda) { break; } - + // Markers without length field (RST0-RST7, SOI, EOI) - if ((marker >= 0xD0 && marker <= 0xD7) || marker === 0xD8 || marker === 0xD9) { + if ((marker >= 0xd0 && marker <= 0xd7) || marker === 0xd8 || marker === 0xd9) { offset += 2; continue; } - + // Read segment length (includes the 2 length bytes) const segmentLength = readUint16BE(data, offset + 2); const segmentData = data.slice(offset + 4, offset + 2 + segmentLength); - + segments.push({ marker, data: segmentData, offset, length: 2 + segmentLength, // marker (2) + length field + data }); - + offset += 2 + segmentLength; } - + return segments; } @@ -130,11 +132,11 @@ function parseSegments(data: Uint8Array): Array<{ marker: number; data: Uint8Arr function isPaarrotXMP(segmentData: Uint8Array): boolean { // Check for XMP namespace if (segmentData.length < XMP_NAMESPACE_BYTES.length) return false; - + for (let i = 0; i < XMP_NAMESPACE_BYTES.length; i++) { if (segmentData[i] !== XMP_NAMESPACE_BYTES[i]) return false; } - + const xmpString = new TextDecoder().decode(segmentData.slice(XMP_NAMESPACE_BYTES.length)); return xmpString.includes('paarrot:color') || xmpString.includes('paarrot.app'); } @@ -144,16 +146,16 @@ function isPaarrotXMP(segmentData: Uint8Array): boolean { */ export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): string | undefined { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isJPEG(data)) { return undefined; } - + const segments = parseSegments(data); - + for (const segment of segments) { // APP1 marker (0xE1) is used for XMP - if (segment.marker === 0xE1) { + if (segment.marker === 0xe1) { // Check for XMP namespace if (segment.data.length >= XMP_NAMESPACE_BYTES.length) { let isXMP = true; @@ -163,9 +165,11 @@ export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): strin break; } } - + if (isXMP) { - const xmpString = new TextDecoder().decode(segment.data.slice(XMP_NAMESPACE_BYTES.length)); + const xmpString = new TextDecoder().decode( + segment.data.slice(XMP_NAMESPACE_BYTES.length), + ); const color = extractColorFromXMP(xmpString); if (color) { return color; @@ -174,49 +178,52 @@ export function extractColorFromJPEG(imageData: ArrayBuffer | Uint8Array): strin } } } - + return undefined; } /** * Embed paarrot color into JPEG image data */ -export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null { +export function embedColorInJPEG( + imageData: ArrayBuffer | Uint8Array, + color: string, +): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isJPEG(data)) { return null; } - + const segments = parseSegments(data); - + // Find existing paarrot XMP segment let existingSegment: { offset: number; length: number } | null = null; - + for (const segment of segments) { - if (segment.marker === 0xE1 && isPaarrotXMP(segment.data)) { + if (segment.marker === 0xe1 && isPaarrotXMP(segment.data)) { existingSegment = { offset: segment.offset, length: segment.length }; break; } } - + // Create XMP APP1 segment const xmpData = createXMPData(color); const xmpBytes = new TextEncoder().encode(xmpData); const segmentData = new Uint8Array(XMP_NAMESPACE_BYTES.length + xmpBytes.length); segmentData.set(XMP_NAMESPACE_BYTES, 0); segmentData.set(xmpBytes, XMP_NAMESPACE_BYTES.length); - + // APP1 segment: FF E1 + length (2 bytes) + data const segmentLength = 2 + segmentData.length; // length field + data const app1Segment = new Uint8Array(4 + segmentData.length); - app1Segment[0] = 0xFF; - app1Segment[1] = 0xE1; + app1Segment[0] = 0xff; + app1Segment[1] = 0xe1; app1Segment.set(writeUint16BE(segmentLength), 2); app1Segment.set(segmentData, 4); - + let newData: Uint8Array; - + if (existingSegment) { // Replace existing segment newData = new Uint8Array(data.length - existingSegment.length + app1Segment.length); @@ -224,7 +231,7 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str newData.set(app1Segment, existingSegment.offset); newData.set( data.slice(existingSegment.offset + existingSegment.length), - existingSegment.offset + app1Segment.length + existingSegment.offset + app1Segment.length, ); } else { // Insert after SOI marker (at offset 2) @@ -233,7 +240,7 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str newData.set(app1Segment, 2); newData.set(data.slice(2), 2 + app1Segment.length); } - + return newData; } @@ -242,34 +249,31 @@ export function embedColorInJPEG(imageData: ArrayBuffer | Uint8Array, color: str */ export function removeColorFromJPEG(imageData: ArrayBuffer | Uint8Array): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isJPEG(data)) { return null; } - + const segments = parseSegments(data); - + // Find existing paarrot XMP segment let existingSegment: { offset: number; length: number } | null = null; - + for (const segment of segments) { - if (segment.marker === 0xE1 && isPaarrotXMP(segment.data)) { + if (segment.marker === 0xe1 && isPaarrotXMP(segment.data)) { existingSegment = { offset: segment.offset, length: segment.length }; break; } } - + if (!existingSegment) { return data; } - + // Remove the segment const newData = new Uint8Array(data.length - existingSegment.length); newData.set(data.slice(0, existingSegment.offset), 0); - newData.set( - data.slice(existingSegment.offset + existingSegment.length), - existingSegment.offset - ); - + newData.set(data.slice(existingSegment.offset + existingSegment.length), existingSegment.offset); + return newData; } diff --git a/src/app/utils/matrix-crypto.ts b/src/app/utils/matrix-crypto.ts index dda402f8..e245b826 100644 --- a/src/app/utils/matrix-crypto.ts +++ b/src/app/utils/matrix-crypto.ts @@ -3,7 +3,7 @@ import { CryptoApi } from 'matrix-js-sdk/lib/crypto-api'; export const verifiedDevice = async ( api: CryptoApi, userId: string, - deviceId: string + deviceId: string, ): Promise => { const status = await api.getDeviceVerificationStatus(userId, deviceId); diff --git a/src/app/utils/matrix-uia.ts b/src/app/utils/matrix-uia.ts index 15c5799c..b46cea6d 100644 --- a/src/app/utils/matrix-uia.ts +++ b/src/app/utils/matrix-uia.ts @@ -2,7 +2,7 @@ import { AuthType, IAuthData, UIAFlow } from 'matrix-js-sdk'; export const getSupportedUIAFlows = (uiaFlows: UIAFlow[], supportedStages: string[]): UIAFlow[] => { const supportedUIAFlows = uiaFlows.filter((flow) => - flow.stages.every((stage) => supportedStages.includes(stage)) + flow.stages.every((stage) => supportedStages.includes(stage)), ); return supportedUIAFlows; diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index 3de69114..248b9235 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -43,7 +43,7 @@ export const getCanonicalAliasRoomId = (mx: MatrixClient, alias: string): string ?.find( (room) => room.getCanonicalAlias() === alias && - getStateEvent(room, StateEvent.RoomTombstone) === undefined + getStateEvent(room, StateEvent.RoomTombstone) === undefined, )?.roomId; export const getCanonicalAliasOrRoomId = (mx: MatrixClient, roomId: string): string => { @@ -105,7 +105,7 @@ export const getThumbnailContent = (thumbnailInfo: { }; export const encryptFile = async ( - file: File | Blob + file: File | Blob, ): Promise<{ encInfo: EncryptedAttachmentInfo; file: File; @@ -126,7 +126,7 @@ export const encryptFile = async ( export const decryptFile = async ( dataBuffer: ArrayBuffer, type: string, - encInfo: EncryptedAttachmentInfo + encInfo: EncryptedAttachmentInfo, ): Promise => { const dataArray = await decryptAttachment(dataBuffer, encInfo); const blob = new Blob([dataArray], { type }); @@ -148,7 +148,7 @@ export type ContentUploadOptions = { export const uploadContent = async ( mx: MatrixClient, file: TUploadContent, - options: ContentUploadOptions + options: ContentUploadOptions, ) => { const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options; @@ -186,7 +186,7 @@ export const getDMRoomFor = (mx: MatrixClient, userId: string): Room | undefined (room) => room.getMyMembership() === Membership.Join && room.hasEncryptionStateEvent() && - room.getMembers().length <= 2 + room.getMembers().length <= 2, ); return dmLikeRooms.find((room) => room.getMember(userId)); @@ -220,7 +220,7 @@ export const guessDmRoomUserId = (room: Room, myUserId: string): string => { // if there are no joined members other than us, use the oldest member const member1 = getOldestMember( - room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getMembers() ?? [] + room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getMembers() ?? [], ); return member1?.userId ?? myUserId; }; @@ -228,7 +228,7 @@ export const guessDmRoomUserId = (room: Room, myUserId: string): string => { export const addRoomIdToMDirect = async ( mx: MatrixClient, roomId: string, - userId: string + userId: string, ): Promise => { const mDirectsEvent = mx.getAccountData(AccountDataEvent.Direct as any); let userIdToRoomIds: Record = {}; @@ -284,7 +284,7 @@ export const mxcUrlToHttp = ( height?: number, resizeMethod?: string, allowDirectLinks?: boolean, - allowRedirects?: boolean + allowRedirects?: boolean, ): string | null => mx.mxcUrlToHttp( mxcUrl, @@ -293,7 +293,7 @@ export const mxcUrlToHttp = ( resizeMethod, allowDirectLinks, allowRedirects, - useAuthentication + useAuthentication, ); /** @@ -302,40 +302,42 @@ export const mxcUrlToHttp = ( export const isAuthenticatedMediaUrl = (url: string): boolean => url.includes('/_matrix/client/v1/media/download') || url.includes('/_matrix/client/v1/media/thumbnail') || - url.includes('/_matrix/media/') && - (url.includes('/download/') || url.includes('/thumbnail/')); + (url.includes('/_matrix/media/') && (url.includes('/download/') || url.includes('/thumbnail/'))); /** * Downloads media with optional authentication. * For authenticated media URLs, the access token is required. * Falls back to unauthenticated request if authenticated request fails with 401. * Returns an empty blob with error type if all attempts fail, to prevent cascading failures. - * + * * @param src - The media URL to download * @param accessToken - Optional access token (if not provided, will use current session's token) */ export const downloadMedia = async (src: string, accessToken?: string | null): Promise => { // Import here to avoid circular dependencies const { getCurrentAccessToken } = await import('./auth'); - + // Use provided token, or fall back to current session's token const token = accessToken ?? getCurrentAccessToken(); const needsAuth = isAuthenticatedMediaUrl(src); const headers: HeadersInit = {}; - + if (needsAuth && token) { headers.Authorization = `Bearer ${token}`; } - + try { let res = await fetch(src, { method: 'GET', headers }); - + // If we got a 401 and we tried with auth, fallback to unauthenticated request if (!res.ok && res.status === 401 && needsAuth && token) { - console.warn('[downloadMedia] Auth failed (401), attempting unauthenticated fallback for:', src); + console.warn( + '[downloadMedia] Auth failed (401), attempting unauthenticated fallback for:', + src, + ); res = await fetch(src, { method: 'GET' }); } - + if (!res.ok) { console.warn(`[downloadMedia] Failed to download media (${res.status}) from:`, src); throw new Error(`Failed to download media: ${res.status}`); @@ -352,7 +354,7 @@ export const downloadMedia = async (src: string, accessToken?: string | null): P export const downloadEncryptedMedia = async ( src: string, decryptContent: (buf: ArrayBuffer) => Promise, - accessToken?: string | null + accessToken?: string | null, ): Promise => { const encryptedContent = await downloadMedia(src, accessToken); const decryptedContent = await decryptContent(await encryptedContent.arrayBuffer()); @@ -363,7 +365,7 @@ export const downloadEncryptedMedia = async ( export const rateLimitedActions = async ( data: T[], callback: (item: T, index: number) => Promise, - maxRetryCount?: number + maxRetryCount?: number, ) => { let retryCount = 0; diff --git a/src/app/utils/notifications.ts b/src/app/utils/notifications.ts index a23bd1a4..87cf270a 100644 --- a/src/app/utils/notifications.ts +++ b/src/app/utils/notifications.ts @@ -21,6 +21,6 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip await mx.sendReadReceipt( latestEvent, - privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read + privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read, ); } diff --git a/src/app/utils/pngMetadata.ts b/src/app/utils/pngMetadata.ts index 32a9f4ed..7f7bb03f 100644 --- a/src/app/utils/pngMetadata.ts +++ b/src/app/utils/pngMetadata.ts @@ -9,6 +9,8 @@ /* eslint-disable no-console */ /** PNG signature bytes */ +import type { ImageMetadata, ProfileGradient } from './imageMetadata'; + const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); /** Key used to store user color in PNG metadata */ @@ -26,12 +28,12 @@ export const PAARROT_GRADIENT_KEY = 'paarrot:gradient'; let crc32Table: Uint32Array | null = null; function getCRC32Table(): Uint32Array { if (crc32Table) return crc32Table; - + crc32Table = new Uint32Array(256); for (let i = 0; i < 256; i++) { let c = i; for (let j = 0; j < 8; j++) { - c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; } crc32Table[i] = c; } @@ -44,11 +46,11 @@ function getCRC32Table(): Uint32Array { function crc32(data: Uint8Array): number { let crc = 0xffffffff; const table = getCRC32Table(); - + for (let i = 0; i < data.length; i++) { crc = (crc >>> 8) ^ table[(crc ^ data[i]) & 0xff]; } - + return (crc ^ 0xffffffff) >>> 0; } @@ -56,7 +58,9 @@ function crc32(data: Uint8Array): number { * Read a 32-bit big-endian integer from a buffer */ function readUint32BE(data: Uint8Array, offset: number): number { - return (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; + return ( + (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3] + ); } /** @@ -77,55 +81,57 @@ function writeUint32BE(value: number): Uint8Array { function createTextChunk(key: string, value: string): Uint8Array { const keyBytes = new TextEncoder().encode(key); const valueBytes = new TextEncoder().encode(value); - + // tEXt chunk data: key + null byte + value const chunkData = new Uint8Array(keyBytes.length + 1 + valueBytes.length); chunkData.set(keyBytes, 0); chunkData[keyBytes.length] = 0; // null separator chunkData.set(valueBytes, keyBytes.length + 1); - + const chunkType = new TextEncoder().encode('tEXt'); - + // Calculate CRC over type + data const crcData = new Uint8Array(4 + chunkData.length); crcData.set(chunkType, 0); crcData.set(chunkData, 4); const crc = crc32(crcData); - + // Full chunk: length (4) + type (4) + data + crc (4) const chunk = new Uint8Array(4 + 4 + chunkData.length + 4); chunk.set(writeUint32BE(chunkData.length), 0); chunk.set(chunkType, 4); chunk.set(chunkData, 8); chunk.set(writeUint32BE(crc), 8 + chunkData.length); - + return chunk; } /** * Parse PNG chunks from image data */ -function parseChunks(data: Uint8Array): Array<{ type: string; data: Uint8Array; offset: number; length: number }> { +function parseChunks( + data: Uint8Array, +): Array<{ type: string; data: Uint8Array; offset: number; length: number }> { const chunks: Array<{ type: string; data: Uint8Array; offset: number; length: number }> = []; let offset = 8; // Skip PNG signature - + while (offset < data.length) { const length = readUint32BE(data, offset); const type = new TextDecoder().decode(data.slice(offset + 4, offset + 8)); const chunkData = data.slice(offset + 8, offset + 8 + length); - + chunks.push({ type, data: chunkData, offset, length: 12 + length, // length field + type + data + crc }); - + offset += 12 + length; - + if (type === 'IEND') break; } - + return chunks; } @@ -135,10 +141,10 @@ function parseChunks(data: Uint8Array): Array<{ type: string; data: Uint8Array; function parseTextChunk(data: Uint8Array): { key: string; value: string } | null { const nullIndex = data.indexOf(0); if (nullIndex === -1) return null; - + const key = new TextDecoder().decode(data.slice(0, nullIndex)); const value = new TextDecoder().decode(data.slice(nullIndex + 1)); - + return { key, value }; } @@ -149,7 +155,7 @@ function parseTextChunk(data: Uint8Array): { key: string; value: string } | null */ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string | undefined { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { @@ -157,10 +163,10 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string return undefined; // Not a PNG } } - + const chunks = parseChunks(data); console.log('[extractColorFromPNG] Found', chunks.length, 'chunks'); - + let textChunksFound = 0; for (const chunk of chunks) { if (chunk.type === 'tEXt') { @@ -175,8 +181,12 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string } } } - - console.log('[extractColorFromPNG] No paarrot:color found (found', textChunksFound, 'tEXt chunks)'); + + console.log( + '[extractColorFromPNG] No paarrot:color found (found', + textChunksFound, + 'tEXt chunks)', + ); return undefined; } @@ -187,16 +197,16 @@ export function extractColorFromPNG(imageData: ArrayBuffer | Uint8Array): string */ export function extractBannerFromPNG(imageData: ArrayBuffer | Uint8Array): string | undefined { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { return undefined; // Not a PNG } } - + const chunks = parseChunks(data); - + for (const chunk of chunks) { if (chunk.type === 'tEXt') { const text = parseTextChunk(chunk.data); @@ -205,12 +215,10 @@ export function extractBannerFromPNG(imageData: ArrayBuffer | Uint8Array): strin } } } - + return undefined; } -import type { ImageMetadata, ProfileGradient } from './imageMetadata'; - /** * Extract all paarrot metadata from PNG image data * @param imageData - Raw PNG image data as ArrayBuffer or Uint8Array @@ -219,7 +227,7 @@ import type { ImageMetadata, ProfileGradient } from './imageMetadata'; export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): ImageMetadata { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); const metadata: ImageMetadata = {}; - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { @@ -227,10 +235,10 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima return metadata; // Not a PNG } } - + const chunks = parseChunks(data); console.log('[extractMetadataFromPNG] Found', chunks.length, 'chunks'); - + let textChunksFound = 0; for (const chunk of chunks) { if (chunk.type === 'tEXt') { @@ -254,9 +262,15 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima } } } - - console.log('[extractMetadataFromPNG] Final metadata extracted:', metadata, 'found', textChunksFound, 'tEXt chunks'); - + + console.log( + '[extractMetadataFromPNG] Final metadata extracted:', + metadata, + 'found', + textChunksFound, + 'tEXt chunks', + ); + return metadata; } @@ -266,22 +280,25 @@ export function extractMetadataFromPNG(imageData: ArrayBuffer | Uint8Array): Ima * @param color - The color string to embed (e.g., '#ff5500') * @returns New PNG data with embedded color, or null if not a valid PNG */ -export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null { +export function embedColorInPNG( + imageData: ArrayBuffer | Uint8Array, + color: string, +): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { return null; // Not a PNG } } - + const chunks = parseChunks(data); - + // Find IHDR chunk (always first) and any existing paarrot tEXt chunk let insertOffset = 8; // After signature let existingPaarrotChunk: { offset: number; length: number } | null = null; - + for (const chunk of chunks) { if (chunk.type === 'IHDR') { insertOffset = chunk.offset + chunk.length; // Insert after IHDR @@ -292,13 +309,13 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri } } } - + // Create new tEXt chunk with color const colorChunk = createTextChunk(PAARROT_COLOR_KEY, color); - + // Build new PNG data let newData: Uint8Array; - + if (existingPaarrotChunk) { // Replace existing chunk newData = new Uint8Array(data.length - existingPaarrotChunk.length + colorChunk.length); @@ -306,7 +323,7 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri newData.set(colorChunk, existingPaarrotChunk.offset); newData.set( data.slice(existingPaarrotChunk.offset + existingPaarrotChunk.length), - existingPaarrotChunk.offset + colorChunk.length + existingPaarrotChunk.offset + colorChunk.length, ); } else { // Insert new chunk after IHDR @@ -315,12 +332,17 @@ export function embedColorInPNG(imageData: ArrayBuffer | Uint8Array, color: stri newData.set(colorChunk, insertOffset); newData.set(data.slice(insertOffset), insertOffset + colorChunk.length); } - + return newData; } /** All paarrot metadata keys */ -const PAARROT_KEYS = [PAARROT_COLOR_KEY, PAARROT_BANNER_KEY, PAARROT_BORDER_COLOR_KEY, PAARROT_GRADIENT_KEY]; +const PAARROT_KEYS = [ + PAARROT_COLOR_KEY, + PAARROT_BANNER_KEY, + PAARROT_BORDER_COLOR_KEY, + PAARROT_GRADIENT_KEY, +]; /** * Embed paarrot metadata into PNG image data @@ -331,34 +353,37 @@ const PAARROT_KEYS = [PAARROT_COLOR_KEY, PAARROT_BANNER_KEY, PAARROT_BORDER_COLO */ export function embedMetadataInPNG( imageData: ArrayBuffer | Uint8Array, - metadata: ImageMetadata + metadata: ImageMetadata, ): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { return null; // Not a PNG } } - + const chunks = parseChunks(data); - + // Get existing metadata const existing = extractMetadataFromPNG(data); - + // Merge with new metadata const finalMetadata: ImageMetadata = { color: metadata.color !== undefined ? metadata.color : existing.color, banner: metadata.banner !== undefined ? metadata.banner : existing.banner, - avatarBorderColor: metadata.avatarBorderColor !== undefined ? metadata.avatarBorderColor : existing.avatarBorderColor, + avatarBorderColor: + metadata.avatarBorderColor !== undefined + ? metadata.avatarBorderColor + : existing.avatarBorderColor, gradient: metadata.gradient !== undefined ? metadata.gradient : existing.gradient, }; - + // Find IHDR chunk and existing paarrot chunks let insertOffset = 8; const existingChunks: { key: string; offset: number; length: number }[] = []; - + for (const chunk of chunks) { if (chunk.type === 'IHDR') { insertOffset = chunk.offset + chunk.length; @@ -369,7 +394,7 @@ export function embedMetadataInPNG( } } } - + // Create new chunks const newChunks: Uint8Array[] = []; if (finalMetadata.color) { @@ -384,46 +409,46 @@ export function embedMetadataInPNG( if (finalMetadata.gradient) { newChunks.push(createTextChunk(PAARROT_GRADIENT_KEY, JSON.stringify(finalMetadata.gradient))); } - + // Calculate new size const removedSize = existingChunks.reduce((sum, chunk) => sum + chunk.length, 0); const addedSize = newChunks.reduce((sum, chunk) => sum + chunk.byteLength, 0); const newSize = data.length - removedSize + addedSize; - + // Build new PNG const newData = new Uint8Array(newSize); let writeOffset = 0; let readOffset = 0; - + // Sort existing chunks by offset existingChunks.sort((a, b) => a.offset - b.offset); - + // Copy data, skipping old chunks and inserting new ones for (const existingChunk of existingChunks) { // Copy data before this chunk newData.set(data.slice(readOffset, existingChunk.offset), writeOffset); writeOffset += existingChunk.offset - readOffset; - + // Skip the old chunk readOffset = existingChunk.offset + existingChunk.length; } - + // If no existing chunks, insert at insertOffset if (existingChunks.length === 0) { newData.set(data.slice(0, insertOffset), 0); writeOffset = insertOffset; readOffset = insertOffset; } - + // Insert new chunks for (const newChunk of newChunks) { newData.set(newChunk, writeOffset); writeOffset += newChunk.byteLength; } - + // Copy remaining data newData.set(data.slice(readOffset), writeOffset); - + return newData; } @@ -434,19 +459,19 @@ export function embedMetadataInPNG( */ export function removeColorFromPNG(imageData: ArrayBuffer | Uint8Array): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + // Verify PNG signature for (let i = 0; i < 8; i++) { if (data[i] !== PNG_SIGNATURE[i]) { return null; // Not a PNG } } - + const chunks = parseChunks(data); - + // Find existing paarrot tEXt chunk let existingPaarrotChunk: { offset: number; length: number } | null = null; - + for (const chunk of chunks) { if (chunk.type === 'tEXt') { const text = parseTextChunk(chunk.data); @@ -456,20 +481,20 @@ export function removeColorFromPNG(imageData: ArrayBuffer | Uint8Array): Uint8Ar } } } - + if (!existingPaarrotChunk) { // No color to remove return data; } - + // Build new PNG data without the color chunk const newData = new Uint8Array(data.length - existingPaarrotChunk.length); newData.set(data.slice(0, existingPaarrotChunk.offset), 0); newData.set( data.slice(existingPaarrotChunk.offset + existingPaarrotChunk.length), - existingPaarrotChunk.offset + existingPaarrotChunk.offset, ); - + return newData; } @@ -482,7 +507,7 @@ export async function fetchAndExtractColor(url: string): Promise { if (!mxcUrl) return undefined; diff --git a/src/app/utils/profileFields.ts b/src/app/utils/profileFields.ts index ee325dbb..30191993 100644 --- a/src/app/utils/profileFields.ts +++ b/src/app/utils/profileFields.ts @@ -83,14 +83,18 @@ export function parseColorPreference(value: unknown): ColorPreference | undefine if (!value || typeof value !== 'object') return undefined; const obj = value as Record; - const on_dark = typeof obj.on_dark === 'string' && isValidHexColor(obj.on_dark) ? obj.on_dark : undefined; - const on_light = typeof obj.on_light === 'string' && isValidHexColor(obj.on_light) ? obj.on_light : undefined; + const on_dark = + typeof obj.on_dark === 'string' && isValidHexColor(obj.on_dark) ? obj.on_dark : undefined; + const on_light = + typeof obj.on_light === 'string' && isValidHexColor(obj.on_light) ? obj.on_light : undefined; if (!on_dark && !on_light) return undefined; return { on_dark, on_light }; } -export function extractColorPreferenceFromProfile(profile: Record): ColorPreference | undefined { +export function extractColorPreferenceFromProfile( + profile: Record, +): ColorPreference | undefined { const stable = parseColorPreference(profile[PROFILE_KEY_COLOR_PREFERENCE_STABLE]); if (stable) return stable; return parseColorPreference(profile[PROFILE_KEY_COLOR_PREFERENCE_UNSTABLE]); @@ -98,7 +102,7 @@ export function extractColorPreferenceFromProfile(profile: Record; const sku_id = typeof obj.sku_id === 'string' ? obj.sku_id : undefined; const name = typeof obj.name === 'string' ? obj.name : undefined; - const assets = obj.assets; + const { assets } = obj; if (!sku_id || !name || !assets || typeof assets !== 'object') return undefined; const parsedAssets: Record = {}; @@ -145,7 +149,9 @@ function parseStoredCollectible(value: unknown): StoredCollectible | undefined { }; } -export function extractCollectiblesFromProfile(profile: Record): CollectibleProfileFields { +export function extractCollectiblesFromProfile( + profile: Record, +): CollectibleProfileFields { return { profile_effect: parseStoredCollectible(profile[PROFILE_KEY_PROFILE_EFFECT]), nameplate: parseStoredCollectible(profile[PROFILE_KEY_NAMEPLATE]), @@ -153,14 +159,17 @@ export function extractCollectiblesFromProfile(profile: Record) }; } -export async function loadUserCollectibles(mx: MatrixClient, userId: string): Promise { +export async function loadUserCollectibles( + mx: MatrixClient, + userId: string, +): Promise { return extractCollectiblesFromProfile(await getProfileFields(mx, userId)); } export async function saveCollectible( mx: MatrixClient, key: string, - collectible: StoredCollectible | undefined + collectible: StoredCollectible | undefined, ): Promise { if (!(await mx.doesServerSupportExtendedProfiles())) { throw new Error('Server does not support extended profile fields (MSC4133)'); @@ -174,15 +183,24 @@ export async function saveCollectible( await mx.setExtendedProfileProperty(key, collectible); } -export async function saveProfileEffect(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise { +export async function saveProfileEffect( + mx: MatrixClient, + collectible: StoredCollectible | undefined, +): Promise { await saveCollectible(mx, PROFILE_KEY_PROFILE_EFFECT, collectible); } -export async function saveNameplate(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise { +export async function saveNameplate( + mx: MatrixClient, + collectible: StoredCollectible | undefined, +): Promise { await saveCollectible(mx, PROFILE_KEY_NAMEPLATE, collectible); } -export async function saveAvatarDecoration(mx: MatrixClient, collectible: StoredCollectible | undefined): Promise { +export async function saveAvatarDecoration( + mx: MatrixClient, + collectible: StoredCollectible | undefined, +): Promise { await saveCollectible(mx, PROFILE_KEY_AVATAR_DECORATION, collectible); } @@ -228,12 +246,15 @@ export async function getColorPreferenceProfileKey(mx: MatrixClient): Promise { return extractColorPreferenceFromProfile(await getProfileFields(mx, userId)); } -export function extractMemberColorPreference(room: Room | undefined, userId: string): ColorPreference | undefined { +export function extractMemberColorPreference( + room: Room | undefined, + userId: string, +): ColorPreference | undefined { if (!room || typeof (room as Room).getMember !== 'function' || !userId) return undefined; const member = room.getMember(userId); const content = member?.events.member?.getContent(); @@ -241,7 +262,10 @@ export function extractMemberColorPreference(room: Room | undefined, userId: str return extractColorPreferenceFromProfile(content as Record); } -export async function saveColorPreference(mx: MatrixClient, preference: ColorPreference): Promise { +export async function saveColorPreference( + mx: MatrixClient, + preference: ColorPreference, +): Promise { if (!(await mx.doesServerSupportExtendedProfiles())) { throw new Error('Server does not support extended profile fields (MSC4133)'); } diff --git a/src/app/utils/regex.ts b/src/app/utils/regex.ts index f46d0760..c0beb801 100644 --- a/src/app/utils/regex.ts +++ b/src/app/utils/regex.ts @@ -34,5 +34,5 @@ export const EMOJI_REG_G = new RegExp(`${URL_NEG_LB}(${EMOJI_SEQUENCE})`, 'gu'); /** Plain-text messages that are only emoji / :shortcodes: (up to 10). */ export const JUMBO_EMOJI_REG = new RegExp( `^(?:(?:${EMOJI_SEQUENCE}|:[^\\s:]+:)(?:${VARIATION_SELECTOR_PATTERN}|\\s)*){1,10}$`, - 'u' + 'u', ); diff --git a/src/app/utils/registerDesktopMediaSaver.ts b/src/app/utils/registerDesktopMediaSaver.ts index c0a750d4..7df9d4e0 100644 --- a/src/app/utils/registerDesktopMediaSaver.ts +++ b/src/app/utils/registerDesktopMediaSaver.ts @@ -21,11 +21,17 @@ async function blobToUint8Array(blob: Blob): Promise { return new Uint8Array(buffer); } -function guessFilters(filename: string, mimeType?: string): Array<{ name: string; extensions: string[] }> { +function guessFilters( + filename: string, + mimeType?: string, +): Array<{ name: string; extensions: string[] }> { const ext = filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : ''; const mime = (mimeType || '').toLowerCase(); - if (mime.startsWith('image/') || ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) { + if ( + mime.startsWith('image/') || + ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext) + ) { return [ { name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'] }, { name: 'All Files', extensions: ['*'] }, diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index a6944c07..be96d381 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -1,5 +1,3 @@ -import { IconName, IconSrc } from '../components/icons'; - import { EventTimeline, EventTimelineSet, @@ -18,6 +16,7 @@ import { RoomMember, } from 'matrix-js-sdk'; import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend'; +import { IconName, IconSrc } from '../components/icons'; import { AccountDataEvent } from '../../types/matrix/accountData'; import { IRoomCreateContent, @@ -34,7 +33,7 @@ import { export const getStateEvent = ( room: Room, eventType: StateEvent, - stateKey = '' + stateKey = '', ): MatrixEvent | undefined => { const fromCurrent = room.currentState?.getStateEvents(eventType, stateKey); if (fromCurrent) return fromCurrent; @@ -52,7 +51,7 @@ export const getStateEvents = (room: Room, eventType: StateEvent): MatrixEvent[] export const getAccountData = ( mx: MatrixClient, - eventType: AccountDataEvent + eventType: AccountDataEvent, ): MatrixEvent | undefined => mx.getAccountData(eventType as any); export const getMDirects = (mDirectEvent: MatrixEvent): Set => { @@ -175,7 +174,7 @@ export const shouldShowForumLobby = isForumContainer; export const findForumRootSpace = ( mx: MatrixClient, roomId: string, - roomToParents: RoomToParents + roomToParents: RoomToParents, ): string | undefined => { const ordered = [roomId, ...Array.from(getAllParents(roomToParents, roomId))]; for (const id of ordered) { @@ -199,10 +198,7 @@ export const isUnsupportedRoom = (room: Room | null): boolean => { if (!room) return false; const roomType = getRoomCreateType(room); if (!roomType) return true; // Consider room unsupported if m.room.create event doesn't exist - return ( - roomType !== RoomType.Space && - roomType !== RoomType.Forum - ); + return roomType !== RoomType.Space && roomType !== RoomType.Forum; }; export function isValidChild(mEvent: MatrixEvent): boolean { @@ -240,7 +236,7 @@ export const getSpaceChildren = (room: Room) => export const mapParentWithChildren = ( roomToParents: RoomToParents, roomId: string, - children: string[] + children: string[], ) => { const allParents = getAllParents(roomToParents, roomId); children.forEach((childId) => { @@ -266,7 +262,7 @@ export const getRoomToParents = (mx: MatrixClient): RoomToParents => { export const getOrphanParents = (roomToParents: RoomToParents, roomId: string): string[] => { const parents = getAllParents(roomToParents, roomId); const orphanParents = Array.from(parents).filter( - (parentRoomId) => !roomToParents.has(parentRoomId) + (parentRoomId) => !roomToParents.has(parentRoomId), ); return orphanParents; @@ -373,7 +369,7 @@ export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => { export const joinRuleToIconSrc = ( icons: Record, joinRule: JoinRule, - space: boolean + space: boolean, ): IconSrc | undefined => { if (joinRule === JoinRule.Restricted) { return space ? icons.Space : icons.Hash; @@ -394,11 +390,12 @@ export const getRoomAvatarUrl = ( mx: MatrixClient, room: Room, size: 32 | 96 = 32, - useAuthentication = false + useAuthentication = false, ): string | undefined => { const mxcUrl = room.getMxcAvatarUrl(); return mxcUrl - ? mx.mxcUrlToHttp(mxcUrl, size, size, 'crop', undefined, false, useAuthentication) ?? undefined + ? (mx.mxcUrlToHttp(mxcUrl, size, size, 'crop', undefined, false, useAuthentication) ?? + undefined) : undefined; }; @@ -406,7 +403,7 @@ export const getDirectRoomAvatarUrl = ( mx: MatrixClient, room: Room, size: 32 | 96 = 32, - useAuthentication = false + useAuthentication = false, ): string | undefined => { const mxcUrl = room.getAvatarFallbackMember()?.getMxcAvatarUrl(); @@ -441,10 +438,10 @@ export const parseReplyFormattedBody = ( roomId: string, userId: string, eventId: string, - formattedBody: string + formattedBody: string, ): string => { const replyToLink = `In reply to`; const userLink = `${userId}`; @@ -461,7 +458,7 @@ export const getMemberDisplayName = (room: Room, userId: string): string | undef export const getMemberSearchStr = ( member: RoomMember, query: string, - mxIdToName: (mxId: string) => string + mxIdToName: (mxId: string) => string, ): string[] => [ member.rawDisplayName === member.userId ? mxIdToName(member.userId) : member.rawDisplayName, query.startsWith('@') || query.indexOf(':') > -1 ? member.userId : mxIdToName(member.userId), @@ -500,7 +497,7 @@ export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string timelineSet.relations.getChildEventsForEvent( eventId, RelationType.Annotation, - EventType.Reaction + EventType.Reaction, ); export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, eventType: string) => @@ -508,7 +505,7 @@ export const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, ev export const getLatestEdit = ( targetEvent: MatrixEvent, - editEvents: MatrixEvent[] + editEvents: MatrixEvent[], ): MatrixEvent | undefined => { const eventByTargetSender = (rEvent: MatrixEvent) => rEvent.getSender() === targetEvent.getSender(); @@ -518,7 +515,7 @@ export const getLatestEdit = ( export const getEditedEvent = ( mEventId: string, mEvent: MatrixEvent, - timelineSet: EventTimelineSet + timelineSet: EventTimelineSet, ): MatrixEvent | undefined => { const edits = getEventEdits(timelineSet, mEventId, mEvent.getType()); return edits && getLatestEdit(mEvent, edits.getRelations()); @@ -539,7 +536,7 @@ export const canEditEvent = (mx: MatrixClient, mEvent: MatrixEvent) => { export const getLatestEditableEvt = ( timeline: EventTimeline, - canEdit: (mEvent: MatrixEvent) => boolean + canEdit: (mEvent: MatrixEvent) => boolean, ): MatrixEvent | undefined => { const events = timeline.getEvents(); @@ -569,7 +566,7 @@ export const getMentionContent = (userIds: string[], room: boolean): IMentions = export const getCommonRooms = ( mx: MatrixClient, rooms: string[], - otherUserId: string + otherUserId: string, ): string[] => { const commonRooms: string[] = []; @@ -615,7 +612,7 @@ export const getAllVersionsRoomCreator = (room: Room): Set => { export const guessPerfectParent = ( mx: MatrixClient, roomId: string, - parents: string[] + parents: string[], ): string | undefined => { if (parents.length === 1) { return parents[0]; @@ -631,7 +628,7 @@ export const guessPerfectParent = ( const powerLevels = getStateEvent( r, - StateEvent.RoomPowerLevels + StateEvent.RoomPowerLevels, )?.getContent(); const { users_default: usersDefault, users } = powerLevels ?? {}; @@ -654,7 +651,7 @@ export const guessPerfectParent = ( parents.forEach((parentId) => { const parentSpecialUsers = getSpecialUsers(parentId); const matchedUsersCount = parentSpecialUsers.filter((userId) => - roomSpecialUsers.includes(userId) + roomSpecialUsers.includes(userId), ).length; if (matchedUsersCount > score) { diff --git a/src/app/utils/saveMedia.ts b/src/app/utils/saveMedia.ts index 826c3b61..128d0bd4 100644 --- a/src/app/utils/saveMedia.ts +++ b/src/app/utils/saveMedia.ts @@ -34,7 +34,7 @@ export const saveMediaBlob = async (blob: Blob, filename: string): Promise export const downloadAndSaveMedia = async ( src: string, filename: string, - accessToken?: string | null + accessToken?: string | null, ): Promise => { let blob: Blob; try { diff --git a/src/app/utils/tauri.ts b/src/app/utils/tauri.ts index 6bf2c082..225d08c7 100644 --- a/src/app/utils/tauri.ts +++ b/src/app/utils/tauri.ts @@ -4,11 +4,11 @@ */ export const openExternalUrl = async (url: string): Promise => { console.log('[openExternalUrl] called with:', url); - + // Use Electron's shell.openExternal if in Electron if (isElectron()) { try { - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.shell?.openExternal) { await electron.shell.openExternal(url); console.log('[openExternalUrl] Electron shell.openExternal succeeded'); @@ -18,7 +18,7 @@ export const openExternalUrl = async (url: string): Promise => { console.warn('[openExternalUrl] Electron shell.openExternal failed:', err); } } - + // Use Tauri for actual Tauri builds if (isTauri() && !isElectron()) { try { @@ -30,7 +30,7 @@ export const openExternalUrl = async (url: string): Promise => { return; } catch (pluginErr) { console.warn('[openExternalUrl] Tauri opener plugin failed:', pluginErr); - + // Fallback: try the custom command (useful if plugin fails due to ACL) try { console.log('[openExternalUrl] trying Tauri invoke command fallback...'); @@ -43,7 +43,7 @@ export const openExternalUrl = async (url: string): Promise => { } } } - + console.log('[openExternalUrl] falling back to window.open'); window.open(url, '_blank'); }; @@ -71,7 +71,7 @@ export const getYouTubeStream = async (url: string): Promise } // Check for Electron - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.youtube?.getStream) { const result = await electron.youtube.getStream(url); // Electron returns { success: true, data: { video_url, title } } or { success: false, error } @@ -100,7 +100,7 @@ export const isYouTubeStreamingAvailable = (): boolean => { } // Check for Electron - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.youtube?.getStream) { return true; } @@ -137,7 +137,7 @@ export const focusWindow = async (): Promise => { // Use Electron's window focus if in Electron if (isElectron()) { try { - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.window?.focus) { await electron.window.focus(); } @@ -164,13 +164,15 @@ export const focusWindow = async (): Promise => { * Set up listener for notification tap/click actions * Call this once at app startup with a navigation callback */ -export const setupNotificationTapListener = async (onTap: (path: string) => void): Promise => { +export const setupNotificationTapListener = async ( + onTap: (path: string) => void, +): Promise => { notificationTapCallback = onTap; - + // Use Electron's native notification handler if in Electron if (isElectron()) { try { - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.notification?.onNavigate) { electron.notification.onNavigate((data: { path?: string }) => { if (data.path && typeof data.path === 'string' && notificationTapCallback) { @@ -184,16 +186,16 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void return; } } - + // Use Tauri plugin for actual Tauri builds (not Electron) if (isTauri() && !isElectron()) { try { const { onAction } = await import('@tauri-apps/plugin-notification'); - + await onAction(async (notification) => { // Bring window to front first await focusWindow(); - + // Get the path from extra data and navigate const path = notification.notification?.extra?.path; if (path && typeof path === 'string' && notificationTapCallback) { @@ -208,13 +210,16 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void if (isCapacitorNative()) { try { const { LocalNotifications } = await importCapacitorLocalNotifications(); - await LocalNotifications.addListener('localNotificationActionPerformed', async (event: any) => { - await focusWindow(); - const path = event?.notification?.extra?.path; - if (path && typeof path === 'string' && notificationTapCallback) { - notificationTapCallback(path); - } - }); + await LocalNotifications.addListener( + 'localNotificationActionPerformed', + async (event: any) => { + await focusWindow(); + const path = event?.notification?.extra?.path; + if (path && typeof path === 'string' && notificationTapCallback) { + notificationTapCallback(path); + } + }, + ); } catch (err) { console.warn('Failed to set up Capacitor notification tap listener:', err); } @@ -224,14 +229,12 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void /** * Check if we're running inside a Tauri application */ -export const isTauri = (): boolean => - '__TAURI__' in window || '__TAURI_INTERNALS__' in window; +export const isTauri = (): boolean => '__TAURI__' in window || '__TAURI_INTERNALS__' in window; /** * Check if we're running inside Electron (not Tauri) */ -export const isElectron = (): boolean => - typeof window !== 'undefined' && 'electron' in window; +export const isElectron = (): boolean => typeof window !== 'undefined' && 'electron' in window; /** * Check if we're running inside a Capacitor native app @@ -239,7 +242,11 @@ export const isElectron = (): boolean => export const isCapacitorNative = (): boolean => { if (typeof window === 'undefined') return false; const cap = (window as any).Capacitor; - return Boolean(cap?.isNativePlatform?.() || cap?.getPlatform?.() === 'android' || cap?.getPlatform?.() === 'ios'); + return Boolean( + cap?.isNativePlatform?.() || + cap?.getPlatform?.() === 'android' || + cap?.getPlatform?.() === 'ios', + ); }; /** @@ -327,7 +334,7 @@ const ensureNotificationChannel = async (): Promise => { try { const { createChannel, Importance } = await import('@tauri-apps/plugin-notification'); - + await createChannel({ id: 'messages', name: 'Messages', @@ -336,7 +343,7 @@ const ensureNotificationChannel = async (): Promise => { vibration: true, sound: 'default', }); - + notificationChannelCreated = true; } catch (err) { console.warn('Failed to create notification channel:', err); @@ -431,7 +438,7 @@ export const sendNotification = async (options: { // Use Electron's native notification API if in Electron if (isElectron()) { try { - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.notification?.show) { await electron.notification.show({ title, @@ -511,7 +518,7 @@ export const sendNotification = async (options: { console.warn('Capacitor notification failed:', err); } } - + // Fallback to browser notification sendBrowserNotification({ title, body, icon, onClick }); }; @@ -532,7 +539,7 @@ export const readClipboardImage = async (): Promise => { // Use Electron's clipboard API if in Electron if (isElectron()) { try { - const electron = (window as any).electron; + const { electron } = window as any; if (electron?.clipboard?.readImage) { const result = await electron.clipboard.readImage(); // IPC may return a data URL string or { success, data } depending on path. @@ -543,7 +550,7 @@ export const readClipboardImage = async (): Promise => { ? result.data : null; if (!dataUrl) return null; - + // Convert data URL to File const response = await fetch(dataUrl); const blob = await response.blob(); @@ -561,7 +568,7 @@ export const readClipboardImage = async (): Promise => { try { const { invoke } = await import('@tauri-apps/api/core'); const dataUrl = await invoke('read_clipboard_image'); - + if (!dataUrl) return null; // Convert data URL to File @@ -574,7 +581,7 @@ export const readClipboardImage = async (): Promise => { return null; } } - + return null; }; @@ -593,7 +600,9 @@ export interface BackgroundSyncCredentials { * Start background Matrix sync on mobile * This runs the sync in native Rust code, allowing notifications even when the app is backgrounded */ -export const startBackgroundSync = async (credentials: BackgroundSyncCredentials): Promise => { +export const startBackgroundSync = async ( + credentials: BackgroundSyncCredentials, +): Promise => { if (!isTauriMobile()) { console.log('[BackgroundSync] Not on mobile, skipping'); return; diff --git a/src/app/utils/telegramStickerImport.ts b/src/app/utils/telegramStickerImport.ts index 8ed269d3..85aecfe7 100644 --- a/src/app/utils/telegramStickerImport.ts +++ b/src/app/utils/telegramStickerImport.ts @@ -69,12 +69,12 @@ export type ImportProgressCallback = (current: number, total: number, status: st */ export function extractPackName(url: string): string | null { const trimmed = url.trim(); - + // Direct pack name (no URL) if (/^[a-zA-Z0-9_]+$/.test(trimmed)) { return trimmed; } - + // URL format: t.me/addstickers/PackName or https://t.me/addstickers/PackName const match = trimmed.match(/(?:https?:\/\/)?t\.me\/addstickers\/([a-zA-Z0-9_]+)/i); return match ? match[1] : null; @@ -88,22 +88,22 @@ export function extractPackName(url: string): string | null { */ export async function fetchStickerSet( botToken: string, - setName: string + setName: string, ): Promise { const response = await fetch( - `${TELEGRAM_API}${botToken}/getStickerSet?name=${encodeURIComponent(setName)}` + `${TELEGRAM_API}${botToken}/getStickerSet?name=${encodeURIComponent(setName)}`, ); - + if (!response.ok) { throw new Error(`Failed to fetch sticker set: ${response.statusText}`); } - + const data: TelegramResponse = await response.json(); - + if (!data.ok || !data.result) { throw new Error(data.description || 'Failed to fetch sticker set'); } - + return data.result; } @@ -115,17 +115,17 @@ export async function fetchStickerSet( */ async function getFilePath(botToken: string, fileId: string): Promise { const response = await fetch(`${TELEGRAM_API}${botToken}/getFile?file_id=${fileId}`); - + if (!response.ok) { throw new Error(`Failed to get file path: ${response.statusText}`); } - + const data: TelegramResponse<{ file_path: string }> = await response.json(); - + if (!data.ok || !data.result) { throw new Error(data.description || 'Failed to get file path'); } - + return data.result.file_path; } @@ -138,11 +138,11 @@ async function getFilePath(botToken: string, fileId: string): Promise { */ async function downloadFile(botToken: string, filePath: string): Promise { const response = await tauriFetch(`${TELEGRAM_FILE_API}${botToken}/${filePath}`); - + if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } - + return response.blob(); } @@ -153,16 +153,12 @@ async function downloadFile(botToken: string, filePath: string): Promise { * @param filename - Filename for the upload * @returns mxc:// URL */ -async function uploadToMatrix( - mx: MatrixClient, - blob: Blob, - filename: string -): Promise { +async function uploadToMatrix(mx: MatrixClient, blob: Blob, filename: string): Promise { const response = await mx.uploadContent(blob, { name: filename, type: blob.type || 'image/webp', }); - + return response.content_uri; } @@ -192,51 +188,51 @@ export async function importTelegramStickerPack( mx: MatrixClient, botToken: string, packUrl: string, - onProgress?: ImportProgressCallback + onProgress?: ImportProgressCallback, ): Promise<{ packId: string; content: PackContent }> { // Extract pack name from URL const packName = extractPackName(packUrl); if (!packName) { throw new Error('Invalid Telegram sticker pack URL'); } - + onProgress?.(0, 1, 'Fetching sticker pack info...'); - + // Fetch sticker set from Telegram const stickerSet = await fetchStickerSet(botToken, packName); - + const total = stickerSet.stickers.length; const images: PackImages = {}; - + // Download and upload each sticker sequentially // (Using sequential await is intentional to avoid overwhelming APIs) for (let i = 0; i < stickerSet.stickers.length; i += 1) { const sticker = stickerSet.stickers[i]; const isAnimated = sticker.is_animated; const isVideo = sticker.is_video; - + let stickerType = 'static'; if (isAnimated) stickerType = 'animated'; else if (isVideo) stickerType = 'video'; onProgress?.(i + 1, total, `Importing ${stickerType} sticker ${i + 1}/${total}...`); - + try { // Get file path from Telegram // eslint-disable-next-line no-await-in-loop const filePath = await getFilePath(botToken, sticker.file_id); - + // Download the sticker // eslint-disable-next-line no-await-in-loop let blob = await downloadFile(botToken, filePath); - + // Generate a shortcode from emoji or index const shortcode = sticker.emoji ? `${packName}_${sticker.emoji.codePointAt(0)?.toString(16) || i}` : `${packName}_${i}`; - + let finalMimeType = getMimeType(filePath); let extension = 'webp'; - + // Convert animated stickers to GIF if (isAnimated && filePath.endsWith('.tgs')) { onProgress?.(i + 1, total, `Converting animated sticker ${i + 1}/${total} to GIF...`); @@ -251,15 +247,11 @@ export async function importTelegramStickerPack( finalMimeType = 'image/gif'; extension = 'gif'; } - + // Upload to Matrix // eslint-disable-next-line no-await-in-loop - const mxcUrl = await uploadToMatrix( - mx, - blob, - `${shortcode}.${extension}` - ); - + const mxcUrl = await uploadToMatrix(mx, blob, `${shortcode}.${extension}`); + // Add to images images[shortcode] = { url: mxcUrl, @@ -278,11 +270,11 @@ export async function importTelegramStickerPack( console.error(`Failed to import sticker ${i + 1}:`, err); } } - + if (Object.keys(images).length === 0) { throw new Error('Failed to import any stickers from the pack'); } - + // eslint-disable-next-line no-console console.log(`Successfully imported ${Object.keys(images).length} stickers`); @@ -294,14 +286,14 @@ export async function importTelegramStickerPack( }, images, }; - + // Generate a unique pack ID const packId = `telegram_${packName}`; - + // Get existing user emotes or create new const existingEvent = getAccountData(mx, AccountDataEvent.PoniesUserEmotes); const existingEmotes = existingEvent?.getContent() as PackContent | undefined; - + // Merge with existing pack if any const mergedContent: PackContent = { pack: existingEmotes?.pack || { usage: [ImageUsage.Emoticon, ImageUsage.Sticker] }, @@ -310,7 +302,7 @@ export async function importTelegramStickerPack( ...images, }, }; - + // Save to user account data // eslint-disable-next-line no-console console.log('Saving merged pack to account data:', AccountDataEvent.PoniesUserEmotes); @@ -320,13 +312,13 @@ export async function importTelegramStickerPack( await mx.setAccountData(AccountDataEvent.PoniesUserEmotes as any, mergedContent as any); // eslint-disable-next-line no-console console.log('Pack saved successfully'); - + // Force the account data event to be emitted for UI refresh const updatedEvent = getAccountData(mx, AccountDataEvent.PoniesUserEmotes); // eslint-disable-next-line no-console console.log('Updated account data after save:', updatedEvent?.getContent()); - + onProgress?.(total, total, 'Import complete!'); - + return { packId, content: packContent }; } diff --git a/src/app/utils/viewTransitions.ts b/src/app/utils/viewTransitions.ts index 7944ecf9..bfd5afbc 100644 --- a/src/app/utils/viewTransitions.ts +++ b/src/app/utils/viewTransitions.ts @@ -49,18 +49,18 @@ export const enableViewTransitionsForNavigation = (): void => { // Intercept link clicks and navigation to add view transitions const handleLinkClick = (event: MouseEvent) => { const target = (event.target as HTMLElement).closest('a'); - + if (!target) return; if (target.target === '_blank') return; if (target.origin !== window.location.origin) return; if (event.metaKey || event.ctrlKey || event.shiftKey) return; const url = new URL(target.href); - + // Only handle same-origin navigation if (url.origin === window.location.origin) { event.preventDefault(); - + withViewTransition(() => { window.history.pushState({}, '', target.href); window.dispatchEvent(new PopStateEvent('popstate')); diff --git a/src/app/utils/webpMetadata.ts b/src/app/utils/webpMetadata.ts index 434d3af9..94b54882 100644 --- a/src/app/utils/webpMetadata.ts +++ b/src/app/utils/webpMetadata.ts @@ -1,7 +1,7 @@ /** * Utilities for reading and writing WebP metadata (custom XMP chunks) * Used to embed user color in avatar images - * + * * WebP uses RIFF container format: * - File starts with "RIFF" (4 bytes) + file size (4 bytes LE) + "WEBP" (4 bytes) * - Chunks: chunk ID (4 bytes) + chunk size (4 bytes LE) + chunk data (+ padding byte if odd size) @@ -9,7 +9,7 @@ /* eslint-disable no-bitwise */ /* eslint-disable no-plusplus */ -/* eslint-disable no-console */ + /* eslint-disable no-restricted-syntax */ /** RIFF signature bytes */ @@ -20,13 +20,15 @@ const WEBP_SIGNATURE = new Uint8Array([0x57, 0x45, 0x42, 0x50]); // "WEBP" export const PAARROT_COLOR_KEY = 'paarrot:color'; /** Custom chunk ID for paarrot color - using XMP_ as it's a standard metadata chunk */ -const XMP_CHUNK_ID = new Uint8Array([0x58, 0x4D, 0x50, 0x20]); // "XMP " +const XMP_CHUNK_ID = new Uint8Array([0x58, 0x4d, 0x50, 0x20]); // "XMP " /** * Read a 32-bit little-endian integer from a buffer */ function readUint32LE(data: Uint8Array, offset: number): number { - return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24); + return ( + data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24) + ); } /** @@ -46,17 +48,17 @@ function writeUint32LE(value: number): Uint8Array { */ function isWebP(data: Uint8Array): boolean { if (data.length < 12) return false; - + // Check RIFF signature for (let i = 0; i < 4; i++) { if (data[i] !== RIFF_SIGNATURE[i]) return false; } - + // Check WEBP signature at offset 8 for (let i = 0; i < 4; i++) { if (data[8 + i] !== WEBP_SIGNATURE[i]) return false; } - + return true; } @@ -90,28 +92,30 @@ function extractColorFromXMP(xmpData: string): string | undefined { /** * Parse WebP chunks from image data */ -function parseChunks(data: Uint8Array): Array<{ id: string; data: Uint8Array; offset: number; length: number }> { +function parseChunks( + data: Uint8Array, +): Array<{ id: string; data: Uint8Array; offset: number; length: number }> { const chunks: Array<{ id: string; data: Uint8Array; offset: number; length: number }> = []; let offset = 12; // Skip RIFF header (4) + size (4) + WEBP (4) - + while (offset + 8 <= data.length) { const id = new TextDecoder().decode(data.slice(offset, offset + 4)); const size = readUint32LE(data, offset + 4); const chunkData = data.slice(offset + 8, offset + 8 + size); - + // Chunk length includes padding byte if size is odd const paddedSize = size + (size % 2); - + chunks.push({ id, data: chunkData, offset, length: 8 + paddedSize, // header (8) + data + optional padding }); - + offset += 8 + paddedSize; } - + return chunks; } @@ -122,13 +126,13 @@ function parseChunks(data: Uint8Array): Array<{ id: string; data: Uint8Array; of */ export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): string | undefined { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isWebP(data)) { return undefined; } - + const chunks = parseChunks(data); - + for (const chunk of chunks) { if (chunk.id === 'XMP ') { const xmpString = new TextDecoder().decode(chunk.data); @@ -138,7 +142,7 @@ export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): strin } } } - + return undefined; } @@ -148,18 +152,21 @@ export function extractColorFromWebP(imageData: ArrayBuffer | Uint8Array): strin * @param color - The color string to embed (e.g., '#ff5500') * @returns New WebP data with embedded color, or null if not a valid WebP */ -export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: string): Uint8Array | null { +export function embedColorInWebP( + imageData: ArrayBuffer | Uint8Array, + color: string, +): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isWebP(data)) { return null; } - + const chunks = parseChunks(data); - + // Find existing XMP chunk with our color let existingXMPChunk: { offset: number; length: number } | null = null; - + for (const chunk of chunks) { if (chunk.id === 'XMP ') { const xmpString = new TextDecoder().decode(chunk.data); @@ -169,21 +176,21 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str } } } - + // Create XMP chunk with color const xmpData = createXMPData(color); const xmpBytes = new TextEncoder().encode(xmpData); const xmpPaddedSize = xmpBytes.length + (xmpBytes.length % 2); // Add padding byte if odd - + // XMP chunk: ID (4) + size (4) + data + optional padding const xmpChunk = new Uint8Array(8 + xmpPaddedSize); xmpChunk.set(XMP_CHUNK_ID, 0); xmpChunk.set(writeUint32LE(xmpBytes.length), 4); xmpChunk.set(xmpBytes, 8); // Padding byte is already 0 from Uint8Array initialization - + let newData: Uint8Array; - + if (existingXMPChunk) { // Replace existing chunk newData = new Uint8Array(data.length - existingXMPChunk.length + xmpChunk.length); @@ -191,7 +198,7 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str newData.set(xmpChunk, existingXMPChunk.offset); newData.set( data.slice(existingXMPChunk.offset + existingXMPChunk.length), - existingXMPChunk.offset + xmpChunk.length + existingXMPChunk.offset + xmpChunk.length, ); } else { // Insert new chunk at end (before any trailing data) @@ -199,11 +206,11 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str newData.set(data, 0); newData.set(xmpChunk, data.length); } - + // Update RIFF file size (at offset 4) const newFileSize = newData.length - 8; // RIFF size excludes first 8 bytes newData.set(writeUint32LE(newFileSize), 4); - + return newData; } @@ -214,16 +221,16 @@ export function embedColorInWebP(imageData: ArrayBuffer | Uint8Array, color: str */ export function removeColorFromWebP(imageData: ArrayBuffer | Uint8Array): Uint8Array | null { const data = imageData instanceof Uint8Array ? imageData : new Uint8Array(imageData); - + if (!isWebP(data)) { return null; } - + const chunks = parseChunks(data); - + // Find existing XMP chunk with our color let existingXMPChunk: { offset: number; length: number } | null = null; - + for (const chunk of chunks) { if (chunk.id === 'XMP ') { const xmpString = new TextDecoder().decode(chunk.data); @@ -233,24 +240,24 @@ export function removeColorFromWebP(imageData: ArrayBuffer | Uint8Array): Uint8A } } } - + if (!existingXMPChunk) { // No color to remove return data; } - + // Build new WebP data without the XMP chunk const newData = new Uint8Array(data.length - existingXMPChunk.length); newData.set(data.slice(0, existingXMPChunk.offset), 0); newData.set( data.slice(existingXMPChunk.offset + existingXMPChunk.length), - existingXMPChunk.offset + existingXMPChunk.offset, ); - + // Update RIFF file size const newFileSize = newData.length - 8; newData.set(writeUint32LE(newFileSize), 4); - + return newData; } @@ -263,7 +270,7 @@ export async function fetchAndExtractColorFromWebP(url: string): Promise => { - return new Promise((resolve, reject) => { +const deleteIndexedDB = (dbName: string): Promise => + new Promise((resolve, reject) => { const request = global.indexedDB.deleteDatabase(dbName); request.onsuccess = () => { console.log(`[initMatrix] Deleted IndexedDB database: ${dbName}`); @@ -24,7 +24,6 @@ const deleteIndexedDB = (dbName: string): Promise => { resolve(); }; }); -}; const getAllIndexedDBNames = async (): Promise => { try { @@ -36,11 +35,11 @@ const getAllIndexedDBNames = async (): Promise => { resolve([]); }, 2000); }); - - const databasesPromise = (global.indexedDB as any).databases().then((dbs: any[]) => { - return dbs.map((db: any) => db.name).filter(Boolean); - }); - + + const databasesPromise = (global.indexedDB as any) + .databases() + .then((dbs: any[]) => dbs.map((db: any) => db.name).filter(Boolean)); + return await Promise.race([databasesPromise, timeoutPromise]); } } catch (error) { @@ -52,21 +51,22 @@ const getAllIndexedDBNames = async (): Promise => { const deleteAllMatrixDatabases = async (): Promise => { console.log('[initMatrix] Clearing all Matrix-related IndexedDB databases...'); - + const dbNames = await getAllIndexedDBNames(); console.log('[initMatrix] Found databases:', dbNames); - + // Delete all Matrix-related databases (with matrix-js-sdk: prefix) - const matrixDbNames = dbNames.filter(name => - name.startsWith('matrix-js-sdk:') || - name.startsWith('crypto@') || - name.startsWith('sync@') || - name === 'crypto-store' || - name === 'web-sync-store' + const matrixDbNames = dbNames.filter( + (name) => + name.startsWith('matrix-js-sdk:') || + name.startsWith('crypto@') || + name.startsWith('sync@') || + name === 'crypto-store' || + name === 'web-sync-store', ); - + console.log('[initMatrix] Deleting Matrix databases:', matrixDbNames); - + for (const dbName of matrixDbNames) { try { await deleteIndexedDB(dbName); @@ -82,23 +82,22 @@ const deleteAllMatrixDatabases = async (): Promise => { */ const deleteRustCryptoDatabase = async (session: Session): Promise => { console.log('[initMatrix] 🔑 Attempting to delete Rust crypto database to fix key conflicts...'); - + const dbNames = await getAllIndexedDBNames(); const storagePrefix = `${session.userId}@${session.deviceId}`; - + // Find crypto databases for this session - const cryptoDbNames = dbNames.filter(name => - name.includes('matrix-sdk-crypto') || - name.includes(storagePrefix) + const cryptoDbNames = dbNames.filter( + (name) => name.includes('matrix-sdk-crypto') || name.includes(storagePrefix), ); - + if (cryptoDbNames.length === 0) { console.log('[initMatrix] No crypto databases found to delete'); return false; } - + console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - + for (const dbName of cryptoDbNames) { try { await deleteIndexedDB(dbName); @@ -107,7 +106,7 @@ const deleteRustCryptoDatabase = async (session: Session): Promise => { console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error); } } - + return true; }; @@ -118,47 +117,56 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { // Listen for HTTP errors from the client let keyConflictCount = 0; const KEY_CONFLICT_THRESHOLD = 3; - + // Patch console.log/error to detect the key conflict errors const originalConsoleLog = console.log; const keyConflictPattern = /One time key.*already exists/; - + // We need to use a different approach - listen to the crypto module // Since we can't directly intercept, we'll use a MutationObserver-style approach // by checking for repeated key upload failures - + const checkKeyConflict = (args: any[]): boolean => { - const message = args.map(a => String(a)).join(' '); + const message = args.map((a) => String(a)).join(' '); return keyConflictPattern.test(message); }; - + // Override console methods temporarily to detect the errors const originalError = console.error; const originalWarn = console.warn; - + const errorHandler = (...args: any[]) => { if (checkKeyConflict(args)) { keyConflictCount++; - console.log(`[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`); - + console.log( + `[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`, + ); + if (keyConflictCount >= KEY_CONFLICT_THRESHOLD && !handlingKeyConflict) { handlingKeyConflict = true; console.log('[initMatrix] 🔄 Too many key conflicts detected, attempting auto-fix...'); - + // Schedule the fix for next page load to avoid issues during active session - localStorage.setItem('cinny_fix_key_conflict', JSON.stringify({ - userId: session.userId, - deviceId: session.deviceId, - timestamp: Date.now() - })); - + localStorage.setItem( + 'cinny_fix_key_conflict', + JSON.stringify({ + userId: session.userId, + deviceId: session.deviceId, + timestamp: Date.now(), + }), + ); + // Restore console methods console.error = originalError; console.warn = originalWarn; - + // Notify user and reload setTimeout(() => { - if (confirm('Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?')) { + if ( + confirm( + 'Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?', + ) + ) { deleteRustCryptoDatabase(session).then(() => { window.location.reload(); }); @@ -170,7 +178,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { } originalError.apply(console, args); }; - + console.error = errorHandler; console.warn = (...args: any[]) => { if (checkKeyConflict(args)) { @@ -182,7 +190,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { export const initClient = async (session: Session): Promise => { const storeName = getSessionStoreName(session); - + // Check if we need to fix a key conflict from a previous session const pendingFix = localStorage.getItem('cinny_fix_key_conflict'); if (pendingFix) { @@ -198,7 +206,7 @@ export const initClient = async (session: Session): Promise => { localStorage.removeItem('cinny_fix_key_conflict'); } } - + console.log('[initMatrix] ========================================'); console.log('[initMatrix] Initializing Matrix client for session:'); console.log('[initMatrix] User ID:', session.userId); @@ -207,9 +215,9 @@ export const initClient = async (session: Session): Promise => { console.log('[initMatrix] Sync store name:', storeName.sync); console.log('[initMatrix] Crypto store name:', storeName.crypto); console.log('[initMatrix] ========================================'); - + console.log('[initMatrix] Creating Matrix client...'); - + try { const indexedDBStore = new IndexedDBStore({ indexedDB: global.indexedDB, @@ -232,10 +240,13 @@ export const initClient = async (session: Session): Promise => { }); await indexedDBStore.startup(); - + // Initialize Rust crypto with a unique store prefix for this account // This ensures each account has its own isolated crypto database - console.log('[initMatrix] Initializing Rust crypto with prefix:', `${session.userId}@${session.deviceId}`); + console.log( + '[initMatrix] Initializing Rust crypto with prefix:', + `${session.userId}@${session.deviceId}`, + ); await mx.initRustCrypto({ storagePrefix: `${session.userId}@${session.deviceId}`, }); @@ -243,7 +254,7 @@ export const initClient = async (session: Session): Promise => { console.log('[initMatrix] ✅ Client initialized successfully!'); mx.setMaxListeners(50); - + // Increase max listeners for User objects to prevent warnings when many components // subscribe to presence events (e.g., in member lists) const originalGetUser = mx.getUser.bind(mx); @@ -270,16 +281,16 @@ export const initClient = async (session: Session): Promise => { console.error('[initMatrix] ❌ Crypto store account mismatch detected!'); console.error('[initMatrix] Error details:', error.message); console.error('[initMatrix] Expected account:', session.userId, session.deviceId); - + // This shouldn't happen anymore since we delete the shared db before init // If it does happen, it means there's a different issue throw new Error( `❌ Crypto store conflict detected.\n\n` + - `This account's crypto store contains data from a different account.\n` + - `Please clear site data in DevTools (F12 → Application → Storage → Clear site data)` + `This account's crypto store contains data from a different account.\n` + + `Please clear site data in DevTools (F12 → Application → Storage → Clear site data)`, ); } - + // Re-throw other errors throw error; } @@ -306,29 +317,28 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { export const fixKeyConflict = async (mx: MatrixClient): Promise => { const userId = mx.getSafeUserId(); const deviceId = mx.getDeviceId(); - + if (!userId || !deviceId) { console.error('[initMatrix] Cannot fix key conflict: missing userId or deviceId'); return; } - + console.log('[initMatrix] 🔧 Fixing key conflict for', userId, deviceId); - + // Stop the client first mx.stopClient(); - + // Delete the crypto databases const dbNames = await getAllIndexedDBNames(); const storagePrefix = `${userId}@${deviceId}`; - - const cryptoDbNames = dbNames.filter(name => - name.includes('matrix-sdk-crypto') || - name.includes(storagePrefix) || - name.includes('crypto') + + const cryptoDbNames = dbNames.filter( + (name) => + name.includes('matrix-sdk-crypto') || name.includes(storagePrefix) || name.includes('crypto'), ); - + console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - + for (const dbName of cryptoDbNames) { try { await deleteIndexedDB(dbName); @@ -337,7 +347,7 @@ export const fixKeyConflict = async (mx: MatrixClient): Promise => { console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error); } } - + // Reload the page console.log('[initMatrix] 🔄 Reloading...'); window.location.reload(); @@ -345,30 +355,32 @@ export const fixKeyConflict = async (mx: MatrixClient): Promise => { export const logoutClient = async (mx: MatrixClient) => { mx.stopClient(); - + // Clear the global MatrixClient reference const { setGlobalMatrixClient } = await import('../app/utils/auth'); setGlobalMatrixClient(null); - + try { await mx.logout(); } catch { // ignore if failed to logout } await mx.clearStores(); - - // Import sessions management - const { sessionsAtom, currentSessionAtom, getSessionByUserId, getCurrentSession } = await import('../app/state/sessions'); - const { getLocalStorageItem, setLocalStorageItem } = await import('../app/state/utils/atomWithLocalStorage'); - + + // Import sessions management + const { sessionsAtom, currentSessionAtom, getSessionByUserId, getCurrentSession } = + await import('../app/state/sessions'); + const { getLocalStorageItem, setLocalStorageItem } = + await import('../app/state/utils/atomWithLocalStorage'); + const userId = mx.getSafeUserId(); const allSessions = getLocalStorageItem('matrixSessions', []); const currentUserId = getLocalStorageItem('currentSessionUserId', undefined); - + // Remove the current session const remainingSessions = allSessions.filter((s: any) => s.userId !== userId); setLocalStorageItem('matrixSessions', remainingSessions); - + // If we're logging out the current session and there are other sessions, switch to the first one if (remainingSessions.length > 0 && currentUserId === userId) { setLocalStorageItem('currentSessionUserId', remainingSessions[0].userId); @@ -385,7 +397,7 @@ export const logoutClient = async (mx: MatrixClient) => { export const logoutAllSessions = async () => { window.localStorage.clear(); - + // Clear all IndexedDB databases const dbs = await window.indexedDB.databases(); for (const idbInfo of dbs) { @@ -393,7 +405,7 @@ export const logoutAllSessions = async () => { window.indexedDB.deleteDatabase(idbInfo.name); } } - + window.location.reload(); }; diff --git a/src/colors.css.ts b/src/colors.css.ts index 86e808bf..e687f5aa 100644 --- a/src/colors.css.ts +++ b/src/colors.css.ts @@ -917,4 +917,3 @@ export const stationeryDarkTheme = createTheme(color, { Overlay: 'rgba(0, 0, 0, 0.8)', }, }); - diff --git a/src/ext.d.ts b/src/ext.d.ts index 237c58cb..31f6dc36 100644 --- a/src/ext.d.ts +++ b/src/ext.d.ts @@ -25,7 +25,7 @@ declare module 'browser-encrypt-attachment' { export function decryptAttachment( dataBuffer: ArrayBuffer, - info: EncryptedAttachmentInfo + info: EncryptedAttachmentInfo, ): Promise; } @@ -39,7 +39,7 @@ interface PluginAPI { download: ( pluginId: string, downloadUrl: string, - name: string + name: string, ) => Promise<{ success: boolean; data?: { path: string }; error?: string }>; list: () => Promise<{ success: boolean; @@ -47,7 +47,9 @@ interface PluginAPI { error?: string; }>; uninstall: (pluginId: string) => Promise<{ success: boolean; error?: string }>; - readPluginCode: (pluginId: string) => Promise<{ success: boolean; data?: string; error?: string }>; + readPluginCode: ( + pluginId: string, + ) => Promise<{ success: boolean; data?: string; error?: string }>; } interface ElectronAPI { @@ -57,11 +59,7 @@ interface ElectronAPI { writeText: (text: string) => void; }; media?: { - saveFile: (payload: { - filename: string; - mimeType?: string; - data: Uint8Array; - }) => Promise<{ + saveFile: (payload: { filename: string; mimeType?: string; data: Uint8Array }) => Promise<{ success?: boolean; canceled?: boolean; path?: string; @@ -108,10 +106,9 @@ interface ElectronAPI { }>; }; updater?: { - onUpdateDownloaded: (callback: (info: { - version: string; - releaseNotes?: unknown; - }) => void) => void; + onUpdateDownloaded: ( + callback: (info: { version: string; releaseNotes?: unknown }) => void, + ) => void; }; discordCollectibles?: { fetchCatalog: (force?: boolean) => Promise<{ @@ -119,7 +116,9 @@ interface ElectronAPI { data?: { items: unknown[]; fetchedAt: string }; error?: string; }>; - downloadAssets: (assets: Array<{ role: string; url: string; filename: string; mimeType: string }>) => Promise<{ + downloadAssets: ( + assets: Array<{ role: string; url: string; filename: string; mimeType: string }>, + ) => Promise<{ success: boolean; data?: Array<{ role: string; diff --git a/src/index.css b/src/index.css index ac87ab07..3684bc20 100644 --- a/src/index.css +++ b/src/index.css @@ -1,37 +1,36 @@ /* Twemoji font (Twitter emoji) — unicode-range keeps spaces/Latin out of emoji metrics */ @font-face { font-family: Twemoji; - src: url('../public/font/Twemoji.Mozilla.v15.1.0.woff2'), + src: + url('../public/font/Twemoji.Mozilla.v15.1.0.woff2'), url('../public/font/Twemoji.Mozilla.v15.1.0.ttf'); font-display: swap; - unicode-range: U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, - U+1FA70-1FAFF, U+1FAB0-1FABF, U+1FAC0-1FAFF; + unicode-range: + U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, U+1FA70-1FAFF, + U+1FAB0-1FABF, U+1FAC0-1FAFF; } /* Apple Color Emoji - uses local Apple Color Emoji if available (macOS/iOS), falls back to Segoe UI Emoji (Windows) or Noto (Linux/Android) */ @font-face { font-family: AppleColorEmoji; - src: local('Apple Color Emoji'), - local('Segoe UI Emoji'), - local('Noto Color Emoji'); + src: local('Apple Color Emoji'), local('Segoe UI Emoji'), local('Noto Color Emoji'); font-display: swap; - unicode-range: U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, - U+1FA70-1FAFF, U+1FAB0-1FABF, U+1FAC0-1FAFF; + unicode-range: + U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, U+1FA70-1FAFF, + U+1FAB0-1FABF, U+1FAC0-1FAFF; } /* System emoji - uses native OS emoji */ @font-face { font-family: SystemEmoji; - src: local('Apple Color Emoji'), - local('Segoe UI Emoji'), - local('Segoe UI Symbol'), - local('Noto Color Emoji'), - local('Android Emoji'), - local('EmojiOne Color'); + src: + local('Apple Color Emoji'), local('Segoe UI Emoji'), local('Segoe UI Symbol'), + local('Noto Color Emoji'), local('Android Emoji'), local('EmojiOne Color'); font-display: swap; - unicode-range: U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, - U+1FA70-1FAFF, U+1FAB0-1FABF, U+1FAC0-1FAFF; + unicode-range: + U+1F300-1F9FF, U+2600-26FF, U+2700-27BF, U+FE0F, U+200D, U+1F1E6-1F1FF, U+1FA70-1FAFF, + U+1FAB0-1FABF, U+1FAC0-1FAFF; } :root { @@ -104,37 +103,50 @@ body { } /* Prevent zalgo text and combining diacritics from overflowing line boundaries */ -p, span, div, a, button, li, td, th, h1, h2, h3, h4, h5, h6 { +p, +span, +div, +a, +button, +li, +td, +th, +h1, +h2, +h3, +h4, +h5, +h6 { line-height: 1.5; } /* Theme-specific body backgrounds for safe area padding */ body.light-theme { - background-color: #F0F0F0; + background-color: #f0f0f0; } body.silver-theme { - background-color: #DEDEDE; + background-color: #dedede; } body.dark-theme { background-color: #262626; } body.butter-theme { - background-color: #1A1916; + background-color: #1a1916; } body.discord-theme { - background-color: #2B2D31; + background-color: #2b2d31; } body.discord-darker-theme { - background-color: #1E1F22; + background-color: #1e1f22; } body.twilight-theme { - background: linear-gradient(135deg, #14121F 0%, #1C1A2E 50%, #24223D 100%); + background: linear-gradient(135deg, #14121f 0%, #1c1a2e 50%, #24223d 100%); } body.mocha-theme { - background: linear-gradient(135deg, #1A1614 0%, #242019 50%, #2D2721 100%); + background: linear-gradient(135deg, #1a1614 0%, #242019 50%, #2d2721 100%); } body.stationery-theme { - background-color: #D9D0C0; + background-color: #d9d0c0; } body.stationery-dark-theme { background-color: #11111b; @@ -177,7 +189,7 @@ body.stationery-dark-theme { } /* Twilight theme gradient overlays */ -.twilight-theme [role="navigation"], +.twilight-theme [role='navigation'], .twilight-theme aside { background: linear-gradient(180deg, rgba(20, 18, 31, 0.8) 0%, rgba(28, 26, 46, 0.9) 100%); backdrop-filter: blur(8px); @@ -213,12 +225,12 @@ body.stationery-dark-theme { } /* Apply transition to route changes - works on ALL themes */ -[data-route-transition="true"] { +[data-route-transition='true'] { animation: fadeSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1); } /* Twilight theme enhanced transitions */ -.twilight-theme [data-route-transition="true"] { +.twilight-theme [data-route-transition='true'] { animation: fadeSlideIn 0.35s cubic-bezier(0.4, 0, 0.2, 1); } @@ -232,26 +244,31 @@ body.stationery-dark-theme { /* Smooth transitions for interactive elements */ .twilight-theme button, -.twilight-theme [role="button"], +.twilight-theme [role='button'], .twilight-theme a, .twilight-theme input, .twilight-theme textarea { - transition: background-color 0.2s ease, color 0.2s ease, transform 0.15s ease; + transition: + background-color 0.2s ease, + color 0.2s ease, + transform 0.15s ease; } .twilight-theme button:hover, -.twilight-theme [role="button"]:hover { +.twilight-theme [role='button']:hover { transform: translateY(-1px); } .twilight-theme button:active, -.twilight-theme [role="button"]:active { +.twilight-theme [role='button']:active { transform: translateY(0); } /* Message transitions */ .twilight-theme [data-message-item] { - transition: background-color 0.2s ease, transform 0.2s ease; + transition: + background-color 0.2s ease, + transform 0.2s ease; } .twilight-theme [data-message-item]:hover { @@ -260,23 +277,23 @@ body.stationery-dark-theme { } /* Selected item indicator */ -.twilight-theme [data-selected="true"], -.twilight-theme [aria-selected="true"], -.twilight-theme [aria-current="true"] { +.twilight-theme [data-selected='true'], +.twilight-theme [aria-selected='true'], +.twilight-theme [aria-current='true'] { position: relative; transition: all 0.2s ease; } -.twilight-theme [data-selected="true"]::before, -.twilight-theme [aria-selected="true"]::before, -.twilight-theme [aria-current="true"]::before { +.twilight-theme [data-selected='true']::before, +.twilight-theme [aria-selected='true']::before, +.twilight-theme [aria-current='true']::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; - background: linear-gradient(180deg, #8B7FFF 0%, #6E62E8 100%); + background: linear-gradient(180deg, #8b7fff 0%, #6e62e8 100%); transition: width 0.2s ease; } @@ -296,7 +313,9 @@ body.stationery-dark-theme { border-radius: 5px; border: 2px solid transparent; background-clip: padding-box; - transition: background 0.2s ease, border-color 0.2s ease; + transition: + background 0.2s ease, + border-color 0.2s ease; } .twilight-theme *:hover::-webkit-scrollbar-track { @@ -304,16 +323,16 @@ body.stationery-dark-theme { } .twilight-theme *:hover::-webkit-scrollbar-thumb { - background: linear-gradient(180deg, #3E3A6A 0%, #565096 100%); + background: linear-gradient(180deg, #3e3a6a 0%, #565096 100%); border-color: rgba(20, 18, 31, 0.5); } .twilight-theme *:hover::-webkit-scrollbar-thumb:hover { - background: linear-gradient(180deg, #4A4580 0%, #625BAC 100%); + background: linear-gradient(180deg, #4a4580 0%, #625bac 100%); } /* Mocha theme gradient overlays */ -.mocha-theme [role="navigation"], +.mocha-theme [role='navigation'], .mocha-theme aside { background: linear-gradient(180deg, rgba(26, 22, 20, 0.8) 0%, rgba(36, 32, 25, 0.9) 100%); backdrop-filter: blur(8px); @@ -328,7 +347,7 @@ body.stationery-dark-theme { } /* Mocha theme enhanced transitions */ -.mocha-theme [data-route-transition="true"] { +.mocha-theme [data-route-transition='true'] { animation: fadeSlideIn 0.35s cubic-bezier(0.4, 0, 0.2, 1); } @@ -341,26 +360,31 @@ body.stationery-dark-theme { /* Smooth transitions for interactive elements */ .mocha-theme button, -.mocha-theme [role="button"], +.mocha-theme [role='button'], .mocha-theme a, .mocha-theme input, .mocha-theme textarea { - transition: background-color 0.2s ease, color 0.2s ease, transform 0.15s ease; + transition: + background-color 0.2s ease, + color 0.2s ease, + transform 0.15s ease; } .mocha-theme button:hover, -.mocha-theme [role="button"]:hover { +.mocha-theme [role='button']:hover { transform: translateY(-1px); } .mocha-theme button:active, -.mocha-theme [role="button"]:active { +.mocha-theme [role='button']:active { transform: translateY(0); } /* Message transitions */ .mocha-theme [data-message-item] { - transition: background-color 0.2s ease, transform 0.2s ease; + transition: + background-color 0.2s ease, + transform 0.2s ease; } .mocha-theme [data-message-item]:hover { @@ -369,23 +393,23 @@ body.stationery-dark-theme { } /* Selected item indicator */ -.mocha-theme [data-selected="true"], -.mocha-theme [aria-selected="true"], -.mocha-theme [aria-current="true"] { +.mocha-theme [data-selected='true'], +.mocha-theme [aria-selected='true'], +.mocha-theme [aria-current='true'] { position: relative; transition: all 0.2s ease; } -.mocha-theme [data-selected="true"]::before, -.mocha-theme [aria-selected="true"]::before, -.mocha-theme [aria-current="true"]::before { +.mocha-theme [data-selected='true']::before, +.mocha-theme [aria-selected='true']::before, +.mocha-theme [aria-current='true']::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; - background: linear-gradient(180deg, #D4A574 0%, #B48660 100%); + background: linear-gradient(180deg, #d4a574 0%, #b48660 100%); transition: width 0.2s ease; } @@ -404,7 +428,9 @@ body.stationery-dark-theme { border-radius: 5px; border: 2px solid transparent; background-clip: padding-box; - transition: background 0.2s ease, border-color 0.2s ease; + transition: + background 0.2s ease, + border-color 0.2s ease; } .mocha-theme *:hover::-webkit-scrollbar-track { @@ -412,12 +438,12 @@ body.stationery-dark-theme { } .mocha-theme *:hover::-webkit-scrollbar-thumb { - background: linear-gradient(180deg, #54493F 0%, #706151 100%); + background: linear-gradient(180deg, #54493f 0%, #706151 100%); border-color: rgba(26, 22, 20, 0.5); } .mocha-theme *:hover::-webkit-scrollbar-thumb:hover { - background: linear-gradient(180deg, #625548 0%, #7E6D5A 100%); + background: linear-gradient(180deg, #625548 0%, #7e6d5a 100%); } /* Subtle dot pattern overlay */ @@ -749,15 +775,10 @@ body.stationery-dark-theme { } .stationery [data-reaction][aria-pressed='true'] [data-reaction-sticker] { - filter: - drop-shadow(0 0 0.6px var(--glow-rim)) - drop-shadow(0 0 1.2px var(--glow-rim)) - drop-shadow(0 0 2px var(--glow-rim)) - drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) - drop-shadow(-1px -1px 0 var(--glow-rim-faint)) - drop-shadow(1px 2px 0 var(--cast-shadow)) - drop-shadow(2px 3px 3px var(--cast-shadow-strong)) - drop-shadow(0 0 3px var(--glow-accent)); + filter: drop-shadow(0 0 0.6px var(--glow-rim)) drop-shadow(0 0 1.2px var(--glow-rim)) + drop-shadow(0 0 2px var(--glow-rim)) drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) + drop-shadow(-1px -1px 0 var(--glow-rim-faint)) drop-shadow(1px 2px 0 var(--cast-shadow)) + drop-shadow(2px 3px 3px var(--cast-shadow-strong)) drop-shadow(0 0 3px var(--glow-accent)); } .stationery [data-reaction-stack-layer] { @@ -772,19 +793,12 @@ body.stationery-dark-theme { line-height: 1 !important; max-width: none !important; /* Same white sticker outline + bevel as jumbo emoji */ - filter: - drop-shadow(0 0 0.6px var(--glow-rim)) - drop-shadow(0 0 1.2px var(--glow-rim)) - drop-shadow(0 0 2px var(--glow-rim)) - drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) - drop-shadow(-1px -1px 0 var(--glow-rim-faint)) - drop-shadow(1px 2px 0 var(--cast-shadow)) + filter: drop-shadow(0 0 0.6px var(--glow-rim)) drop-shadow(0 0 1.2px var(--glow-rim)) + drop-shadow(0 0 2px var(--glow-rim)) drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) + drop-shadow(-1px -1px 0 var(--glow-rim-faint)) drop-shadow(1px 2px 0 var(--cast-shadow)) drop-shadow(2px 3px 3px var(--cast-shadow-strong)); /* Clearer multi-sticker fan */ - transform: translate( - calc(var(--sticker-i, 0) * 8px - 2px), - calc(var(--sticker-i, 0) * -6px) - ) + transform: translate(calc(var(--sticker-i, 0) * 8px - 2px), calc(var(--sticker-i, 0) * -6px)) rotate(calc((var(--sticker-i, 0) - 1) * 14deg)) !important; } @@ -842,13 +856,9 @@ body.stationery-dark-theme { .stationery [data-jumbo-emoji] span span { border-radius: 8px; /* White sticker outline + soft bevel / lift */ - filter: - drop-shadow(0 0 0.6px var(--glow-rim)) - drop-shadow(0 0 1.2px var(--glow-rim)) - drop-shadow(0 0 2px var(--glow-rim)) - drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) - drop-shadow(-1px -1px 0 var(--glow-rim-faint)) - drop-shadow(1px 2px 0 var(--cast-shadow)) + filter: drop-shadow(0 0 0.6px var(--glow-rim)) drop-shadow(0 0 1.2px var(--glow-rim)) + drop-shadow(0 0 2px var(--glow-rim)) drop-shadow(0.5px 0.5px 0 var(--glow-rim-soft)) + drop-shadow(-1px -1px 0 var(--glow-rim-faint)) drop-shadow(1px 2px 0 var(--cast-shadow)) drop-shadow(2px 3px 3px var(--cast-shadow-strong)); transform: rotate(-5deg); transform-origin: center center; @@ -1083,7 +1093,9 @@ body.stationery-dark-theme { border: none !important; /* Sit past the manila bar edge into the room-list gutter */ transform: rotate(var(--postit-rot)) translateX(16px); - transition: transform 0.18s ease, box-shadow 0.18s ease; + transition: + transform 0.18s ease, + box-shadow 0.18s ease; z-index: 21; } @@ -1365,7 +1377,9 @@ body.stationery-dark-theme { outline: none !important; transform: rotate(var(--postit-rot)); transform-origin: 50% center; - transition: transform 0.15s ease, box-shadow 0.15s ease !important; + transition: + transform 0.15s ease, + box-shadow 0.15s ease !important; overflow: hidden !important; } @@ -1516,7 +1530,10 @@ body.stationery-dark-theme { margin: 0 2px !important; } -.stationery [data-page-nav] [data-nav-category]:not([data-nav-rooms]) > [data-nav-item][aria-selected='true'] { +.stationery + [data-page-nav] + [data-nav-category]:not([data-nav-rooms]) + > [data-nav-item][aria-selected='true'] { background: var(--sleeve-paper-soft) !important; box-shadow: inset 3px 0 0 var(--message-hover-edge) !important; } @@ -1527,7 +1544,9 @@ body.stationery-dark-theme { } .stationery [data-message-item] { - transition: background-color 0.2s ease, box-shadow 0.2s ease; + transition: + background-color 0.2s ease, + box-shadow 0.2s ease; border-radius: 2px; /* Keep overflowing tape/peel inside this message's paint layer */ isolation: isolate; @@ -1552,7 +1571,9 @@ body.stationery-dark-theme { 2px 4px 8px var(--cast-shadow-mid), 4px 10px 20px var(--cast-shadow), 0 0 0 3px var(--media-mat) !important; - transition: transform 0.25s ease, box-shadow 0.25s ease; + transition: + transform 0.25s ease, + box-shadow 0.25s ease; isolation: isolate; overflow-anchor: none; perspective: 520px; @@ -1578,12 +1599,7 @@ body.stationery-dark-theme { height: 16px; /* Mid-weight film — readable ink, still reads as tape */ background: - linear-gradient( - 105deg, - var(--tape-fill-a) 0%, - var(--tape-fill-b) 45%, - var(--tape-fill-c) 100% - ), + linear-gradient(105deg, var(--tape-fill-a) 0%, var(--tape-fill-b) 45%, var(--tape-fill-c) 100%), var(--tape-base); border: 1px solid var(--tape-border); box-shadow: @@ -1642,12 +1658,7 @@ body.stationery-dark-theme { transition: none; transform-style: preserve-3d; /* Pivot on fold midpoint; axis along the fold edge */ - transform: rotate3d( - var(--peel-axis-x, 1), - var(--peel-axis-y, 0), - 0, - var(--peel-hinge, 0deg) - ); + transform: rotate3d(var(--peel-axis-x, 1), var(--peel-axis-y, 0), 0, var(--peel-hinge, 0deg)); filter: drop-shadow(1px 2px 4px var(--cast-shadow-strong)); backface-visibility: hidden; } @@ -1676,7 +1687,6 @@ body.stationery-dark-theme { /* Don't raise above neighboring messages (tape was covering them) */ } - .stationery [data-message-item] [data-mx-spoiler], .stationery code { background: var(--code-mark); @@ -1850,7 +1860,6 @@ body.stationery-dark-theme { background-attachment: local; } - /* Dark stationery — Catppuccin Mocha */ .stationery-dark-theme { --stationery-ink: #cdd6f4; @@ -1930,7 +1939,6 @@ body.stationery-dark-theme { --mx-uc-8: #a6e3a1; } - *, *::before, *::after { diff --git a/src/index.tsx b/src/index.tsx index 0c3e53c8..6af9abe9 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -49,8 +49,8 @@ if ('serviceWorker' in navigator) { const { getCurrentAccessToken: getToken } = await import('./app/utils/auth'); return getToken(); }; - - getCurrentAccessToken().then(token => { + + getCurrentAccessToken().then((token) => { event.source!.postMessage({ responseKey: event.data.responseKey, token, @@ -96,7 +96,7 @@ async function checkForUpdates() { console.log(`Update available: ${update.version}`); const shouldUpdate = await ask( `A new version (${update.version}) is available. Would you like to update now?`, - { title: 'Update Available', kind: 'info' } + { title: 'Update Available', kind: 'info' }, ); if (shouldUpdate) { console.log('User chose to update, downloading...'); diff --git a/src/playground/App.tsx b/src/playground/App.tsx index 6d9a4b51..a37ca7f8 100644 --- a/src/playground/App.tsx +++ b/src/playground/App.tsx @@ -121,13 +121,11 @@ export function App() { const liveReady = matrix.mode === 'live' && matrix.status === 'ready' && matrix.client; const previewClient = liveReady ? matrix.client! : undefined; - const previewRoom = liveReady ? matrix.room ?? undefined : undefined; + const previewRoom = liveReady ? (matrix.room ?? undefined) : undefined; const editorValue = editorTab === 'component' ? componentSource : harnessSource; const editorPath = - editorTab === 'component' && selected - ? selected.filePath - : 'playground-live.tsx'; + editorTab === 'component' && selected ? selected.filePath : 'playground-live.tsx'; return (
@@ -179,11 +177,7 @@ export function App() { > {matrix.status === 'connecting' ? 'Connecting…' : 'Paarrot session'} -
@@ -200,7 +194,9 @@ export function App() { {matrix.error} )} {!matrix.hasPaarrotSession && matrix.mode !== 'live' && ( - Tip: log into Paarrot at / first, then hit Paarrot session + + Tip: log into Paarrot at / first, then hit Paarrot session + )}
diff --git a/src/playground/LivePreview.tsx b/src/playground/LivePreview.tsx index 7a8d7a4a..b5e2ec3f 100644 --- a/src/playground/LivePreview.tsx +++ b/src/playground/LivePreview.tsx @@ -41,10 +41,7 @@ export function LivePreview() { }) .catch((err: unknown) => { if (cancelled) return; - const message = - err instanceof Error - ? `${err.message}\n\n${err.stack ?? ''}` - : String(err); + const message = err instanceof Error ? `${err.message}\n\n${err.stack ?? ''}` : String(err); setError(message); }); diff --git a/src/playground/ResizableStage.tsx b/src/playground/ResizableStage.tsx index 4cc36f8b..22b9a911 100644 --- a/src/playground/ResizableStage.tsx +++ b/src/playground/ResizableStage.tsx @@ -23,8 +23,8 @@ export function ResizableStage({ children }: Props) { const dx = e.clientX - drag.startX; const dy = e.clientY - drag.startY; setSize((prev) => { - let width = prev.width; - let height = prev.height; + let { width } = prev; + let { height } = prev; if (drag.edge === 'e' || drag.edge === 'se') { width = clamp(drag.startW + dx, MIN, MAX); } @@ -68,8 +68,18 @@ export function ResizableStage({ children }: Props) {
{children}
-