diff --git a/config.json b/config.json index 1bdffb67..f0c3c8b6 100644 --- a/config.json +++ b/config.json @@ -13,6 +13,8 @@ "webPushAppID": "moe.sable.app.sygnal" }, + "settingsLinkBaseUrl": "https://app.sable.moe", + "slidingSync": { "enabled": true }, diff --git a/src/app/components/Modal500.test.tsx b/src/app/components/Modal500.test.tsx new file mode 100644 index 00000000..2a6386ff --- /dev/null +++ b/src/app/components/Modal500.test.tsx @@ -0,0 +1,15 @@ +import { render } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { Modal500 } from './Modal500'; + +describe('Modal500', () => { + it('does not throw when rendered without tabbable children', () => { + expect(() => + render( + +
Empty modal content
+
+ ) + ).not.toThrow(); + }); +}); diff --git a/src/app/components/Modal500.tsx b/src/app/components/Modal500.tsx index 260baa6d..fc75b8a1 100644 --- a/src/app/components/Modal500.tsx +++ b/src/app/components/Modal500.tsx @@ -1,4 +1,4 @@ -import { ReactNode } from 'react'; +import { ReactNode, useRef } from 'react'; import FocusTrap from 'focus-trap-react'; import { Modal, Overlay, OverlayBackdrop, OverlayCenter } from 'folds'; import { stopPropagation } from '$utils/keyboard'; @@ -8,18 +8,21 @@ type Modal500Props = { children: ReactNode; }; export function Modal500({ requestClose, children }: Modal500Props) { + const modalRef = useRef(null); + return ( }> modalRef.current ?? document.body, clickOutsideDeactivates: true, onDeactivate: requestClose, escapeDeactivates: stopPropagation, }} > - + {children} diff --git a/src/app/components/RenderMessageContent.test.tsx b/src/app/components/RenderMessageContent.test.tsx new file mode 100644 index 00000000..ffacb90a --- /dev/null +++ b/src/app/components/RenderMessageContent.test.tsx @@ -0,0 +1,48 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { MsgType } from '$types/matrix-sdk'; +import { ClientConfigProvider } from '$hooks/useClientConfig'; +import { RenderMessageContent } from './RenderMessageContent'; + +vi.mock('./url-preview', () => ({ + UrlPreviewHolder: ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ), + UrlPreviewCard: ({ url }: { url: string }) =>
{url}
, + ClientPreview: ({ url }: { url: string }) =>
{url}
, + youtubeUrl: () => false, +})); + +function renderMessage(body: string, settingsLinkBaseUrl = 'https://app.sable.moe') { + return render( + + ({ body }) as never} + urlPreview + clientUrlPreview + htmlReactParserOptions={{}} + linkifyOpts={{}} + /> + + ); +} + +describe('RenderMessageContent', () => { + it('does not render url previews for settings permalinks', () => { + renderMessage('https://app.sable.moe/settings/account/?focus=status'); + + expect(screen.queryByTestId('url-preview-holder')).not.toBeInTheDocument(); + expect(screen.queryByTestId('url-preview-card')).not.toBeInTheDocument(); + expect(screen.queryByTestId('client-preview')).not.toBeInTheDocument(); + }); + + it('still renders url previews for non-settings links', () => { + renderMessage('https://example.com'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); + }); +}); diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 6f361785..245a7e3f 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -1,5 +1,7 @@ import { memo, useMemo, useCallback } from 'react'; import { MsgType } from '$types/matrix-sdk'; +import { parseSettingsPermalink } from '$features/settings/settingsLink'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { testMatrixTo } from '$plugins/matrix-to'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, CaptionPosition } from '$state/settings'; @@ -80,6 +82,7 @@ function RenderMessageContentInternal({ const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); const [captionPosition] = useSetting(settingsAtom, 'captionPosition'); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const captionPositionMap = { [CaptionPosition.Above]: 'column-reverse', [CaptionPosition.Below]: 'column', @@ -101,7 +104,9 @@ function RenderMessageContentInternal({ const renderUrlsPreview = useCallback( (urls: string[]) => { - const filteredUrls = urls.filter((url) => !testMatrixTo(url)); + const filteredUrls = urls.filter( + (url) => !testMatrixTo(url) && !parseSettingsPermalink(settingsLinkBaseUrl, url) + ); if (filteredUrls.length === 0) return undefined; const analyzed = filteredUrls.map((url) => ({ @@ -129,7 +134,7 @@ function RenderMessageContentInternal({ ); }, - [ts, clientUrlPreview, urlPreview] + [ts, clientUrlPreview, settingsLinkBaseUrl, urlPreview] ); const renderCaption = () => { diff --git a/src/app/components/event-history/EventHistory.tsx b/src/app/components/event-history/EventHistory.tsx index 955a2846..f08fd6c0 100644 --- a/src/app/components/event-history/EventHistory.tsx +++ b/src/app/components/event-history/EventHistory.tsx @@ -39,6 +39,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { MessageEvent } from '$types/matrix/room'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import * as css from './EventHistory.css'; export type EventHistoryProps = { @@ -50,6 +51,7 @@ export const EventHistory = as<'div', EventHistoryProps>( ({ className, room, mEvents, requestClose, ...props }, ref) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const openProfile = useOpenUserRoomProfile(); const space = useSpaceOptionally(); const nicknames = useAtomValue(nicknamesAtom); @@ -72,11 +74,12 @@ export const EventHistory = as<'div', EventHistoryProps>( const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, mEvents[0].getRoomId(), { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, }), - [linkifyOpts, mEvents, mx, spoilerClickHandler, useAuthentication] + [linkifyOpts, mEvents, mx, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication] ); const powerLevels = usePowerLevelsContext(); const creators = useRoomCreators(room); diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 3342b0d5..23844cbb 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -27,6 +27,7 @@ import { StateEvent, MessageEvent } from '$types/matrix/room'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; import { useTranslation } from 'react-i18next'; import * as customHtmlCss from '$styles/CustomHtml.css'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { MessageBadEncryptedContent, MessageBlockedContent, @@ -120,6 +121,7 @@ export const Reply = as<'div', ReplyProps>( const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); const nicknames = useAtomValue(nicknamesAtom); const useAuthentication = useMediaAuthentication(); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const fallbackBody = isRedacted ? : ; @@ -144,17 +146,20 @@ export const Reply = as<'div', ReplyProps>( const replyLinkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room.roomId, mentionClickHandler, nicknames] + [mx, room.roomId, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); if (format === 'org.matrix.custom.html' && formattedBody) { @@ -166,6 +171,7 @@ export const Reply = as<'div', ReplyProps>( .replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '') .replaceAll(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts: replyLinkifyOpts, useAuthentication, nicknames, diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index 9928f15e..ee423ca2 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -58,11 +58,14 @@ const highlightAnime = keyframes({ backgroundColor: color.Primary.Container, }, }); + +export const messageJumpHighlight = style({ + animation: `${highlightAnime} 2000ms ease-in-out`, + animationIterationCount: 'infinite', +}); + const HighlightVariant = styleVariants({ - true: { - animation: `${highlightAnime} 2000ms ease-in-out`, - animationIterationCount: 'infinite', - }, + true: [messageJumpHighlight], }); const NotifyHighlightVariant = styleVariants({ diff --git a/src/app/components/sequence-card/SequenceCard.tsx b/src/app/components/sequence-card/SequenceCard.tsx index 7738d93f..810afd3d 100644 --- a/src/app/components/sequence-card/SequenceCard.tsx +++ b/src/app/components/sequence-card/SequenceCard.tsx @@ -29,6 +29,7 @@ export const SequenceCard = as< ContainerColor({ variant }), className )} + data-sequence-card="true" data-first-child={firstChild} data-last-child={lastChild} {...props} diff --git a/src/app/components/setting-tile/SettingTile.css.ts b/src/app/components/setting-tile/SettingTile.css.ts new file mode 100644 index 00000000..34f70790 --- /dev/null +++ b/src/app/components/setting-tile/SettingTile.css.ts @@ -0,0 +1,54 @@ +import { style } from '@vanilla-extract/css'; +import { config } from 'folds'; + +export const settingTileRoot = style({ + minWidth: 0, +}); + +export const settingTileTitleRow = style({ + minWidth: 0, +}); + +const permalinkActionBase = style({ + transition: + 'opacity 150ms ease, transform 150ms ease, color 150ms ease, background-color 150ms ease', +}); + +export const settingTilePermalinkAction = style([ + permalinkActionBase, + { + minWidth: 0, + minHeight: 0, + width: 'auto', + height: 'auto', + padding: 0, + }, +]); + +export const settingTilePermalinkActionDesktopHidden = style([ + permalinkActionBase, + { + opacity: 0, + pointerEvents: 'none', + transform: `translateX(${config.space.S100})`, + selectors: { + [`${settingTileRoot}:hover &`]: { + opacity: 1, + transform: 'translateX(0)', + pointerEvents: 'auto', + }, + [`${settingTileRoot}:focus-within &`]: { + opacity: 1, + transform: 'translateX(0)', + pointerEvents: 'auto', + }, + }, + }, +]); + +export const settingTilePermalinkActionMobileVisible = style([ + permalinkActionBase, + { + opacity: 1, + }, +]); diff --git a/src/app/components/setting-tile/SettingTile.test.tsx b/src/app/components/setting-tile/SettingTile.test.tsx new file mode 100644 index 00000000..a21a59f7 --- /dev/null +++ b/src/app/components/setting-tile/SettingTile.test.tsx @@ -0,0 +1,97 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; +import { ClientConfigProvider } from '$hooks/useClientConfig'; +import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; +import { SettingsPermalinkProvider } from '$features/settings/SettingsPermalinkContext'; +import { SettingTile } from './SettingTile'; +import { + settingTilePermalinkActionDesktopHidden, + settingTilePermalinkActionMobileVisible, +} from './SettingTile.css'; + +const writeText = vi.fn(); + +function renderTile(screenSize: ScreenSize, focusId?: string) { + return render( + + + + + + + + ); +} + +beforeEach(() => { + writeText.mockReset(); + vi.stubGlobal('navigator', { clipboard: { writeText } } as unknown as Navigator); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('SettingTile', () => { + it('copies the real settings permalink when a focus id is present', async () => { + writeText.mockResolvedValueOnce(undefined); + + renderTile(ScreenSize.Desktop, 'message-link-preview'); + + fireEvent.click(screen.getByRole('button', { name: /copy settings permalink/i })); + + await waitFor(() => { + expect(writeText).toHaveBeenCalledWith( + 'https://settings.example/settings/appearance/?focus=message-link-preview' + ); + }); + expect(screen.getByRole('button', { name: /copied settings permalink/i })).toBeInTheDocument(); + }); + + it('keeps the copy state unchanged when clipboard write fails', async () => { + writeText.mockRejectedValueOnce(new Error('denied')); + + renderTile(ScreenSize.Desktop, 'message-link-preview'); + + fireEvent.click(screen.getByRole('button', { name: /copy settings permalink/i })); + + await waitFor(() => { + expect(writeText).toHaveBeenCalledWith( + 'https://settings.example/settings/appearance/?focus=message-link-preview' + ); + }); + expect(screen.getByRole('button', { name: /copy settings permalink/i })).toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: /copied settings permalink/i }) + ).not.toBeInTheDocument(); + }); + + it('does not render a copy button without a focus id', () => { + renderTile(ScreenSize.Desktop); + + expect( + screen.queryByRole('button', { name: /copy settings permalink/i }) + ).not.toBeInTheDocument(); + }); + + it('uses the desktop hidden-until-hover class for the permalink action', () => { + renderTile(ScreenSize.Desktop, 'message-link-preview'); + + expect(screen.getByText('Appearance').parentElement).toContainElement( + screen.getByRole('button', { name: /copy settings permalink/i }) + ); + expect(screen.getByRole('button', { name: /copy settings permalink/i })).toHaveClass( + settingTilePermalinkActionDesktopHidden + ); + }); + + it('uses the mobile always-visible class for the permalink action', () => { + renderTile(ScreenSize.Mobile, 'message-link-preview'); + + expect(screen.getByRole('button', { name: /copy settings permalink/i })).toHaveClass( + settingTilePermalinkActionMobileVisible + ); + }); +}); diff --git a/src/app/components/setting-tile/SettingTile.tsx b/src/app/components/setting-tile/SettingTile.tsx index 67548ece..33b6ce11 100644 --- a/src/app/components/setting-tile/SettingTile.tsx +++ b/src/app/components/setting-tile/SettingTile.tsx @@ -1,6 +1,19 @@ import { ReactNode } from 'react'; -import { Box, Text } from 'folds'; +import { Box, Icon, IconButton, Icons, Text } from 'folds'; import { BreakWord } from '$styles/Text.css'; +import { buildSettingsPermalink } from '$features/settings/settingsLink'; +import { copyToClipboard } from '$utils/dom'; +import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; +import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { useSettingsPermalinkContext } from '$features/settings/SettingsPermalinkContext'; +import { type SettingsSectionId } from '$features/settings/routes'; +import { + settingTilePermalinkAction, + settingTilePermalinkActionDesktopHidden, + settingTilePermalinkActionMobileVisible, + settingTileRoot, + settingTileTitleRow, +} from './SettingTile.css'; type SettingTileProps = { focusId?: string; @@ -11,6 +24,42 @@ type SettingTileProps = { after?: ReactNode; children?: ReactNode; }; + +function SettingTilePermalinkAction({ + baseUrl, + section, + focusId, +}: { + baseUrl: string; + section: SettingsSectionId; + focusId: string; +}) { + const screenSize = useScreenSizeContext(); + const [copied, setCopied] = useTimeoutToggle(); + const copyPath = buildSettingsPermalink(baseUrl, section, focusId); + + return ( + { + if (await copyToClipboard(copyPath)) setCopied(); + }} + size="300" + variant="Surface" + fill="None" + radii="Inherit" + > + + + ); +} + export function SettingTile({ focusId, className, @@ -20,20 +69,48 @@ export function SettingTile({ after, children, }: SettingTileProps) { + const settingsPermalink = useSettingsPermalinkContext(); + const copyAction = + settingsPermalink && focusId ? ( + + ) : null; + const titleAction = title ? copyAction : null; + const trailingCopyAction = title ? null : copyAction; + + const trailing = + after || trailingCopyAction ? ( + + {after} + {trailingCopyAction} + + ) : null; + return ( {before && {before}} {title && ( - - {title} - + + + {title} + + {titleAction} + )} {description && ( @@ -42,7 +119,7 @@ export function SettingTile({ )} {children} - {after && {after}} + {trailing} ); } diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index d9fa444f..d97a29f5 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -27,6 +27,7 @@ import { bytesToSize, getFileTypeIcon } from '$utils/common'; import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/roomInputDrafts'; import { useObjectURL } from '$hooks/useObjectURL'; import { useMediaConfig } from '$hooks/useMediaConfig'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard'; import * as css from './UploadCard.css'; import { DescriptionEditor } from './UploadDescriptionEditor'; @@ -383,14 +384,16 @@ export function UploadCardRenderer({ const spoilerClickHandler = useSpoilerClickHandler(); const useAuthentication = useMediaAuthentication(); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, roomId, { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, }), - [linkifyOpts, mx, roomId, spoilerClickHandler, useAuthentication] + [linkifyOpts, mx, roomId, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication] ); return ( ) => { e.preventDefault(); }, []); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room, mentionClickHandler, nicknames] + [mx, room, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); const spoilerClickHandler = useSpoilerClickHandler(); @@ -337,11 +342,12 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, }), - [mx, room, linkifyOpts, useAuthentication, spoilerClickHandler] + [mx, room, linkifyOpts, settingsLinkBaseUrl, useAuthentication, spoilerClickHandler] ); return ( diff --git a/src/app/features/message-search/SearchResultGroup.tsx b/src/app/features/message-search/SearchResultGroup.tsx index 7e4bcf53..c3450c6e 100644 --- a/src/app/features/message-search/SearchResultGroup.tsx +++ b/src/app/features/message-search/SearchResultGroup.tsx @@ -52,6 +52,7 @@ import { } from '$hooks/useMemberPowerTag'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomCreatorsTag } from '$hooks/useRoomCreatorsTag'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { ResultItem } from './useMessageSearch'; type SearchResultGroupProps = { @@ -90,6 +91,7 @@ export function SearchResultGroup({ const theme = useTheme(); const accessibleTagColors = useAccessiblePowerTagColors(theme.kind, creatorsTag, powerLevelTags); const nicknames = useAtomValue(nicknamesAtom); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const mentionClickHandler = useMentionClickHandler(room.roomId); const spoilerClickHandler = useSpoilerClickHandler(); @@ -97,21 +99,25 @@ export function SearchResultGroup({ const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room, mentionClickHandler, nicknames] + [mx, room, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, highlightRegex, useAuthentication, @@ -128,6 +134,7 @@ export function SearchResultGroup({ spoilerClickHandler, useAuthentication, nicknames, + settingsLinkBaseUrl, ] ); diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index dd655dee..e608f202 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -49,6 +49,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useSpaceOptionally } from '$hooks/useSpace'; @@ -177,6 +178,7 @@ export function RoomTimeline({ const mediaAuthentication = useMediaAuthentication(); const spoilerClickHandler = useSpoilerClickHandler(); const mentionClickHandler = useMentionClickHandler(room.roomId); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const openUserRoomProfile = useOpenUserRoomProfile(); const optionalSpace = useSpaceOptionally(); const roomParents = useAtomValue(roomToParentsAtom); @@ -438,22 +440,26 @@ export function RoomTimeline({ const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room.roomId, mentionClickHandler, nicknames] + [mx, room.roomId, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, useAuthentication: mediaAuthentication, handleSpoilerClick: spoilerClickHandler, @@ -470,6 +476,7 @@ export function RoomTimeline({ nicknames, mediaAuthentication, spoilerClickHandler, + settingsLinkBaseUrl, ] ); diff --git a/src/app/features/room/ThreadBrowser.tsx b/src/app/features/room/ThreadBrowser.tsx index 7c1e830f..0d9240c3 100644 --- a/src/app/features/room/ThreadBrowser.tsx +++ b/src/app/features/room/ThreadBrowser.tsx @@ -26,6 +26,7 @@ import { HTMLReactParserOptions } from 'html-react-parser'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { nicknamesAtom } from '$state/nicknames'; import { getMemberAvatarMxc, getMemberDisplayName, reactionOrEditEvent } from '$utils/room'; @@ -67,6 +68,7 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) { const useAuthentication = useMediaAuthentication(); const { navigateRoom } = useRoomNavigate(); const nicknames = useAtomValue(nicknamesAtom); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); @@ -77,29 +79,42 @@ function ThreadPreview({ room, thread, onClick }: ThreadPreviewProps) { const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href: string) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href: string) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room.roomId, nicknames, mentionClickHandler] + [mx, room.roomId, nicknames, mentionClickHandler, settingsLinkBaseUrl] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, useAuthentication, nicknames, }), - [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication, nicknames] + [ + mx, + room, + linkifyOpts, + mentionClickHandler, + spoilerClickHandler, + useAuthentication, + nicknames, + settingsLinkBaseUrl, + ] ); const handleJumpClick: MouseEventHandler = useCallback( diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 163d40ff..988d1ba8 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -35,6 +35,7 @@ import { getMxIdLocalPart, toggleReaction } from '$utils/matrix'; import { minuteDifference } from '$utils/time'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { nicknamesAtom } from '$state/nicknames'; import { MessageLayout, MessageSpacing, settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; @@ -367,6 +368,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); const useAuthentication = useMediaAuthentication(); const mentionClickHandler = useMentionClickHandler(room.roomId); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const spoilerClickHandler = useSpoilerClickHandler(); // Settings @@ -381,29 +383,42 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room, mentionClickHandler, nicknames] + [mx, room, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, nicknames, }), - [mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication, nicknames] + [ + mx, + room, + linkifyOpts, + spoilerClickHandler, + mentionClickHandler, + useAuthentication, + nicknames, + settingsLinkBaseUrl, + ] ); // Power levels & permissions diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 22c63ce2..f2e720bd 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -66,6 +66,7 @@ import { mobileOrTablet } from '$utils/user-agent'; import { useComposingCheck } from '$hooks/useComposingCheck'; import { floatingEditor } from '$styles/overrides/Composer.css'; import { RenderMessageContent } from '$components/RenderMessageContent'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser'; import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; import { HTMLReactParserOptions } from 'html-react-parser'; @@ -348,16 +349,18 @@ export const MessageEditor = as<'div', MessageEditorProps>( }, [saveState, onCancel]); const useAuthentication = useMediaAuthentication(); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const linkifyOpts = useMemo(() => ({ ...LINKIFY_OPTS }), []); const spoilerClickHandler = useSpoilerClickHandler(); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, mEvent.getRoomId(), { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, }), - [linkifyOpts, mEvent, mx, spoilerClickHandler, useAuthentication] + [linkifyOpts, mEvent, mx, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication] ); const getContent = (() => mEvent.getContent()) as GetContentCallback; const msgType = mEvent.getContent().msgtype; diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 9762f216..dd34bb48 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -52,6 +52,7 @@ import { import { GetContentCallback, MessageEvent, StateEvent } from '$types/matrix/room'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { factoryRenderLinkifyWithMention, getReactCustomHtmlParser, @@ -332,26 +333,31 @@ export const RoomPinMenu = forwardRef( }); const mentionClickHandler = useMentionClickHandler(room.roomId); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const spoilerClickHandler = useSpoilerClickHandler(); const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room, mentionClickHandler, nicknames] + [mx, room, mentionClickHandler, nicknames, settingsLinkBaseUrl] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, @@ -366,6 +372,7 @@ export const RoomPinMenu = forwardRef( spoilerClickHandler, useAuthentication, nicknames, + settingsLinkBaseUrl, ] ); diff --git a/src/app/features/settings/Persona/ProfilesPage.tsx b/src/app/features/settings/Persona/ProfilesPage.tsx index 2ed5dfa8..841b0386 100644 --- a/src/app/features/settings/Persona/ProfilesPage.tsx +++ b/src/app/features/settings/Persona/ProfilesPage.tsx @@ -4,12 +4,13 @@ import { SettingsSectionPage } from '../SettingsSectionPage'; import { PerMessageProfileOverview } from './PerMessageProfileOverview'; type PerMessageProfilePageProps = { + requestBack?: () => void; requestClose: () => void; }; -export function PerMessageProfilePage({ requestClose }: PerMessageProfilePageProps) { +export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageProfilePageProps) { return ( - + ({ + mockMatrixClient: { getUserId: () => '@alice:server' }, + mockProfile: { displayName: 'Alice', avatarUrl: undefined }, +})); + +let settingsLinkBaseUrlOverride: string | undefined; + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => mockMatrixClient, +})); + +vi.mock('$hooks/useUserProfile', () => ({ + useUserProfile: () => mockProfile, +})); + +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => false, +})); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: (_atom: unknown, key: string) => { + if (key === 'settingsLinkBaseUrlOverride') { + return [settingsLinkBaseUrlOverride, vi.fn()] as const; + } + + return [true, vi.fn()] as const; + }, +})); + +vi.mock('$state/settings', () => ({ + settingsAtom: {}, +})); + +vi.mock('./useSettingsFocus', () => ({ + useSettingsFocus: () => {}, +})); + +vi.mock('./general', () => ({ + General: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./account', () => ({ + Account: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./Persona/ProfilesPage', () => ({ + PerMessageProfilePage: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./cosmetics/Cosmetics', () => ({ + Cosmetics: ({ requestClose }: { requestClose: () => void }) => ( +
+ + +
+ ), +})); + +vi.mock('./notifications', () => ({ + Notifications: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./devices', () => ({ + Devices: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./emojis-stickers', () => ({ + EmojisStickers: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./developer-tools', () => ({ + DeveloperTools: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./experimental/Experimental', () => ({ + Experimental: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./about', () => ({ + About: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +vi.mock('./keyboard-shortcuts', () => ({ + KeyboardShortcuts: ({ requestClose }: { requestClose: () => void }) => ( + + ), +})); + +beforeEach(() => { + writeText.mockReset(); + settingsLinkBaseUrlOverride = undefined; + vi.stubGlobal('location', { origin: 'https://app.example' } as Location); + vi.stubGlobal('navigator', { clipboard: { writeText } } as unknown as Navigator); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Settings', () => { + it('uses the configured settings link base URL for copied settings permalinks', async () => { + writeText.mockResolvedValueOnce(undefined); + + render( + + + + + + ); + + fireEvent.click(screen.getByRole('button', { name: /copy settings permalink/i })); + + await waitFor(() => { + expect(writeText).toHaveBeenCalledWith( + 'https://config.example/settings/appearance/?focus=message-link-preview' + ); + }); + }); + + it('prefers the client-side override over the configured settings link base URL', async () => { + writeText.mockResolvedValueOnce(undefined); + settingsLinkBaseUrlOverride = 'https://override.example/'; + + render( + + + + + + ); + + fireEvent.click(screen.getByRole('button', { name: /copy settings permalink/i })); + + await waitFor(() => { + expect(writeText).toHaveBeenCalledWith( + 'https://override.example/settings/appearance/?focus=message-link-preview' + ); + }); + }); +}); diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 72ed2925..d52b4d3a 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -40,7 +40,10 @@ import { KeyboardShortcuts } from './keyboard-shortcuts'; import { Notifications } from './notifications'; import { PerMessageProfilePage } from './Persona/ProfilesPage'; import { settingsSections, type SettingsSectionId } from './routes'; +import { settingsHeader } from './styles.css'; import { useSettingsFocus } from './useSettingsFocus'; +import { SettingsPermalinkProvider } from './SettingsPermalinkContext'; +import { useSettingsLinkBaseUrl } from './useSettingsLinkBaseUrl'; export enum SettingsPages { GeneralPage, @@ -110,7 +113,7 @@ const settingsSectionIdToPage: Record = { const settingsSectionComponents: Record< SettingsSectionId, - (props: { requestClose: () => void }) => JSX.Element + (props: { requestBack?: () => void; requestClose: () => void }) => JSX.Element > = { general: General, account: Account, @@ -128,25 +131,29 @@ const settingsSectionComponents: Record< type ControlledSettingsProps = { activeSection?: SettingsSectionId | null; onSelectSection?: (section: SettingsSectionId) => void; + onBack?: () => void; requestClose: () => void; initialPage?: SettingsPages; }; function SettingsSectionViewport({ section, + requestBack, requestClose, }: { section: SettingsSectionId; + requestBack?: () => void; requestClose: () => void; }) { useSettingsFocus(); const Section = settingsSectionComponents[section]; - return
; + return
; } export function Settings({ activeSection, onSelectSection, + onBack, requestClose, initialPage, }: ControlledSettingsProps) { @@ -160,6 +167,7 @@ export function Settings({ : undefined; const [showPersona] = useSetting(settingsAtom, 'showPersonaSetting'); + const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const screenSize = useScreenSizeContext(); const isControlled = activeSection !== undefined; @@ -220,12 +228,30 @@ export function Settings({ requestClose(); }; + const handleRequestBack = () => { + if (isControlled) { + onBack?.(); + return; + } + + if (screenSize === ScreenSize.Mobile) { + setLegacyActivePage(undefined); + return; + } + + setLegacyActivePage(SettingsPages.GeneralPage); + }; + + const shouldShowSectionBack = + visibleSection !== null && (screenSize === ScreenSize.Mobile || visibleSection !== 'general'); + const sectionRequestBack = shouldShowSectionBack ? handleRequestBack : undefined; + return ( - + - {screenSize === ScreenSize.Mobile && ( + {visibleSection === null && ( + } onClick={() => handleSelectSection(item.id)} > @@ -273,7 +303,7 @@ export function Settings({ fontWeight: visibleSection === item.id ? config.fontWeight.W600 : undefined, }} - size="T300" + size={screenSize === ScreenSize.Mobile ? 'T400' : 'T300'} truncate > {item.name} @@ -322,7 +352,15 @@ export function Settings({ } > {visibleSection && ( - + + + )} ); diff --git a/src/app/features/settings/SettingsPermalinkContext.tsx b/src/app/features/settings/SettingsPermalinkContext.tsx new file mode 100644 index 00000000..043b1e35 --- /dev/null +++ b/src/app/features/settings/SettingsPermalinkContext.tsx @@ -0,0 +1,16 @@ +import { createContext, useContext } from 'react'; +import { type SettingsSectionId } from './routes'; + +type SettingsPermalinkContextValue = { + section: SettingsSectionId; + baseUrl: string; +}; + +const SettingsPermalinkContext = createContext(null); + +export const SettingsPermalinkProvider = SettingsPermalinkContext.Provider; + +export const useSettingsPermalinkContext = (): SettingsPermalinkContextValue | null => + useContext(SettingsPermalinkContext); + +export type { SettingsPermalinkContextValue }; diff --git a/src/app/features/settings/SettingsRoute.test.tsx b/src/app/features/settings/SettingsRoute.test.tsx index 97cd518f..91de0214 100644 --- a/src/app/features/settings/SettingsRoute.test.tsx +++ b/src/app/features/settings/SettingsRoute.test.tsx @@ -10,28 +10,56 @@ import { useNavigationType, } from 'react-router-dom'; import { describe, expect, it, vi } from 'vitest'; +import { Text } from 'folds'; +import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; +import { ClientConfigProvider } from '$hooks/useClientConfig'; +import { ClientLayout } from '$pages/client'; import { ClientRouteOutlet } from '$pages/client/ClientRouteOutlet'; import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; +import * as pageCss from '$components/page/style.css'; +import { messageJumpHighlight } from '$components/message/layout/layout.css'; import { getHomePath, getSettingsPath } from '$pages/pathUtils'; import { SETTINGS_PATH } from '$pages/paths'; import { SettingsRoute } from './SettingsRoute'; import { SettingsShallowRouteRenderer } from './SettingsShallowRouteRenderer'; import { SettingsSectionPage } from './SettingsSectionPage'; import { focusedSettingTile } from './styles.css'; +import * as settingsCss from './styles.css'; import { useOpenSettings } from './useOpenSettings'; import { useSettingsFocus } from './useSettingsFocus'; +type RouterInitialEntry = + | string + | { + pathname: string; + search?: string; + hash?: string; + state?: unknown; + key?: string; + }; + const { mockMatrixClient, mockProfile, mockUseSetting, createSectionMock } = vi.hoisted(() => { const mockSettingsHook = vi.fn(() => [true, vi.fn()] as const); const createMockSection = (title: string) => - function MockSection({ requestClose }: { requestClose: () => void }) { + function MockSection({ + requestBack, + requestClose, + }: { + requestBack?: () => void; + requestClose: () => void; + }) { return (

{title}

+ {requestBack && ( + + )}
); @@ -66,7 +94,28 @@ vi.mock('$components/Modal500', () => ({ })); vi.mock('./general', () => ({ - General: createSectionMock('General section'), + General: ({ + requestBack, + requestClose, + }: { + requestBack?: () => void; + requestClose: () => void; + }) => ( +
+

General section

+ + Message Layout + + {requestBack && ( + + )} + +
+ ), })); vi.mock('./account', () => ({ @@ -114,7 +163,9 @@ function FocusFixture() { return (
- focus target + + focus target +
); } @@ -167,22 +218,24 @@ function OpenSettingsHomePage() { function renderClientShell( screenSize: ScreenSize, - options?: { initialEntries?: string[]; initialIndex?: number } + options?: { initialEntries?: RouterInitialEntry[]; initialIndex?: number } ) { const initialEntries = options?.initialEntries ?? [getHomePath()]; return render( - - - - - }> - } /> - } /> - - - - - + + + + + + }> + } /> + } /> + + + + + + ); } @@ -198,53 +251,92 @@ function SidebarSettingsShortcut() { function renderClientShellWithOpenSettings( screenSize: ScreenSize, - options?: { initialEntries?: string[]; initialIndex?: number } + options?: { initialEntries?: RouterInitialEntry[]; initialIndex?: number } ) { const initialEntries = options?.initialEntries ?? [getHomePath()]; return render( - - - - - - }> - } /> - } /> - - - - - + + + + + + + }> + } /> + } /> + + + + + + + ); +} + +function renderClientLayoutShell( + screenSize: ScreenSize, + options?: { initialEntries?: RouterInitialEntry[]; initialIndex?: number } +) { + const initialEntries = options?.initialEntries ?? [getHomePath()]; + return render( + + + + + + App sidebar}> + + + } + > + } /> + } /> + + + + + + ); } function renderSettingsRoute( path: string, screenSize: ScreenSize, - options?: { initialEntries?: string[]; initialIndex?: number } + options?: { initialEntries?: RouterInitialEntry[]; initialIndex?: number } ) { const initialEntries = options?.initialEntries ?? [path]; return render( - - - - - } /> - - - + + + + + + } /> + + + + ); } describe('SettingsSectionPage', () => { - it('shows a back affordance on mobile section pages', () => { + it('reuses the message jump highlight class without adding a separate radius override', () => { + expect(focusedSettingTile).toBe(messageJumpHighlight); + }); + + it('shows back on the left and close on the right for mobile section pages', () => { render( - + ); - expect(screen.getByRole('button')).toBeInTheDocument(); + expect( + screen.getAllByRole('button').map((button) => button.getAttribute('aria-label')) + ).toEqual(['Back', 'Close']); }); it('supports custom title semantics and close label', () => { @@ -254,14 +346,51 @@ describe('SettingsSectionPage', () => { title="Keyboard Shortcuts" titleAs="h1" actionLabel="Close keyboard shortcuts" + requestBack={vi.fn()} requestClose={vi.fn()} /> ); expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Keyboard Shortcuts'); + expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Close keyboard shortcuts' })).toBeInTheDocument(); }); + + it('uses the default outlined page header treatment', () => { + render( + + + + ); + + expect(screen.getByText('Devices').closest('header')).toHaveClass(pageCss.PageHeader({})); + }); + + it('matches the main settings header title size', () => { + const rootRender = renderSettingsRoute('/settings', ScreenSize.Mobile); + const mainHeaderClassName = screen.getByText('Settings').className; + + rootRender.unmount(); + + render( + + + + ); + + expect(screen.getByText('Devices').className).toBe(mainHeaderClassName); + }); + + it('uses settings header spacing that matches the main settings shell', () => { + render( + + + + ); + + expect(screen.getByText('Devices').closest('header')).toHaveClass(settingsCss.settingsHeader); + }); }); describe('SettingsRoute', () => { @@ -273,6 +402,27 @@ describe('SettingsRoute', () => { expect(screen.queryByRole('heading', { name: 'General section' })).not.toBeInTheDocument(); }); + it('uses the default outlined nav header treatment for the settings menu', () => { + renderSettingsRoute('/settings', ScreenSize.Mobile); + + expect(screen.getByText('Settings').closest('header')).toHaveClass(pageCss.PageNavHeader({})); + }); + + it('uses larger nav labels on mobile settings', () => { + const referenceRender = render( + + Reference + + ); + const mobileClassName = screen.getByText('Reference').className; + + referenceRender.unmount(); + + renderSettingsRoute('/settings', ScreenSize.Mobile); + + expect(screen.getByText('Notifications').className).toBe(mobileClassName); + }); + it('redirects desktop /settings to /settings/general', async () => { renderSettingsRoute('/settings', ScreenSize.Desktop); @@ -291,19 +441,80 @@ describe('SettingsRoute', () => { expect(screen.getByTestId('location-probe')).toHaveTextContent(getSettingsPath('general')) ); - await user.click(screen.getByRole('button', { name: 'Back' })); + await user.click(screen.getByRole('button', { name: 'Close' })); await waitFor(() => expect(screen.getByTestId('location-probe')).toHaveTextContent(getHomePath()) ); }); + it('closes to the stored background route instead of stepping through prior settings entries', async () => { + const user = userEvent.setup(); + const backgroundLocation = { + pathname: getHomePath(), + search: '', + hash: '', + state: null, + key: 'home', + }; + + renderSettingsRoute(getSettingsPath('devices'), ScreenSize.Desktop, { + initialEntries: [ + getHomePath(), + { + pathname: getSettingsPath('notifications'), + state: { backgroundLocation }, + key: 'settings-notifications', + }, + { + pathname: getSettingsPath('devices'), + state: { backgroundLocation }, + key: 'settings-devices', + }, + ], + initialIndex: 2, + }); + + await user.click(screen.getByRole('button', { name: 'Close' })); + + await waitFor(() => + expect(screen.getByTestId('location-probe')).toHaveTextContent(getHomePath()) + ); + expect(screen.getByTestId('location-probe')).not.toHaveTextContent( + getSettingsPath('notifications') + ); + }); + it('renders the requested section at /settings/devices', () => { renderSettingsRoute('/settings/devices', ScreenSize.Mobile); expect(screen.getByRole('heading', { name: 'Devices section' })).toBeInTheDocument(); }); + it('focuses and highlights a real general setting tile from the URL', async () => { + vi.useFakeTimers(); + + try { + renderSettingsRoute('/settings/general?focus=message-layout', ScreenSize.Mobile); + + const target = document.querySelector('[data-settings-focus="message-layout"]'); + const highlightTarget = target?.parentElement; + + expect(target).not.toHaveClass(focusedSettingTile); + expect(highlightTarget).toHaveClass(focusedSettingTile); + expect(screen.getByTestId('location-probe')).toHaveTextContent('?focus=message-layout'); + + await act(async () => { + await vi.advanceTimersByTimeAsync(3000); + }); + + expect(highlightTarget).not.toHaveClass(focusedSettingTile); + expect(screen.getByTestId('location-probe')).toHaveTextContent('/settings/general'); + } finally { + vi.useRealTimers(); + } + }); + it('redirects invalid sections back to /settings', async () => { renderSettingsRoute('/settings/not-a-real-section', ScreenSize.Mobile); @@ -326,6 +537,18 @@ describe('SettingsRoute', () => { expect(screen.getByText('Settings')).toBeInTheDocument(); }); + it('falls back to /home when a direct section entry is closed', async () => { + const user = userEvent.setup(); + + renderSettingsRoute('/settings/devices', ScreenSize.Mobile); + + await user.click(screen.getByRole('button', { name: 'Close' })); + + await waitFor(() => + expect(screen.getByTestId('location-probe')).toHaveTextContent(getHomePath()) + ); + }); + it('falls back to /home when the root settings page is closed from a direct entry', async () => { const user = userEvent.setup(); @@ -446,7 +669,7 @@ describe('Settings shallow route shell', () => { expect(screen.getByRole('heading', { name: 'Devices section' })).toBeInTheDocument(); }); - it('closes a desktop shallow settings flow in one step after switching sections', async () => { + it('returns to general settings when desktop section back is clicked', async () => { const user = userEvent.setup(); renderClientShell(ScreenSize.Desktop); @@ -455,6 +678,20 @@ describe('Settings shallow route shell', () => { await user.click(screen.getByRole('button', { name: 'Devices' })); await user.click(screen.getByRole('button', { name: 'Back' })); + expect(screen.getByRole('heading', { name: 'Home route' })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'General section' })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Devices section' })).not.toBeInTheDocument(); + }); + + it('closes a desktop shallow settings flow in one step after switching sections', async () => { + const user = userEvent.setup(); + + renderClientShell(ScreenSize.Desktop); + + await user.click(screen.getByRole('button', { name: 'Open settings' })); + await user.click(screen.getByRole('button', { name: 'Devices' })); + await user.click(screen.getByRole('button', { name: 'Close' })); + expect(screen.getByRole('heading', { name: 'Home route' })).toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Devices section' })).not.toBeInTheDocument(); expect( @@ -471,6 +708,15 @@ describe('Settings shallow route shell', () => { expect(screen.queryByRole('heading', { name: 'Home route' })).not.toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Devices section' })).toBeInTheDocument(); }); + + it('hides the client sidebar when desktop settings renders as a full page', () => { + renderClientLayoutShell(ScreenSize.Desktop, { + initialEntries: [getSettingsPath('devices')], + }); + + expect(screen.queryByText('App sidebar')).not.toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Devices section' })).toBeInTheDocument(); + }); }); describe('useSettingsFocus', () => { @@ -488,20 +734,24 @@ describe('useSettingsFocus', () => { ); const target = document.querySelector('[data-settings-focus="message-link-preview"]'); - expect(target).toHaveClass(focusedSettingTile); + const highlightTarget = target?.parentElement; + expect(target).not.toHaveClass(focusedSettingTile); + expect(highlightTarget).toHaveClass(focusedSettingTile); + expect(highlightTarget).toHaveClass(messageJumpHighlight); expect(screen.getByTestId('location-probe')).toHaveTextContent('?focus=message-link-preview'); await act(async () => { await vi.advanceTimersByTimeAsync(2999); }); expect(screen.getByTestId('location-probe')).toHaveTextContent('?focus=message-link-preview'); - expect(target).toHaveClass(focusedSettingTile); + expect(highlightTarget).toHaveClass(focusedSettingTile); + expect(highlightTarget).toHaveClass(messageJumpHighlight); await act(async () => { await vi.advanceTimersByTimeAsync(1); }); expect(screen.getByTestId('location-probe')).toHaveTextContent('/settings/appearance'); - expect(target).not.toHaveClass(focusedSettingTile); + expect(highlightTarget).not.toHaveClass(focusedSettingTile); } finally { vi.useRealTimers(); } diff --git a/src/app/features/settings/SettingsRoute.tsx b/src/app/features/settings/SettingsRoute.tsx index 81d266c9..c1fbce5d 100644 --- a/src/app/features/settings/SettingsRoute.tsx +++ b/src/app/features/settings/SettingsRoute.tsx @@ -1,17 +1,13 @@ import { useEffect } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; -import { getHomePath, getSettingsPath } from '$pages/pathUtils'; +import { getSettingsPath } from '$pages/pathUtils'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; +import { getSettingsCloseTarget, type SettingsRouteState } from './navigation'; import { Settings } from './Settings'; import { isSettingsSectionId, type SettingsSectionId } from './routes'; -type SettingsRouteState = { - backgroundLocation?: unknown; - redirectedFromDesktopRoot?: boolean; -}; - function resolveSettingsSection( section: string | undefined, screenSize: ScreenSize, @@ -41,6 +37,13 @@ export function SettingsRoute() { const routeState = location.state as SettingsRouteState | null; const shallowBackgroundState = screenSize !== ScreenSize.Mobile && Boolean(routeState?.backgroundLocation); + const browserHistoryIndex = + typeof window !== 'undefined' && typeof window.history.state?.idx === 'number' + ? window.history.state.idx + : null; + const hasPreviousEntry = + (typeof browserHistoryIndex === 'number' && browserHistoryIndex > 0) || + location.key !== 'default'; const activeSection = resolveSettingsSection(section, screenSize, showPersona); const shouldRedirectToGeneral = section === undefined && screenSize !== ScreenSize.Mobile; @@ -62,23 +65,38 @@ export function SettingsRoute() { if (shouldRedirectToGeneral || shouldRedirectToIndex) return null; + const requestBack = () => { + if (section === undefined) return; + + if (screenSize === ScreenSize.Mobile) { + if (hasPreviousEntry) { + navigate(-1); + return; + } + + navigate(getSettingsPath(), { + replace: true, + state: routeState?.backgroundLocation ? routeState : undefined, + }); + return; + } + + let desktopBackState: SettingsRouteState | undefined; + if (routeState?.backgroundLocation) { + desktopBackState = routeState; + } else if (routeState?.redirectedFromDesktopRoot) { + desktopBackState = { redirectedFromDesktopRoot: true }; + } + + navigate(getSettingsPath('general'), { + replace: true, + state: desktopBackState, + }); + }; + const requestClose = () => { - if (section !== undefined && routeState?.redirectedFromDesktopRoot) { - navigate(getHomePath(), { replace: true }); - return; - } - - if (section !== undefined && location.key === 'default') { - navigate(getSettingsPath(), { replace: true, state: routeState }); - return; - } - - if (section === undefined && location.key === 'default') { - navigate(getHomePath(), { replace: true }); - return; - } - - navigate(-1); + const closeTarget = getSettingsCloseTarget(routeState); + navigate(closeTarget.to, { replace: true, state: closeTarget.state }); }; const handleSelectSection = (nextSection: SettingsSectionId) => { @@ -93,6 +111,7 @@ export function SettingsRoute() { return ( diff --git a/src/app/features/settings/SettingsSectionPage.tsx b/src/app/features/settings/SettingsSectionPage.tsx index a7f6ff19..277e6c18 100644 --- a/src/app/features/settings/SettingsSectionPage.tsx +++ b/src/app/features/settings/SettingsSectionPage.tsx @@ -1,39 +1,46 @@ import { ReactNode } from 'react'; import { Box, Icon, IconButton, Icons, Text } from 'folds'; import { Page, PageHeader } from '$components/page'; -import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; +import { settingsHeader } from './styles.css'; type SettingsSectionPageProps = { title: ReactNode; + requestBack?: () => void; requestClose: () => void; titleAs?: 'h1' | 'h2' | 'h3' | 'span' | 'div'; + backLabel?: string; actionLabel?: string; children?: ReactNode; }; export function SettingsSectionPage({ title, + requestBack, requestClose, titleAs, + backLabel, actionLabel, children, }: SettingsSectionPageProps) { - const screenSize = useScreenSizeContext(); - const isMobile = screenSize === ScreenSize.Mobile; - const closeLabel = isMobile ? 'Back' : (actionLabel ?? 'Close'); + const closeLabel = actionLabel ?? 'Close'; return ( - + - + {requestBack && ( + + + + )} + {title} - + diff --git a/src/app/features/settings/SettingsShallowRouteRenderer.tsx b/src/app/features/settings/SettingsShallowRouteRenderer.tsx index 92256fa8..e44d8746 100644 --- a/src/app/features/settings/SettingsShallowRouteRenderer.tsx +++ b/src/app/features/settings/SettingsShallowRouteRenderer.tsx @@ -3,17 +3,24 @@ import { useScreenSizeContext } from '$hooks/useScreenSize'; import { Modal500 } from '$components/Modal500'; import { isShallowSettingsRoute } from '$pages/client/ClientRouteOutlet'; import { SETTINGS_PATH } from '$pages/paths'; +import { getSettingsCloseTarget, type SettingsRouteState } from './navigation'; import { SettingsRoute } from './SettingsRoute'; export function SettingsShallowRouteRenderer() { const navigate = useNavigate(); const location = useLocation(); const screenSize = useScreenSizeContext(); + const routeState = location.state as SettingsRouteState | null; if (!isShallowSettingsRoute(location.pathname, location.state, screenSize)) return null; + const handleRequestClose = () => { + const closeTarget = getSettingsCloseTarget(routeState); + navigate(closeTarget.to, { replace: true, state: closeTarget.state }); + }; + return ( - navigate(-1)}> + } /> diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index 7abb66ef..fdd3d383 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -51,7 +51,11 @@ export function HomeserverInfo() { direction="Column" gap="400" > - + {mx.baseUrl} @@ -77,6 +82,7 @@ export function HomeserverInfo() { > {federationUrl} @@ -104,7 +110,11 @@ export function HomeserverInfo() { direction="Column" gap="400" > - + )} {version.server?.version && ( @@ -114,7 +124,11 @@ export function HomeserverInfo() { direction="Column" gap="400" > - + )} {version.server?.compiler && ( @@ -124,7 +138,11 @@ export function HomeserverInfo() { direction="Column" gap="400" > - + )} @@ -143,16 +161,17 @@ export function HomeserverInfo() { } type AboutProps = { + requestBack?: () => void; requestClose: () => void; }; -export function About({ requestClose }: Readonly) { +export function About({ requestBack, requestClose }: Readonly) { const mx = useMatrixClient(); const devLabel = IS_RELEASE_TAG ? '' : '-dev'; const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : ''; const openBugReport = useOpenBugReportModal(); return ( - + @@ -214,6 +233,7 @@ export function About({ requestClose }: Readonly) { > ) { > void; requestClose: () => void; }; -export function Account({ requestClose }: AccountProps) { +export function Account({ requestBack, requestClose }: AccountProps) { return ( - + diff --git a/src/app/features/settings/account/AnimalCosmetics.tsx b/src/app/features/settings/account/AnimalCosmetics.tsx index ada07ef9..30fe96a9 100644 --- a/src/app/features/settings/account/AnimalCosmetics.tsx +++ b/src/app/features/settings/account/AnimalCosmetics.tsx @@ -40,6 +40,7 @@ export function AnimalCosmetics({ profile, userId }: Readonly } /> @@ -47,6 +48,7 @@ export function AnimalCosmetics({ profile, userId }: Readonly - + {autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && ( - + {emailIds?.map((email) => ( diff --git a/src/app/features/settings/account/IgnoredUserList.tsx b/src/app/features/settings/account/IgnoredUserList.tsx index 0b3b3470..a898e799 100644 --- a/src/app/features/settings/account/IgnoredUserList.tsx +++ b/src/app/features/settings/account/IgnoredUserList.tsx @@ -144,6 +144,7 @@ export function IgnoredUserList() { > diff --git a/src/app/features/settings/account/MatrixId.tsx b/src/app/features/settings/account/MatrixId.tsx index 64043752..8e72acf8 100644 --- a/src/app/features/settings/account/MatrixId.tsx +++ b/src/app/features/settings/account/MatrixId.tsx @@ -20,6 +20,7 @@ export function MatrixId() { > copyToClipboard(userId)}> Copy diff --git a/src/app/features/settings/account/NameColorEditor.tsx b/src/app/features/settings/account/NameColorEditor.tsx index 73e417d2..8185dc2c 100644 --- a/src/app/features/settings/account/NameColorEditor.tsx +++ b/src/app/features/settings/account/NameColorEditor.tsx @@ -57,7 +57,7 @@ export function NameColorEditor({ return ( - + ) { return ( ) { const previewUrl = isRemoving ? undefined : imageFileURL || stagedUrl || bannerUrl; return ( - + ) { const hasChanges = displayName !== defaultDisplayName; return ( - + ) { > + diff --git a/src/app/features/settings/account/TimezoneEditor.tsx b/src/app/features/settings/account/TimezoneEditor.tsx index 7d28399a..2cbade5b 100644 --- a/src/app/features/settings/account/TimezoneEditor.tsx +++ b/src/app/features/settings/account/TimezoneEditor.tsx @@ -47,6 +47,7 @@ export function TimezoneEditor({ current, onSave }: TimezoneEditorProps) { return ( diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index e000075f..3d50d886 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -109,6 +109,7 @@ function JumboEmoji() { } /> @@ -132,6 +133,7 @@ function Privacy() { } /> @@ -140,6 +142,7 @@ function Privacy() { @@ -150,6 +153,7 @@ function Privacy() { @@ -181,6 +185,7 @@ function IdentityCosmetics() { } /> @@ -201,6 +207,7 @@ function IdentityCosmetics() { } /> @@ -208,6 +215,7 @@ function IdentityCosmetics() { @@ -217,6 +225,7 @@ function IdentityCosmetics() { @@ -226,6 +235,7 @@ function IdentityCosmetics() { } /> @@ -233,6 +243,7 @@ function IdentityCosmetics() { } /> @@ -242,12 +253,13 @@ function IdentityCosmetics() { } type CosmeticsProps = { + requestBack?: () => void; requestClose: () => void; }; -export function Cosmetics({ requestClose }: CosmeticsProps) { +export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) { return ( - + diff --git a/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx b/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx index 32c57e59..07d36892 100644 --- a/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx +++ b/src/app/features/settings/cosmetics/LanguageSpecificPronouns.tsx @@ -78,6 +78,7 @@ export function LanguageSpecificPronouns() { > } /> @@ -272,6 +275,7 @@ function ThemeSettings() { } /> @@ -280,6 +284,7 @@ function ThemeSettings() { } /> @@ -312,6 +318,7 @@ function ThemeSettings() { } /> @@ -319,6 +326,7 @@ function ThemeSettings() { } /> @@ -326,6 +334,7 @@ function ThemeSettings() { @@ -335,6 +344,7 @@ function ThemeSettings() { } /> @@ -446,6 +456,7 @@ export function Appearance() { } /> @@ -454,18 +465,20 @@ export function Appearance() { } /> - } /> + } /> } /> diff --git a/src/app/features/settings/developer-tools/AccountData.tsx b/src/app/features/settings/developer-tools/AccountData.tsx index 6cd68e9b..bc8737e9 100644 --- a/src/app/features/settings/developer-tools/AccountData.tsx +++ b/src/app/features/settings/developer-tools/AccountData.tsx @@ -38,6 +38,7 @@ export function AccountData({ expand, onExpandToggle, onSelect }: AccountDataPro > void; requestClose: () => void; }; -export function DeveloperTools({ requestClose }: DeveloperToolsProps) { +export function DeveloperTools({ requestBack, requestClose }: DeveloperToolsProps) { const mx = useMatrixClient(); const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools'); const [expand, setExpend] = useState(false); @@ -49,7 +50,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { } return ( - + @@ -64,6 +69,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { > @@ -113,6 +117,7 @@ export function SentrySettings() { {ALL_CATEGORIES.map((cat) => ( diff --git a/src/app/features/settings/devices/DeviceTile.tsx b/src/app/features/settings/devices/DeviceTile.tsx index b77be8ac..a63d7b72 100644 --- a/src/app/features/settings/devices/DeviceTile.tsx +++ b/src/app/features/settings/devices/DeviceTile.tsx @@ -28,6 +28,7 @@ import { stopPropagation } from '$utils/keyboard'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { SequenceCardStyle } from '$features/settings/styles.css'; +import { toSettingsFocusIdPart } from '$features/settings/settingsLink'; export function DeviceTilePlaceholder() { return ( @@ -285,6 +286,7 @@ export function DeviceTile({ return ( <> void; requestClose: () => void; }; -export function Devices({ requestClose }: DevicesProps) { +export function Devices({ requestBack, requestClose }: DevicesProps) { const mx = useMatrixClient(); const crypto = mx.getCrypto(); const crossSigningActive = useCrossSigningActive(); @@ -62,7 +63,7 @@ export function Devices({ requestClose }: DevicesProps) { ); return ( - + @@ -77,6 +78,7 @@ export function Devices({ requestClose }: DevicesProps) { > diff --git a/src/app/features/settings/devices/LocalBackup.tsx b/src/app/features/settings/devices/LocalBackup.tsx index eaefc7ff..09d350f8 100644 --- a/src/app/features/settings/devices/LocalBackup.tsx +++ b/src/app/features/settings/devices/LocalBackup.tsx @@ -73,7 +73,7 @@ function ExportKeys() { }; return ( - + @@ -142,6 +142,7 @@ function ExportKeysTile() { <> @@ -219,7 +220,7 @@ function ImportKeys({ file, onDone }: ImportKeysProps) { }; return ( - + @@ -271,6 +272,7 @@ function ImportKeysTile() { <> diff --git a/src/app/features/settings/devices/OtherDevices.tsx b/src/app/features/settings/devices/OtherDevices.tsx index e044201d..145be32d 100644 --- a/src/app/features/settings/devices/OtherDevices.tsx +++ b/src/app/features/settings/devices/OtherDevices.tsx @@ -114,6 +114,7 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O > void; requestClose: () => void; }; -export function EmojisStickers({ requestClose }: EmojisStickersProps) { +export function EmojisStickers({ requestBack, requestClose }: EmojisStickersProps) { const [imagePack, setImagePack] = useState(); const handleImagePackViewClose = () => { @@ -22,7 +23,11 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) { } return ( - + diff --git a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx index 1c66d4c6..224ed493 100644 --- a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx +++ b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx @@ -30,6 +30,7 @@ import { SettingTile } from '$components/setting-tile'; import { mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { toSettingsFocusIdPart } from '$features/settings/settingsLink'; import { EmoteRoomsContent, ImagePack, @@ -185,6 +186,7 @@ function GlobalPackSelector({ > {pack.meta.attribution}} before={ @@ -358,6 +360,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { gap="400" > {pack.meta.name ?? 'Unknown'} @@ -429,6 +432,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { > diff --git a/src/app/features/settings/emojis-stickers/UserPack.tsx b/src/app/features/settings/emojis-stickers/UserPack.tsx index 03c80da2..5d0c0c77 100644 --- a/src/app/features/settings/emojis-stickers/UserPack.tsx +++ b/src/app/features/settings/emojis-stickers/UserPack.tsx @@ -39,6 +39,7 @@ export function UserPack({ onViewPack }: UserPackProps) { > diff --git a/src/app/features/settings/experimental/BandwithSavingEmojis.tsx b/src/app/features/settings/experimental/BandwithSavingEmojis.tsx index 7e660fba..6240f236 100644 --- a/src/app/features/settings/experimental/BandwithSavingEmojis.tsx +++ b/src/app/features/settings/experimental/BandwithSavingEmojis.tsx @@ -22,6 +22,7 @@ export function BandwidthSavingEmojis() { > diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index 13456344..33041218 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -23,6 +23,7 @@ function PersonaToggle() { @@ -34,11 +35,12 @@ function PersonaToggle() { } type ExperimentalProps = { + requestBack?: () => void; requestClose: () => void; }; -export function Experimental({ requestClose }: Readonly) { +export function Experimental({ requestBack, requestClose }: Readonly) { return ( - + diff --git a/src/app/features/settings/experimental/MSC4268HistoryShare.tsx b/src/app/features/settings/experimental/MSC4268HistoryShare.tsx index d93a4103..27c868d1 100644 --- a/src/app/features/settings/experimental/MSC4268HistoryShare.tsx +++ b/src/app/features/settings/experimental/MSC4268HistoryShare.tsx @@ -22,6 +22,7 @@ export function MSC4268HistoryShare() { > ) const hasChanges = dateFormatCustom !== value; return ( - + } /> @@ -407,6 +409,7 @@ function DateAndTime() { } /> @@ -437,6 +440,7 @@ function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { > ) { } /> } /> @@ -464,6 +470,7 @@ function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { } /> @@ -471,6 +478,7 @@ function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { } /> @@ -478,6 +486,7 @@ function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { @@ -771,6 +780,7 @@ function Gestures({ isMobile }: Readonly<{ isMobile: boolean }>) { ) { } /> @@ -848,6 +859,7 @@ function Calls() { Messages - } /> + } + /> - } /> + } + /> - } /> + } + /> } /> @@ -916,6 +941,7 @@ function Messages() { } /> @@ -924,6 +950,7 @@ function Messages() { } /> } /> + + + @@ -1160,6 +1201,7 @@ export function Sync() { } type GeneralProps = { + requestBack?: () => void; requestClose: () => void; }; @@ -1201,11 +1243,16 @@ function SettingsSyncSection() { > } /> {syncEnabled && ( - + )} @@ -1294,6 +1341,7 @@ function DiagnosticsAndPrivacy() { > ) { +export function General({ requestBack, requestClose }: Readonly) { return ( - + diff --git a/src/app/features/settings/general/SettingsLinkBaseUrlSetting.test.tsx b/src/app/features/settings/general/SettingsLinkBaseUrlSetting.test.tsx new file mode 100644 index 00000000..f79b1e0c --- /dev/null +++ b/src/app/features/settings/general/SettingsLinkBaseUrlSetting.test.tsx @@ -0,0 +1,71 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ClientConfigProvider } from '$hooks/useClientConfig'; +import { SettingsLinkBaseUrlSetting } from './SettingsLinkBaseUrlSetting'; + +let settingsLinkBaseUrlOverride: string | undefined; +const setSettingsLinkBaseUrlOverride = vi.fn(); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: () => [settingsLinkBaseUrlOverride, setSettingsLinkBaseUrlOverride] as const, +})); + +vi.mock('$state/settings', () => ({ + settingsAtom: {}, +})); + +function renderSetting(settingsLinkBaseUrl = 'https://app.sable.moe') { + return render( + + + + ); +} + +describe('SettingsLinkBaseUrlSetting', () => { + beforeEach(() => { + settingsLinkBaseUrlOverride = undefined; + setSettingsLinkBaseUrlOverride.mockReset(); + }); + + it('shows the configured default in the input and no separate reset button', () => { + renderSetting('https://config.example'); + + expect(screen.getByRole('textbox', { name: 'Settings link base URL' })).toHaveValue( + 'https://config.example' + ); + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); + expect(screen.queryByRole('button', { name: 'Reset' })).not.toBeInTheDocument(); + }); + + it('uses an inline reset control to restore the configured default URL', () => { + renderSetting('https://config.example'); + + fireEvent.change(screen.getByRole('textbox', { name: 'Settings link base URL' }), { + target: { value: 'https://override.example' }, + }); + + expect( + screen.getByRole('button', { name: 'Reset settings link base URL' }) + ).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Reset settings link base URL' })); + + expect(screen.getByRole('textbox', { name: 'Settings link base URL' })).toHaveValue( + 'https://config.example' + ); + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); + }); + + it('clears the override when saving the configured default URL', () => { + settingsLinkBaseUrlOverride = 'https://override.example'; + renderSetting('https://config.example'); + + fireEvent.change(screen.getByRole('textbox', { name: 'Settings link base URL' }), { + target: { value: 'https://config.example' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + + expect(setSettingsLinkBaseUrlOverride).toHaveBeenCalledWith(undefined); + }); +}); diff --git a/src/app/features/settings/general/SettingsLinkBaseUrlSetting.tsx b/src/app/features/settings/general/SettingsLinkBaseUrlSetting.tsx new file mode 100644 index 00000000..22bb6655 --- /dev/null +++ b/src/app/features/settings/general/SettingsLinkBaseUrlSetting.tsx @@ -0,0 +1,108 @@ +import { ChangeEventHandler, FormEventHandler, useEffect, useMemo, useState } from 'react'; +import { Box, Button, config, Icon, IconButton, Icons, Input, Text } from 'folds'; +import { useClientConfig } from '$hooks/useClientConfig'; +import { SettingTile } from '$components/setting-tile'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { getConfiguredSettingsLinkBaseUrl, normalizeSettingsLinkBaseUrl } from '../settingsLink'; + +export function SettingsLinkBaseUrlSetting() { + const clientConfig = useClientConfig(); + const [settingsLinkBaseUrlOverride, setSettingsLinkBaseUrlOverride] = useSetting( + settingsAtom, + 'settingsLinkBaseUrlOverride' + ); + const configuredBaseUrl = useMemo( + () => getConfiguredSettingsLinkBaseUrl(clientConfig), + [clientConfig] + ); + const currentValue = + normalizeSettingsLinkBaseUrl(settingsLinkBaseUrlOverride) ?? configuredBaseUrl; + const [inputValue, setInputValue] = useState(currentValue); + + useEffect(() => { + setInputValue(currentValue); + }, [currentValue]); + + const trimmedValue = inputValue.trim(); + const normalizedInputValue = normalizeSettingsLinkBaseUrl(trimmedValue); + const nextOverrideValue = + normalizedInputValue && normalizedInputValue !== configuredBaseUrl + ? normalizedInputValue + : undefined; + const hasChanges = normalizedInputValue !== currentValue; + const isValid = Boolean(normalizedInputValue); + + const handleChange: ChangeEventHandler = (evt) => { + setInputValue(evt.currentTarget.value); + }; + + const handleSubmit: FormEventHandler = (evt) => { + evt.preventDefault(); + if (!isValid) return; + + setSettingsLinkBaseUrlOverride(nextOverrideValue); + setInputValue(normalizedInputValue ?? configuredBaseUrl); + }; + + const handleReset = () => { + setInputValue(configuredBaseUrl); + }; + + return ( + + + + + + + + ) + } + /> + + + + + {!isValid && ( + + Enter a full `http://` or `https://` URL. + + )} + + ); +} diff --git a/src/app/features/settings/index.ts b/src/app/features/settings/index.ts index 5b1e4342..c19de644 100644 --- a/src/app/features/settings/index.ts +++ b/src/app/features/settings/index.ts @@ -1,4 +1,5 @@ export * from './Settings'; export * from './SettingsRoute'; +export * from './settingsLink'; export * from './routes'; export * from './useOpenSettings'; diff --git a/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx b/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx index 2900f78c..54e0f0d7 100644 --- a/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx +++ b/src/app/features/settings/keyboard-shortcuts/KeyboardShortcuts.tsx @@ -107,14 +107,16 @@ function ShortcutRow({ keys, description }: ShortcutEntry) { } type KeyboardShortcutsProps = { + requestBack?: () => void; requestClose: () => void; }; -export function KeyboardShortcuts({ requestClose }: KeyboardShortcutsProps) { +export function KeyboardShortcuts({ requestBack, requestClose }: KeyboardShortcutsProps) { return ( diff --git a/src/app/features/settings/navigation.ts b/src/app/features/settings/navigation.ts new file mode 100644 index 00000000..da78c597 --- /dev/null +++ b/src/app/features/settings/navigation.ts @@ -0,0 +1,34 @@ +import type { To } from 'react-router-dom'; +import { getHomePath } from '$pages/pathUtils'; + +export type SettingsStoredLocation = { + pathname: string; + search: string; + hash: string; + state?: unknown; + key?: string; +}; + +export type SettingsRouteState = { + backgroundLocation?: SettingsStoredLocation; + redirectedFromDesktopRoot?: boolean; +}; + +export function getSettingsCloseTarget(routeState: SettingsRouteState | null | undefined): { + to: To; + state?: unknown; +} { + const backgroundLocation = routeState?.backgroundLocation; + if (!backgroundLocation) { + return { to: getHomePath() }; + } + + return { + to: { + pathname: backgroundLocation.pathname, + search: backgroundLocation.search, + hash: backgroundLocation.hash, + }, + state: backgroundLocation.state, + }; +} diff --git a/src/app/features/settings/notifications/AllMessages.tsx b/src/app/features/settings/notifications/AllMessages.tsx index 5ee60a17..f6736910 100644 --- a/src/app/features/settings/notifications/AllMessages.tsx +++ b/src/app/features/settings/notifications/AllMessages.tsx @@ -109,6 +109,7 @@ export function AllMessagesNotifications() { > } /> @@ -121,6 +122,7 @@ export function AllMessagesNotifications() { > } /> @@ -151,6 +154,7 @@ export function AllMessagesNotifications() { > This will remove push notifications from all your sessions/devices. diff --git a/src/app/features/settings/notifications/KeywordMessages.tsx b/src/app/features/settings/notifications/KeywordMessages.tsx index ff235271..941cf95e 100644 --- a/src/app/features/settings/notifications/KeywordMessages.tsx +++ b/src/app/features/settings/notifications/KeywordMessages.tsx @@ -6,6 +6,7 @@ import { AccountDataEvent } from '$types/matrix/accountData'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { toSettingsFocusIdPart } from '$features/settings/settingsLink'; import { getNotificationModeActions, NotificationMode, @@ -183,6 +184,7 @@ export function KeywordMessagesNotifications() { > @@ -198,6 +200,9 @@ export function KeywordMessagesNotifications() { > } after={} /> diff --git a/src/app/features/settings/notifications/Notifications.tsx b/src/app/features/settings/notifications/Notifications.tsx index 729859a7..b161a357 100644 --- a/src/app/features/settings/notifications/Notifications.tsx +++ b/src/app/features/settings/notifications/Notifications.tsx @@ -7,11 +7,16 @@ import { SpecialMessagesNotifications } from './SpecialMessages'; import { KeywordMessagesNotifications } from './KeywordMessages'; type NotificationsProps = { + requestBack?: () => void; requestClose: () => void; }; -export function Notifications({ requestClose }: NotificationsProps) { +export function Notifications({ requestBack, requestClose }: NotificationsProps) { return ( - + diff --git a/src/app/features/settings/notifications/SpecialMessages.tsx b/src/app/features/settings/notifications/SpecialMessages.tsx index ac8d736f..866c5382 100644 --- a/src/app/features/settings/notifications/SpecialMessages.tsx +++ b/src/app/features/settings/notifications/SpecialMessages.tsx @@ -146,6 +146,7 @@ export function SpecialMessagesNotifications() { > {result && !result.email && ( @@ -140,6 +141,7 @@ function WebPushNotificationSetting() { return ( @@ -237,6 +239,7 @@ export function SystemNotification() { > } /> @@ -260,6 +263,7 @@ export function SystemNotification() { > } /> @@ -273,6 +277,7 @@ export function SystemNotification() { > } /> @@ -285,6 +290,7 @@ export function SystemNotification() { > } /> @@ -297,6 +303,7 @@ export function SystemNotification() { > } /> @@ -351,6 +359,7 @@ export function SystemNotification() { > @@ -383,6 +393,7 @@ export function SystemNotification() { > @@ -397,6 +408,7 @@ export function SystemNotification() { > } /> @@ -409,6 +421,7 @@ export function SystemNotification() { > diff --git a/src/app/features/settings/settingTileFocusCoverage.test.ts b/src/app/features/settings/settingTileFocusCoverage.test.ts new file mode 100644 index 00000000..76b02f79 --- /dev/null +++ b/src/app/features/settings/settingTileFocusCoverage.test.ts @@ -0,0 +1,31 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const getSettingsFiles = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const filePath = join(dir, entry.name); + + if (entry.isDirectory()) { + return getSettingsFiles(filePath); + } + + if (!entry.isFile() || !filePath.endsWith('.tsx') || filePath.endsWith('.test.tsx')) { + return []; + } + + return [filePath]; + }); + +describe('settings tile focus coverage', () => { + it('requires every settings SettingTile to declare a focusId', () => { + const offenders = getSettingsFiles('src/app/features/settings').flatMap((file) => { + const source = readFileSync(file, 'utf8'); + const matches = [...source.matchAll(/]*\bfocusId=)/g)]; + + return matches.map(() => file); + }); + + expect(offenders).toEqual([]); + }); +}); diff --git a/src/app/features/settings/settingsLink.test.ts b/src/app/features/settings/settingsLink.test.ts new file mode 100644 index 00000000..a9dfdb10 --- /dev/null +++ b/src/app/features/settings/settingsLink.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest'; +import { + DEFAULT_SETTINGS_LINK_BASE_URL, + buildSettingsPermalink, + getEffectiveSettingsLinkBaseUrl, + parseSettingsPermalink, + toSettingsFocusIdPart, +} from './settingsLink'; + +describe('settingsLink', () => { + it('builds settings permalinks for plain and hash-router base urls', () => { + expect( + buildSettingsPermalink('https://app.example', 'appearance', 'message-link-preview') + ).toBe('https://app.example/settings/appearance/?focus=message-link-preview'); + expect( + buildSettingsPermalink('https://app.example/#/app', 'appearance', 'message-link-preview') + ).toBe('https://app.example/#/app/settings/appearance/?focus=message-link-preview'); + }); + + it('resolves the settings link base URL from built-in default, config, and override', () => { + expect(getEffectiveSettingsLinkBaseUrl({}, undefined)).toBe(DEFAULT_SETTINGS_LINK_BASE_URL); + expect(getEffectiveSettingsLinkBaseUrl({}, true as never)).toBe(DEFAULT_SETTINGS_LINK_BASE_URL); + expect( + getEffectiveSettingsLinkBaseUrl({ settingsLinkBaseUrl: 'https://config.example/' }) + ).toBe('https://config.example'); + expect( + getEffectiveSettingsLinkBaseUrl( + { settingsLinkBaseUrl: 'https://config.example' }, + 'https://override.example/' + ) + ).toBe('https://override.example'); + }); + + it('parses settings permalinks from the same app origin only', () => { + expect( + parseSettingsPermalink( + 'https://app.example', + 'https://app.example/settings/appearance/?focus=message-link-preview' + ) + ).toEqual({ section: 'appearance', focus: 'message-link-preview' }); + + expect( + parseSettingsPermalink('https://app.example', 'https://other.example/settings/appearance/') + ).toBeUndefined(); + expect( + parseSettingsPermalink('https://app.example', 'https://app.example/home/') + ).toBeUndefined(); + }); + + it('rejects a same-origin hash permalink that does not match the configured app base', () => { + expect( + parseSettingsPermalink( + 'https://app.example/#/app', + 'https://app.example/#/wrong/settings/appearance/?focus=message-link-preview' + ) + ).toBeUndefined(); + }); + + it('rejects a same-origin hash permalink that only shares the configured base as a prefix', () => { + expect( + parseSettingsPermalink( + 'https://app.example/#/app', + 'https://app.example/#/ap/settings/appearance/?focus=message-link-preview' + ) + ).toBeUndefined(); + }); + + it('normalizes focus id parts', () => { + expect(toSettingsFocusIdPart('@alice:example.org')).toBe('alice-example-org'); + expect(toSettingsFocusIdPart('DEVICE-123')).toBe('device-123'); + }); +}); diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts new file mode 100644 index 00000000..4e72526f --- /dev/null +++ b/src/app/features/settings/settingsLink.ts @@ -0,0 +1,86 @@ +import type { ClientConfig } from '$hooks/useClientConfig'; +import { getAppPathFromHref, getSettingsPath, withOriginBaseUrl } from '$pages/pathUtils'; +import { isSettingsSectionId, type SettingsSectionId } from './routes'; + +export type SettingsPermalink = { + section: SettingsSectionId; + focus?: string; +}; + +export const DEFAULT_SETTINGS_LINK_BASE_URL = 'https://app.sable.moe'; + +export const normalizeSettingsLinkBaseUrl = (value?: string | null): string | undefined => { + if (typeof value !== 'string') return undefined; + + const trimmed = value.trim(); + if (!trimmed) return undefined; + + try { + const url = new URL(trimmed); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return undefined; + } + + return url.toString().replace(/\/+$/, ''); + } catch { + return undefined; + } +}; + +export const getConfiguredSettingsLinkBaseUrl = ( + clientConfig: Pick +): string => + normalizeSettingsLinkBaseUrl(clientConfig.settingsLinkBaseUrl) ?? DEFAULT_SETTINGS_LINK_BASE_URL; + +export const getEffectiveSettingsLinkBaseUrl = ( + clientConfig: Pick, + override?: string +): string => + normalizeSettingsLinkBaseUrl(override) ?? getConfiguredSettingsLinkBaseUrl(clientConfig); + +export const buildSettingsPermalink = ( + baseUrl: string, + section: SettingsSectionId, + focus?: string +): string => withOriginBaseUrl(baseUrl, getSettingsPath(section, focus)); + +export const parseSettingsPermalink = ( + baseUrl: string, + href: string +): SettingsPermalink | undefined => { + try { + const base = new URL(baseUrl); + const target = new URL(href); + + if (base.origin !== target.origin) return undefined; + + if (base.hash) { + const baseHash = base.hash.replace(/\/+$/, ''); + if (!(target.hash === baseHash || target.hash.startsWith(`${baseHash}/`))) { + return undefined; + } + } + + const appPath = getAppPathFromHref(baseUrl, href); + if (!appPath.startsWith('/settings/')) return undefined; + + const [pathname, search = ''] = appPath.split('?'); + const sectionMatch = pathname.match(/^\/settings\/([^/]+)\/$/); + if (!sectionMatch) return undefined; + + const section = sectionMatch[1]; + if (!isSettingsSectionId(section)) return undefined; + + const focus = new URLSearchParams(search).get('focus') ?? undefined; + + return { section, focus }; + } catch { + return undefined; + } +}; + +export const toSettingsFocusIdPart = (value: string): string => + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); diff --git a/src/app/features/settings/styles.css.ts b/src/app/features/settings/styles.css.ts index 84d0a317..23067658 100644 --- a/src/app/features/settings/styles.css.ts +++ b/src/app/features/settings/styles.css.ts @@ -1,28 +1,14 @@ -import { keyframes, style } from '@vanilla-extract/css'; -import { color, config } from 'folds'; +import { style } from '@vanilla-extract/css'; +import { config } from 'folds'; +import { messageJumpHighlight } from '$components/message/layout/layout.css'; export const SequenceCardStyle = style({ padding: config.space.S300, }); -const focusPulse = keyframes({ - '0%': { - backgroundColor: 'transparent', - boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.Primary.ContainerLine}`, - }, - '20%': { - backgroundColor: `color-mix(in srgb, ${color.Primary.Container} 20%, transparent)`, - }, - '50%': { - backgroundColor: `color-mix(in srgb, ${color.Primary.Container} 8%, transparent)`, - }, - '100%': { - backgroundColor: 'transparent', - boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.Primary.ContainerLine}`, - }, +export const settingsHeader = style({ + paddingLeft: config.space.S300, + paddingRight: config.space.S200, }); -export const focusedSettingTile = style({ - borderRadius: config.radii.R400, - animation: `${focusPulse} 3s ease-in-out 1`, -}); +export const focusedSettingTile = messageJumpHighlight; diff --git a/src/app/features/settings/useSettingsFocus.ts b/src/app/features/settings/useSettingsFocus.ts index b301d209..98296652 100644 --- a/src/app/features/settings/useSettingsFocus.ts +++ b/src/app/features/settings/useSettingsFocus.ts @@ -2,6 +2,10 @@ import { useEffect, useRef } from 'react'; import { useSearchParams } from 'react-router-dom'; import { focusedSettingTile } from './styles.css'; +const focusedSettingTileClasses = focusedSettingTile.split(' ').filter(Boolean); +const getHighlightTarget = (target: HTMLElement): HTMLElement => + target.closest('[data-sequence-card="true"]') ?? target.parentElement ?? target; + export function useSettingsFocus() { const [searchParams, setSearchParams] = useSearchParams(); const focusId = searchParams.get('focus'); @@ -14,7 +18,7 @@ export function useSettingsFocus() { window.clearTimeout(timeoutRef.current); timeoutRef.current = undefined; } - activeTargetRef.current?.classList.remove(focusedSettingTile); + activeTargetRef.current?.classList.remove(...focusedSettingTileClasses); activeTargetRef.current = null; }, [] @@ -27,8 +31,10 @@ export function useSettingsFocus() { document.querySelector(`[data-settings-focus="${focusId}"]`); if (target) { - if (activeTargetRef.current && activeTargetRef.current !== target) { - activeTargetRef.current.classList.remove(focusedSettingTile); + const highlightTarget = getHighlightTarget(target); + + if (activeTargetRef.current && activeTargetRef.current !== highlightTarget) { + activeTargetRef.current.classList.remove(...focusedSettingTileClasses); } if (timeoutRef.current !== undefined) { window.clearTimeout(timeoutRef.current); @@ -36,12 +42,12 @@ export function useSettingsFocus() { } target.scrollIntoView?.({ block: 'center', behavior: 'smooth' }); - target.classList.add(focusedSettingTile); - activeTargetRef.current = target; + highlightTarget.classList.add(...focusedSettingTileClasses); + activeTargetRef.current = highlightTarget; timeoutRef.current = window.setTimeout(() => { - target.classList.remove(focusedSettingTile); - if (activeTargetRef.current === target) { + highlightTarget.classList.remove(...focusedSettingTileClasses); + if (activeTargetRef.current === highlightTarget) { activeTargetRef.current = null; } timeoutRef.current = undefined; diff --git a/src/app/features/settings/useSettingsLinkBaseUrl.ts b/src/app/features/settings/useSettingsLinkBaseUrl.ts new file mode 100644 index 00000000..15eb73a6 --- /dev/null +++ b/src/app/features/settings/useSettingsLinkBaseUrl.ts @@ -0,0 +1,15 @@ +import { useMemo } from 'react'; +import { useClientConfig } from '$hooks/useClientConfig'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { getEffectiveSettingsLinkBaseUrl } from './settingsLink'; + +export const useSettingsLinkBaseUrl = (): string => { + const clientConfig = useClientConfig(); + const [settingsLinkBaseUrlOverride] = useSetting(settingsAtom, 'settingsLinkBaseUrlOverride'); + + return useMemo( + () => getEffectiveSettingsLinkBaseUrl(clientConfig, settingsLinkBaseUrlOverride), + [clientConfig, settingsLinkBaseUrlOverride] + ); +}; diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts index 87685337..e523f15a 100644 --- a/src/app/hooks/useClientConfig.ts +++ b/src/app/hooks/useClientConfig.ts @@ -42,6 +42,7 @@ export type ClientConfig = { hashRouter?: HashRouterConfig; matrixToBaseUrl?: string; + settingsLinkBaseUrl?: string; }; const ClientConfigContext = createContext(null); diff --git a/src/app/hooks/useMentionClickHandler.test.tsx b/src/app/hooks/useMentionClickHandler.test.tsx new file mode 100644 index 00000000..55719bea --- /dev/null +++ b/src/app/hooks/useMentionClickHandler.test.tsx @@ -0,0 +1,63 @@ +import { render, fireEvent, renderHook } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useMentionClickHandler } from './useMentionClickHandler'; + +const { mockOpenSettings } = vi.hoisted(() => ({ + mockOpenSettings: vi.fn(), +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => ({ getRoom: vi.fn() }), +})); + +vi.mock('$hooks/useRoomNavigate', () => ({ + useRoomNavigate: () => ({ navigateRoom: vi.fn(), navigateSpace: vi.fn() }), +})); + +vi.mock('$hooks/useSpace', () => ({ + useSpaceOptionally: () => undefined, +})); + +vi.mock('$state/hooks/userRoomProfile', () => ({ + useOpenUserRoomProfile: () => vi.fn(), +})); + +vi.mock('$features/settings/useOpenSettings', () => ({ + useOpenSettings: () => mockOpenSettings, +})); + +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn(), +})); + +function Wrapper({ children }: { children: ReactNode }) { + return <>{children}; +} + +describe('useMentionClickHandler', () => { + beforeEach(() => { + mockOpenSettings.mockReset(); + }); + + it('routes settings permalinks through openSettings with section and focus', () => { + const { result } = renderHook(() => useMentionClickHandler('!room:example.org'), { + wrapper: Wrapper, + }); + + const { getByRole } = render( + + ); + + fireEvent.click(getByRole('button', { name: 'Open settings link' })); + + expect(mockOpenSettings).toHaveBeenCalledWith('appearance', 'message-link-preview'); + }); +}); diff --git a/src/app/hooks/useMentionClickHandler.ts b/src/app/hooks/useMentionClickHandler.ts index aadfb982..350b7c2e 100644 --- a/src/app/hooks/useMentionClickHandler.ts +++ b/src/app/hooks/useMentionClickHandler.ts @@ -3,6 +3,8 @@ import { useNavigate } from 'react-router-dom'; import { isRoomId, isUserId } from '$utils/matrix'; import { getHomeRoomPath, withSearchParam } from '$pages/pathUtils'; import { RoomSearchParams } from '$pages/paths'; +import { isSettingsSectionId } from '$features/settings/routes'; +import { useOpenSettings } from '$features/settings/useOpenSettings'; import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useMatrixClient } from './useMatrixClient'; import { useRoomNavigate } from './useRoomNavigate'; @@ -14,12 +16,20 @@ export const useMentionClickHandler = (roomId: string): ReactEventHandler = useCallback( (evt) => { evt.stopPropagation(); evt.preventDefault(); const target = evt.currentTarget; + const settingsSection = target.getAttribute('data-settings-link-section') || undefined; + if (isSettingsSectionId(settingsSection)) { + const settingsFocus = target.getAttribute('data-settings-link-focus') || undefined; + openSettings(settingsSection, settingsFocus); + return; + } + const mentionId = target.getAttribute('data-mention-id'); if (typeof mentionId !== 'string') return; @@ -40,7 +50,7 @@ export const useMentionClickHandler = (roomId: string): ReactEventHandler(path, { viaServers }) : path); }, - [mx, navigate, navigateRoom, navigateSpace, roomId, space, openProfile] + [mx, navigate, navigateRoom, navigateSpace, openProfile, openSettings, roomId, space] ); return handleClick; diff --git a/src/app/pages/App.tsx b/src/app/pages/App.tsx index 3ed43c51..60424b92 100644 --- a/src/app/pages/App.tsx +++ b/src/app/pages/App.tsx @@ -1,8 +1,8 @@ +import { lazy, Suspense } from 'react'; import { Provider as JotaiProvider } from 'jotai'; import { OverlayContainerProvider, PopOutContainerProvider, TooltipContainerProvider } from 'folds'; import { RouterProvider } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import * as Sentry from '@sentry/react'; import { ClientConfigLoader } from '$components/ClientConfigLoader'; @@ -14,12 +14,19 @@ import { ErrorPage } from '$components/DefaultErrorPage'; import { ConfigConfigError, ConfigConfigLoading } from './ConfigConfig'; import { FeatureCheck } from './FeatureCheck'; import { createRouter } from './Router'; +import { isReactQueryDevtoolsEnabled } from './reactQueryDevtoolsGate'; const queryClient = new QueryClient(); +const ReactQueryDevtools = lazy(async () => { + const { ReactQueryDevtools: Devtools } = await import('@tanstack/react-query-devtools'); + + return { default: Devtools }; +}); function App() { const screenSize = useScreenSize(); useCompositionEndTracking(); + const reactQueryDevtoolsEnabled = isReactQueryDevtoolsEnabled(); const portalContainer = document.getElementById('portalContainer') ?? undefined; @@ -51,7 +58,11 @@ function App() { - + {reactQueryDevtoolsEnabled && ( + + + + )} ); diff --git a/src/app/pages/client/ClientLayout.tsx b/src/app/pages/client/ClientLayout.tsx index 4bbd4068..b22abcb3 100644 --- a/src/app/pages/client/ClientLayout.tsx +++ b/src/app/pages/client/ClientLayout.tsx @@ -1,14 +1,24 @@ import { ReactNode } from 'react'; import { Box } from 'folds'; +import { matchPath, useLocation } from 'react-router-dom'; +import { useScreenSizeContext } from '$hooks/useScreenSize'; +import { SETTINGS_PATH } from '../paths'; +import { isShallowSettingsRoute } from './ClientRouteOutlet'; type ClientLayoutProps = { nav: ReactNode; children: ReactNode; }; export function ClientLayout({ nav, children }: ClientLayoutProps) { + const location = useLocation(); + const screenSize = useScreenSizeContext(); + const fullPageSettings = + Boolean(matchPath(SETTINGS_PATH, location.pathname)) && + !isShallowSettingsRoute(location.pathname, location.state, screenSize); + return ( - {nav} + {!fullPageSettings && {nav}} {children} ); diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index dc9bf984..26ac2f43 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -39,6 +39,7 @@ import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useInboxNotificationsSelected } from '$hooks/router/useInbox'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { registrationAtom } from '$state/serviceWorkerRegistration'; import { pendingNotificationAtom, inAppBannerAtom, activeSessionIdAtom } from '$state/sessions'; import { @@ -242,6 +243,7 @@ function MessageNotifications() { const clientStartTimeRef = useRef(Date.now()); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); + const appBaseUrl = useSettingsLinkBaseUrl(); const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); @@ -474,6 +476,7 @@ function MessageNotifications() { content.formatted_body ) { const htmlParserOpts = getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl: appBaseUrl, linkifyOpts: LINKIFY_OPTS, useAuthentication, nicknames: nicknamesRef.current, @@ -532,6 +535,7 @@ function MessageNotifications() { setInAppBanner, setPending, selectedRoomId, + appBaseUrl, useAuthentication, ]); diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index dc3d3529..61ae4096 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -81,6 +81,7 @@ import { UserAvatar } from '$components/user-avatar'; import { EncryptedContent } from '$features/room/message'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; +import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { BackRouteHandler } from '$components/BackRouteHandler'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -204,6 +205,7 @@ const useNotificationTimeline = ( type RoomNotificationsGroupProps = { room: Room; + appBaseUrl: string; notifications: INotification[]; mediaAutoLoad?: boolean; urlPreview?: boolean; @@ -215,6 +217,7 @@ type RoomNotificationsGroupProps = { }; function RoomNotificationsGroupComp({ room, + appBaseUrl, notifications, mediaAutoLoad, urlPreview, @@ -245,28 +248,41 @@ function RoomNotificationsGroupComp({ const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, - render: factoryRenderLinkifyWithMention((href) => - renderMatrixMention( - mx, - room.roomId, - href, - makeMentionCustomProps(mentionClickHandler), - nicknames - ) + render: factoryRenderLinkifyWithMention( + appBaseUrl, + (href) => + renderMatrixMention( + mx, + room.roomId, + href, + makeMentionCustomProps(mentionClickHandler), + nicknames + ), + mentionClickHandler ), }), - [mx, room, mentionClickHandler, nicknames] + [appBaseUrl, mx, room, mentionClickHandler, nicknames] ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { + settingsLinkBaseUrl: appBaseUrl, linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, nicknames, }), - [mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication, nicknames] + [ + appBaseUrl, + mx, + room, + linkifyOpts, + mentionClickHandler, + spoilerClickHandler, + useAuthentication, + nicknames, + ] ); const renderMatrixEvent = useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]>( @@ -582,6 +598,7 @@ export function Notifications() { const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); const screenSize = useScreenSizeContext(); const mDirects = useAtomValue(mDirectAtom); + const appBaseUrl = useSettingsLinkBaseUrl(); const { navigateRoom } = useRoomNavigate(); const [searchParams, setSearchParams] = useSearchParams(); @@ -726,6 +743,7 @@ export function Notifications() { > { + afterEach(() => { + localStorage.clear(); + vi.unstubAllEnvs(); + }); + + it('is disabled by default even in development', () => { + vi.stubEnv('VITE_ENABLE_REACT_QUERY_DEVTOOLS', 'false'); + + expect(isReactQueryDevtoolsEnabled()).toBe(false); + }); + + it('is enabled by the env variable', () => { + vi.stubEnv('VITE_ENABLE_REACT_QUERY_DEVTOOLS', 'true'); + + expect(isReactQueryDevtoolsEnabled()).toBe(true); + }); + + it('is enabled by the local storage flag', () => { + vi.stubEnv('VITE_ENABLE_REACT_QUERY_DEVTOOLS', 'false'); + localStorage.setItem(REACT_QUERY_DEVTOOLS_LOCAL_STORAGE_KEY, '1'); + + expect(isReactQueryDevtoolsEnabled()).toBe(true); + }); +}); diff --git a/src/app/pages/reactQueryDevtoolsGate.ts b/src/app/pages/reactQueryDevtoolsGate.ts new file mode 100644 index 00000000..aa77ba2e --- /dev/null +++ b/src/app/pages/reactQueryDevtoolsGate.ts @@ -0,0 +1,5 @@ +export const REACT_QUERY_DEVTOOLS_LOCAL_STORAGE_KEY = 'sable_react_query_devtools'; + +export const isReactQueryDevtoolsEnabled = (): boolean => + import.meta.env.VITE_ENABLE_REACT_QUERY_DEVTOOLS === 'true' || + localStorage.getItem(REACT_QUERY_DEVTOOLS_LOCAL_STORAGE_KEY) === '1'; diff --git a/src/app/plugins/react-custom-html-parser.test.tsx b/src/app/plugins/react-custom-html-parser.test.tsx new file mode 100644 index 00000000..f1a66396 --- /dev/null +++ b/src/app/plugins/react-custom-html-parser.test.tsx @@ -0,0 +1,98 @@ +import { render, screen } from '@testing-library/react'; +import parse from 'html-react-parser'; +import { describe, expect, it } from 'vitest'; +import * as customHtmlCss from '$styles/CustomHtml.css'; +import { + LINKIFY_OPTS, + factoryRenderLinkifyWithMention, + getReactCustomHtmlParser, + makeMentionCustomProps, + renderMatrixMention, +} from './react-custom-html-parser'; + +const settingsLinkBaseUrl = 'https://app.example'; + +const mockMx = { + getUserId: () => '@alice:example.org', + getRoom: () => undefined, +}; + +function Subject({ body }: { body: string }) { + const options = getReactCustomHtmlParser(mockMx as never, undefined, { + settingsLinkBaseUrl, + linkifyOpts: LINKIFY_OPTS, + handleMentionClick: undefined, + }); + + return
{parse(body, options)}
; +} + +describe('react custom html parser', () => { + it('renders same-origin raw settings permalinks as mention-style chips through the factory link render path', () => { + const renderLink = factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + () => undefined, + undefined + ) as (ir: never) => JSX.Element; + + render( +
+ {renderLink({ + tagName: 'a', + attributes: { + href: 'https://app.example/settings/appearance/?focus=message-link-preview', + }, + content: 'https://app.example/settings/appearance/?focus=message-link-preview', + } as never)} +
+ ); + + const link = screen.getByRole('link', { name: 'Appearance / Message Link Preview' }); + expect(link).toHaveAttribute('data-settings-link-section', 'appearance'); + expect(link).toHaveAttribute('data-settings-link-focus', 'message-link-preview'); + expect(link.className).toContain(customHtmlCss.Mention({})); + expect(link.className).toContain(customHtmlCss.SettingsMention); + expect(link).not.toHaveTextContent('Settings:'); + }); + + it('renders same-origin settings permalinks as internal app links with settings metadata', () => { + render( + + ); + + const link = screen.getByRole('link', { name: 'Appearance' }); + expect(link).toHaveAttribute( + 'href', + 'https://app.example/settings/appearance/?focus=message-link-preview' + ); + expect(link).toHaveAttribute('data-settings-link-section', 'appearance'); + expect(link).toHaveAttribute('data-settings-link-focus', 'message-link-preview'); + expect(link).not.toHaveAttribute('data-mention-id'); + expect(link.className).toContain(customHtmlCss.Mention({})); + expect(link.className).toContain(customHtmlCss.SettingsMention); + }); + + it('renders matrix message permalinks with an icon instead of the Message prefix', () => { + render( +
+ {renderMatrixMention( + { + getUserId: () => '@alice:example.org', + getRoom: () => ({ roomId: '!room:example.org', name: 'Lobby' }), + } as never, + undefined, + 'https://matrix.to/#/!room:example.org/$event123', + makeMentionCustomProps(undefined) + )} +
+ ); + + const link = screen.getByRole('link', { name: '#Lobby' }); + expect(link).toHaveAttribute('data-mention-id', '!room:example.org'); + expect(link).toHaveAttribute('data-mention-event-id', '$event123'); + expect(link.className).toContain(customHtmlCss.Mention({})); + expect(link.className).toContain(customHtmlCss.SettingsMention); + expect(link).not.toHaveTextContent('Message:'); + expect(link.querySelector('[aria-hidden="true"]')).not.toBeNull(); + }); +}); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 1a351572..efb8991b 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -36,6 +36,8 @@ import { findAndReplace } from '$utils/findAndReplace'; import { onEnterOrSpace } from '$utils/keyboard'; import { copyToClipboard } from '$utils/dom'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { parseSettingsPermalink } from '$features/settings/settingsLink'; +import { settingsSections } from '$features/settings/routes'; import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import { parseMatrixToRoom, @@ -138,21 +140,26 @@ export const renderMatrixMention = ( const mentionRoom = mx.getRoom( isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias ); + const fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias; return ( - {customProps.children - ? customProps.children - : `Message: ${mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias}`} + + {customProps.children ? customProps.children : fallbackContent} ); } @@ -160,8 +167,80 @@ export const renderMatrixMention = ( return undefined; }; +const settingsSectionLabel = Object.fromEntries( + settingsSections.map((section) => [section.id, section.label]) +) as Record<(typeof settingsSections)[number]['id'], string>; + +const humanizeSettingsPermalinkPart = (value: string): string => + value + .split(/[^a-zA-Z0-9]+/) + .filter(Boolean) + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(' '); + +const getSettingsPermalinkLabel = ( + section: keyof typeof settingsSectionLabel, + focus?: string +): string => { + const sectionLabel = settingsSectionLabel[section]; + const focusLabel = focus ? humanizeSettingsPermalinkPart(focus) : undefined; + + return focusLabel ? `${sectionLabel} / ${focusLabel}` : sectionLabel; +}; + +const getSettingsPermalinkChildren = ({ + href, + section, + focus, + content, + fallbackChildren, +}: { + href: string; + section: keyof typeof settingsSectionLabel; + focus?: string; + content?: string; + fallbackChildren?: ReactNode; +}): ReactNode => { + if (!content || content === href || content === safeDecodeUrl(href)) { + return getSettingsPermalinkLabel(section, focus); + } + + return fallbackChildren ?? content; +}; + +const renderSettingsPermalink = ({ + href, + section, + focus, + handleMentionClick, + content, + fallbackChildren, +}: { + href: string; + section: keyof typeof settingsSectionLabel; + focus?: string; + handleMentionClick?: ReactEventHandler; + content?: string; + fallbackChildren?: ReactNode; +}) => ( + + + {getSettingsPermalinkChildren({ href, section, focus, content, fallbackChildren })} + +); + export const factoryRenderLinkifyWithMention = ( - mentionRender: (href: string) => JSX.Element | undefined + settingsLinkBaseUrl: string, + mentionRender: (href: string) => JSX.Element | undefined, + handleMentionClick?: ReactEventHandler ): OptFn<(ir: IntermediateRepresentation) => any> => { const renderLink: OptFn<(ir: IntermediateRepresentation) => any> = ({ tagName, @@ -176,6 +255,21 @@ export const factoryRenderLinkifyWithMention = ( if (mention) return mention; } + if (tagName === 'a' && decodedHref) { + const settingsPermalink = parseSettingsPermalink(settingsLinkBaseUrl, decodedHref); + if (settingsPermalink) { + const { section, focus } = settingsPermalink; + return renderSettingsPermalink({ + href: decodedHref, + section, + focus, + handleMentionClick, + content, + fallbackChildren: content, + }); + } + } + return {content}; }; @@ -344,6 +438,7 @@ export const getReactCustomHtmlParser = ( mx: MatrixClient, roomId: string | undefined, params: { + settingsLinkBaseUrl: string; linkifyOpts: LinkifyOpts; highlightRegex?: RegExp; handleSpoilerClick?: ReactEventHandler; @@ -489,23 +584,41 @@ export const getReactCustomHtmlParser = ( if (name === 'a' && typeof props.href === 'string') { const encodedHref = props.href; const decodedHref = encodedHref && safeDecodeUrl(encodedHref); - if (!decodedHref || !testMatrixTo(decodedHref)) { - return undefined; - } + const renderedChildren = renderChildren(); const content = children.find((child) => !(child instanceof DOMText)) ? undefined : children.map((c) => (c instanceof DOMText ? c.data : '')).join(); - const mention = renderMatrixMention( - mx, - roomId, - safeDecodeUrl(props.href), - makeMentionCustomProps(params.handleMentionClick, content), - params.nicknames - ); + if (decodedHref && testMatrixTo(decodedHref)) { + const mention = renderMatrixMention( + mx, + roomId, + decodedHref, + makeMentionCustomProps(params.handleMentionClick, content), + params.nicknames + ); - if (mention) return mention; + if (mention) return mention; + } + + if (decodedHref) { + const settingsPermalink = parseSettingsPermalink( + params.settingsLinkBaseUrl, + decodedHref + ); + if (settingsPermalink) { + const { section, focus } = settingsPermalink; + return renderSettingsPermalink({ + href: decodedHref, + section, + focus, + handleMentionClick: params.handleMentionClick, + content, + fallbackChildren: renderedChildren, + }); + } + } } if (name === 'span' && 'data-mx-spoiler' in props) { diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index cfa53386..0b4bf15d 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -69,6 +69,7 @@ export interface Settings { developerTools: boolean; enableMSC4268CMD: boolean; settingsSyncEnabled: boolean; + settingsLinkBaseUrlOverride?: string; // Cosmetics! jumboEmojiSize: JumboEmojiSize; @@ -162,6 +163,7 @@ const defaultSettings: Settings = { developerTools: false, settingsSyncEnabled: false, + settingsLinkBaseUrlOverride: undefined, // Cosmetics! jumboEmojiSize: 'normal', diff --git a/src/app/styles/CustomHtml.css.ts b/src/app/styles/CustomHtml.css.ts index 6ff53d9d..2102ea4e 100644 --- a/src/app/styles/CustomHtml.css.ts +++ b/src/app/styles/CustomHtml.css.ts @@ -171,6 +171,18 @@ export const Mention = recipe({ }, }); +export const SettingsMention = style({ + display: 'inline-flex', + alignItems: 'center', + gap: config.space.S100, + padding: `0 ${config.space.S100}`, +}); + +export const SettingsMentionIcon = style({ + display: 'inline-flex', + flexShrink: 0, +}); + export const Command = recipe({ base: [ DefaultReset, diff --git a/src/app/utils/dom.ts b/src/app/utils/dom.ts index 12fc93e7..e51bdfed 100644 --- a/src/app/utils/dom.ts +++ b/src/app/utils/dom.ts @@ -187,22 +187,35 @@ export const scrollToBottom = (scrollEl: HTMLElement, behavior?: 'auto' | 'insta }); }; -export const copyToClipboard = (text: string) => { +export const copyToClipboard = async (text: string): Promise => { if (navigator.clipboard) { - navigator.clipboard.writeText(text); - } else { - const host = document.body; - const copyInput = document.createElement('input'); - copyInput.style.position = 'fixed'; - copyInput.style.opacity = '0'; - copyInput.value = text; - host.append(copyInput); - - copyInput.select(); - copyInput.setSelectionRange(0, 99999); - document.execCommand('Copy'); - copyInput.remove(); + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + return false; + } } + + const host = document.body; + const copyInput = document.createElement('input'); + copyInput.style.position = 'fixed'; + copyInput.style.opacity = '0'; + copyInput.value = text; + host.append(copyInput); + + copyInput.select(); + copyInput.setSelectionRange(0, 99999); + + let copied = false; + try { + copied = document.execCommand('Copy'); + } catch { + copied = false; + } + + copyInput.remove(); + return copied; }; export const setFavicon = (url: string): void => { diff --git a/src/app/utils/settingsSync.test.ts b/src/app/utils/settingsSync.test.ts index 66c4f527..fb5ad6c8 100644 --- a/src/app/utils/settingsSync.test.ts +++ b/src/app/utils/settingsSync.test.ts @@ -30,6 +30,7 @@ describe('NON_SYNCABLE_KEYS', () => { 'isPeopleDrawer', 'isWidgetDrawer', 'memberSortFilterIndex', + 'settingsLinkBaseUrlOverride', 'developerTools', 'settingsSyncEnabled', ] as const; diff --git a/src/app/utils/settingsSync.ts b/src/app/utils/settingsSync.ts index a154ff92..0f6b2588 100644 --- a/src/app/utils/settingsSync.ts +++ b/src/app/utils/settingsSync.ts @@ -14,6 +14,7 @@ export const NON_SYNCABLE_KEYS = new Set([ 'isPeopleDrawer', 'isWidgetDrawer', 'memberSortFilterIndex', + 'settingsLinkBaseUrlOverride', // Developer / diagnostic 'developerTools', // Sync toggle itself must never be uploaded (it's device-local)