From ddb927e3de7f9fbfcdb72f1600b09fbb5c84afdf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:02:02 +0100 Subject: [PATCH 1/7] teardown(R2.1): collapse PhoneHit sprawl into global IconButton rule and delete AST guard suite --- src/app/components/AccountDataEditor.tsx | 3 +- src/app/components/BackupRestore.tsx | 2 - src/app/components/DeviceVerification.tsx | 3 +- .../components/DeviceVerificationSetup.tsx | 5 +- src/app/components/Pdf-viewer/PdfViewer.tsx | 5 +- src/app/components/UIAFlowOverlay.tsx | 2 - src/app/components/editor/Editor.css.ts | 14 +- src/app/components/editor/Toolbar.tsx | 9 - .../emoji-board/components/Sidebar.tsx | 2 - .../components/event-readers/EventReaders.tsx | 3 +- .../components/image-editor/ImageEditor.tsx | 3 +- .../image-pack-view/ImagePackView.tsx | 3 +- .../components/image-viewer/ImageViewer.tsx | 5 +- .../invite-user-prompt/InviteUserPrompt.tsx | 3 +- .../join-address-prompt/JoinAddressPrompt.tsx | 3 +- .../leave-room-prompt/LeaveRoomPrompt.tsx | 3 +- .../leave-space-prompt/LeaveSpacePrompt.tsx | 3 +- src/app/components/message/FileHeader.tsx | 2 - src/app/components/message/Reaction.css.ts | 2 +- .../message/content/AudioContent.tsx | 2 - .../password-input/PasswordInput.tsx | 2 - .../room-topic-viewer/RoomTopicViewer.tsx | 3 +- src/app/components/text-viewer/TextViewer.tsx | 3 +- .../components/uia-stages/PasswordStage.tsx | 3 +- src/app/components/uia-stages/SSOStage.tsx | 3 +- .../upload-card/CompactUploadCardRenderer.tsx | 2 - .../upload-card/UploadCardRenderer.tsx | 2 - .../components/url-preview/UrlPreviewCard.tsx | 12 +- src/app/components/user-profile/PowerChip.tsx | 5 +- src/app/features/add-existing/AddExisting.tsx | 3 +- src/app/features/call-status/CallControl.tsx | 5 - src/app/features/call/CallControls.tsx | 2 - src/app/features/call/Controls.tsx | 6 - .../developer-tools/DevelopTools.tsx | 3 +- .../developer-tools/SendRoomEvent.tsx | 3 +- .../developer-tools/StateEventEditor.tsx | 3 +- .../emojis-stickers/EmojisStickers.tsx | 3 +- .../emojis-stickers/RoomPacks.tsx | 3 - .../general/RoomEncryption.tsx | 2 - .../common-settings/general/RoomUpgrade.tsx | 3 +- .../common-settings/members/Members.tsx | 4 +- .../permissions/PowersEditor.tsx | 3 +- .../features/create-room/CreateRoomModal.tsx | 3 +- .../create-space/CreateSpaceModal.tsx | 3 +- src/app/features/desk/Desk.tsx | 2 - .../JoinBeforeNavigate.tsx | 3 +- src/app/features/lobby/HierarchyItemMenu.tsx | 2 - src/app/features/lobby/Lobby.tsx | 2 - src/app/features/lobby/LobbyHeader.tsx | 4 +- .../features/message-search/MessageSearch.tsx | 2 - src/app/features/room-nav/RoomNavItem.tsx | 3 - .../features/room-settings/RoomSettings.tsx | 3 +- .../room-settings/general/General.tsx | 3 +- .../room-settings/permissions/Permissions.tsx | 3 +- src/app/features/room/CallChatView.tsx | 2 - src/app/features/room/MembersDrawer.tsx | 3 - src/app/features/room/RoomInput.tsx | 7 - src/app/features/room/RoomViewHeader.tsx | 8 +- src/app/features/room/RoomViewTyping.tsx | 2 - .../features/room/jump-to-time/JumpToTime.tsx | 3 +- src/app/features/room/message/Message.tsx | 11 +- .../features/room/message/MessageEditor.tsx | 3 - src/app/features/room/message/styles.css.ts | 8 +- .../room/reaction-viewer/ReactionViewer.tsx | 3 +- .../room/room-pin-menu/RoomPinMenu.tsx | 4 +- src/app/features/scene/SceneViewEntry.tsx | 2 - src/app/features/scene/SceneViewHost.test.tsx | 4 +- src/app/features/scene/SceneViewHost.tsx | 3 +- src/app/features/scene/view/PlaceSubmenu.tsx | 3 - .../features/scene/view/SceneView.test.tsx | 8 +- src/app/features/scene/view/SceneView.tsx | 4 +- src/app/features/settings/Settings.tsx | 3 +- src/app/features/settings/about/About.tsx | 3 +- src/app/features/settings/account/Account.tsx | 3 +- .../settings/account/IgnoredUserList.tsx | 2 - src/app/features/settings/account/Profile.tsx | 3 - .../settings/developer-tools/DevelopTools.tsx | 3 +- .../features/settings/devices/DeviceTile.tsx | 2 - src/app/features/settings/devices/Devices.tsx | 3 +- .../settings/devices/Verification.tsx | 2 - .../emojis-stickers/EmojisStickers.tsx | 3 +- .../settings/emojis-stickers/GlobalPacks.tsx | 3 - src/app/features/settings/general/General.tsx | 5 +- .../notifications/KeywordMessages.tsx | 3 - .../settings/notifications/Notifications.tsx | 3 +- .../features/space-settings/SpaceSettings.tsx | 3 +- .../space-settings/general/General.tsx | 3 +- .../permissions/Permissions.tsx | 3 +- src/app/pages/auth/ServerPicker.tsx | 2 - .../pages/auth/login/PasswordLoginForm.tsx | 2 - src/app/pages/client/ClientRoot.tsx | 2 - src/app/pages/client/direct/DirectCreate.tsx | 3 +- src/app/pages/client/explore/Explore.tsx | 2 - src/app/pages/client/explore/Featured.tsx | 3 +- src/app/pages/client/explore/Server.tsx | 3 +- src/app/pages/client/home/CreateRoom.tsx | 3 +- src/app/pages/client/home/Search.tsx | 3 +- src/app/pages/client/inbox/Invites.tsx | 3 +- src/app/pages/client/inbox/Notifications.tsx | 4 +- src/app/pages/client/space/Search.tsx | 3 +- src/app/phoneGlyph.test.ts | 59 +-- src/app/phoneHit.call.test.ts | 15 - src/app/phoneHit.commonSettings.test.ts | 26 -- src/app/phoneHit.content.test.ts | 26 -- src/app/phoneHit.coverage.test.ts | 80 ---- src/app/phoneHit.dialogs.test.ts | 28 -- src/app/phoneHit.editor.test.ts | 119 ------ src/app/phoneHit.pages.test.ts | 29 -- src/app/phoneHit.roomSpace.test.ts | 28 -- src/app/phoneHit.settingsA.test.ts | 29 -- src/app/phoneHit.settingsB.test.ts | 21 - src/app/phoneHit.viewers.test.ts | 27 -- src/app/phoneHitTestKit.test.ts | 276 ------------- src/app/phoneHitTestKit.ts | 384 ------------------ src/app/phoneTapTargets.test.ts | 225 ---------- src/app/plugins/react-custom-html-parser.tsx | 2 - src/app/styles/PhoneHit.css.ts | 68 ---- src/phoneGlyph.css.ts | 27 +- 118 files changed, 114 insertions(+), 1704 deletions(-) delete mode 100644 src/app/phoneHit.call.test.ts delete mode 100644 src/app/phoneHit.commonSettings.test.ts delete mode 100644 src/app/phoneHit.content.test.ts delete mode 100644 src/app/phoneHit.coverage.test.ts delete mode 100644 src/app/phoneHit.dialogs.test.ts delete mode 100644 src/app/phoneHit.editor.test.ts delete mode 100644 src/app/phoneHit.pages.test.ts delete mode 100644 src/app/phoneHit.roomSpace.test.ts delete mode 100644 src/app/phoneHit.settingsA.test.ts delete mode 100644 src/app/phoneHit.settingsB.test.ts delete mode 100644 src/app/phoneHit.viewers.test.ts delete mode 100644 src/app/phoneHitTestKit.test.ts delete mode 100644 src/app/phoneHitTestKit.ts delete mode 100644 src/app/phoneTapTargets.test.ts delete mode 100644 src/app/styles/PhoneHit.css.ts diff --git a/src/app/components/AccountDataEditor.tsx b/src/app/components/AccountDataEditor.tsx index 8c28b935..2dbaf1f1 100644 --- a/src/app/components/AccountDataEditor.tsx +++ b/src/app/components/AccountDataEditor.tsx @@ -16,7 +16,6 @@ import { } from 'folds'; import { MatrixError } from 'matrix-js-sdk'; import { Cursor } from '../plugins/text-area'; -import { PhoneHit } from '../styles/PhoneHit.css'; import { syntaxErrorPosition } from '../utils/dom'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { Page, PageHeader } from './page'; @@ -295,7 +294,7 @@ export function AccountDataEditor({ - + diff --git a/src/app/components/BackupRestore.tsx b/src/app/components/BackupRestore.tsx index 57a18674..068f437b 100644 --- a/src/app/components/BackupRestore.tsx +++ b/src/app/components/BackupRestore.tsx @@ -30,7 +30,6 @@ import { } from '../hooks/useKeyBackup'; import { stopPropagation } from '../utils/keyboard'; import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification'; -import { PhoneHit } from '../styles/PhoneHit.css'; type BackupStatusProps = { enabled: boolean; @@ -178,7 +177,6 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) { )} Device Verification - + diff --git a/src/app/components/DeviceVerificationSetup.tsx b/src/app/components/DeviceVerificationSetup.tsx index 68f42221..433fa6a1 100644 --- a/src/app/components/DeviceVerificationSetup.tsx +++ b/src/app/components/DeviceVerificationSetup.tsx @@ -25,7 +25,6 @@ import { ActionUIA, ActionUIAFlowsLoader } from './ActionUIA'; import { useMatrixClient } from '../hooks/useMatrixClient'; import { useAlive } from '../hooks/useAlive'; import { UseStateProvider } from './UseStateProvider'; -import { PhoneHit } from '../styles/PhoneHit.css'; type UIACallback = ( authDict: AuthDict | null @@ -302,7 +301,7 @@ export const DeviceVerificationSetup = forwardRef Setup Device Verification - + @@ -337,7 +336,7 @@ export const DeviceVerificationReset = forwardRef Reset Device Verification - + diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index d0e5f715..9c7fd980 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -27,7 +27,6 @@ import { AsyncStatus } from '../../hooks/useAsyncCallback'; import { useZoom } from '../../hooks/useZoom'; import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css'; export type PdfViewerProps = { name: string; @@ -109,7 +108,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
- + @@ -118,7 +117,6 @@ export const PdfViewer = as<'div', PdfViewerProps>( ( {Math.round(zoom * 100)}% 1 ? 'Success' : 'SurfaceVariant'} outlined={zoom > 1} size="300" diff --git a/src/app/components/UIAFlowOverlay.tsx b/src/app/components/UIAFlowOverlay.tsx index 49e1d821..a2bdd1b8 100644 --- a/src/app/components/UIAFlowOverlay.tsx +++ b/src/app/components/UIAFlowOverlay.tsx @@ -13,7 +13,6 @@ import { IconButton, } from 'folds'; import FocusTrap from 'focus-trap-react'; -import { PhoneHit } from '../styles/PhoneHit.css'; export type UIAFlowOverlayProps = { currentStep: number; @@ -54,7 +53,6 @@ export function UIAFlowOverlay({ > {(anchorRef) => ( {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( handleMenuSelect(1)} size="400" @@ -182,7 +178,6 @@ export function HeadingBlockButton() { > {(triggerRef) => ( handleMenuSelect(2)} size="400" @@ -198,7 +193,6 @@ export function HeadingBlockButton() { > {(triggerRef) => ( handleMenuSelect(3)} size="400" @@ -214,7 +208,6 @@ export function HeadingBlockButton() { } > {(triggerRef) => ( {(triggerRef) => ( setIsMarkdown(!isMarkdown)} diff --git a/src/app/components/emoji-board/components/Sidebar.tsx b/src/app/components/emoji-board/components/Sidebar.tsx index d2d5f197..de22b483 100644 --- a/src/app/components/emoji-board/components/Sidebar.tsx +++ b/src/app/components/emoji-board/components/Sidebar.tsx @@ -14,7 +14,6 @@ import { } from 'folds'; import classNames from 'classnames'; import * as css from './styles.css'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function Sidebar({ children }: { children: ReactNode }) { return ( @@ -69,7 +68,6 @@ function SidebarBtn({ > {(ref) => ( ( Seen by - +
diff --git a/src/app/components/image-editor/ImageEditor.tsx b/src/app/components/image-editor/ImageEditor.tsx index 0f072bb0..1ec474e8 100644 --- a/src/app/components/image-editor/ImageEditor.tsx +++ b/src/app/components/image-editor/ImageEditor.tsx @@ -2,7 +2,6 @@ import React from 'react'; import classNames from 'classnames'; import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds'; import * as css from './ImageEditor.css'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export type ImageEditorProps = { name: string; @@ -25,7 +24,7 @@ export const ImageEditor = as<'div', ImageEditorProps>( >
- + diff --git a/src/app/components/image-pack-view/ImagePackView.tsx b/src/app/components/image-pack-view/ImagePackView.tsx index 15b1cd08..ab81d503 100644 --- a/src/app/components/image-pack-view/ImagePackView.tsx +++ b/src/app/components/image-pack-view/ImagePackView.tsx @@ -1,7 +1,6 @@ import React from 'react'; import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds'; import { PackAddress } from '../../plugins/custom-emoji'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { Page, PageHeader, PageContent } from '../page'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { RoomImagePack } from './RoomImagePack'; @@ -30,7 +29,7 @@ export function ImagePackView({ address, requestClose }: ImagePackViewProps) { - + diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index 4d2d7694..4956a7b6 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -7,7 +7,6 @@ import * as css from './ImageViewer.css'; import { useZoom } from '../../hooks/useZoom'; import { usePan } from '../../hooks/usePan'; import { downloadMedia } from '../../utils/matrix'; -import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css'; export type ImageViewerProps = { alt: string; @@ -34,7 +33,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( >
- + @@ -43,7 +42,6 @@ export const ImageViewer = as<'div', ImageViewerProps>( ( {Math.round(zoom * 100)}% 1 ? 'Success' : 'SurfaceVariant'} outlined={zoom > 1} size="300" diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index a503fe13..ddac0576 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -42,7 +42,6 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { BreakWord } from '../../styles/Text.css'; import { useAlive } from '../../hooks/useAlive'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, @@ -174,7 +173,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { - + diff --git a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx index ffd5241c..50a89418 100644 --- a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx +++ b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx @@ -20,7 +20,6 @@ import { stopPropagation } from '../../utils/keyboard'; import { isRoomAlias, isRoomId } from '../../utils/matrix'; import { parseMatrixToRoom, parseMatrixToRoomEvent, testMatrixTo } from '../../plugins/matrix-to'; import { tryDecodeURIComponent } from '../../utils/dom'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type JoinAddressProps = { onOpen: (roomIdOrAlias: string, via?: string[], eventId?: string) => void; @@ -83,7 +82,7 @@ export function JoinAddressPrompt({ onOpen, onCancel }: JoinAddressProps) { Join with Address - +
diff --git a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx index 832dd59d..217491e6 100644 --- a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx +++ b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx @@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LeaveRoomPromptProps = { roomId: string; @@ -69,7 +68,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro Leave Room - +
diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx index 6c75ef99..8709b942 100644 --- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx +++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx @@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LeaveSpacePromptProps = { roomId: string; @@ -69,7 +68,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP Leave Space - + diff --git a/src/app/components/message/FileHeader.tsx b/src/app/components/message/FileHeader.tsx index 41cef5f4..2ffc9ec4 100644 --- a/src/app/components/message/FileHeader.tsx +++ b/src/app/components/message/FileHeader.tsx @@ -2,7 +2,6 @@ import { Badge, Box, Icon, IconButton, Icons, Spinner, Text, as, toRem } from 'f import React, { ReactNode, useCallback } from 'react'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import FileSaver from 'file-saver'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { mimeTypeToExt } from '../../utils/mimeTypes'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; @@ -49,7 +48,6 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow variant={hasError ? 'Critical' : 'SurfaceVariant'} size="300" radii="300" - className={PhoneHit} > {downloading ? ( diff --git a/src/app/components/message/Reaction.css.ts b/src/app/components/message/Reaction.css.ts index 08003f0e..6c9052ec 100644 --- a/src/app/components/message/Reaction.css.ts +++ b/src/app/components/message/Reaction.css.ts @@ -1,7 +1,7 @@ import { createVar, style } from '@vanilla-extract/css'; import { DefaultReset, FocusOutline, color, config, toRem } from 'folds'; import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize'; -import { PHONE_TAP } from '../../styles/PhoneHit.css'; +import { PHONE_TAP } from '../../../phoneGlyph.css'; const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; const Container = createVar(); diff --git a/src/app/components/message/content/AudioContent.tsx b/src/app/components/message/content/AudioContent.tsx index 94132cea..478486a4 100644 --- a/src/app/components/message/content/AudioContent.tsx +++ b/src/app/components/message/content/AudioContent.tsx @@ -3,7 +3,6 @@ import React, { ReactNode, useCallback, useRef, useState } from 'react'; import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { Range } from 'react-range'; -import { PhoneHitSpread24 } from '../../../styles/PhoneHit.css'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { IAudioInfo } from '../../../../types/matrix/common'; @@ -160,7 +159,6 @@ export function AudioContent({ variant="SurfaceVariant" size="300" radii="Pill" - className={PhoneHitSpread24} onClick={() => setMute(!mute)} aria-pressed={mute} > diff --git a/src/app/components/password-input/PasswordInput.tsx b/src/app/components/password-input/PasswordInput.tsx index 6aa0d4f3..4ffe0d83 100644 --- a/src/app/components/password-input/PasswordInput.tsx +++ b/src/app/components/password-input/PasswordInput.tsx @@ -1,7 +1,6 @@ import React, { ComponentProps, forwardRef } from 'react'; import { Icon, IconButton, Input, config, Icons } from 'folds'; import { UseStateProvider } from '../UseStateProvider'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type PasswordInputProps = Omit, 'type' | 'size'> & { size: '400' | '500'; @@ -24,7 +23,6 @@ export const PasswordInput = forwardRef( <> {after} setVisible(!visible)} type="button" variant={visible ? 'Warning' : variant} diff --git a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx index 0d091e7e..52128772 100644 --- a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx +++ b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx @@ -4,7 +4,6 @@ import classNames from 'classnames'; import Linkify from 'linkify-react'; import * as css from './style.css'; import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export const RoomTopicViewer = as< 'div', @@ -27,7 +26,7 @@ export const RoomTopicViewer = as< {name}
- + diff --git a/src/app/components/text-viewer/TextViewer.tsx b/src/app/components/text-viewer/TextViewer.tsx index e9e150b5..ec4ed0a5 100644 --- a/src/app/components/text-viewer/TextViewer.tsx +++ b/src/app/components/text-viewer/TextViewer.tsx @@ -5,7 +5,6 @@ import { Box, Chip, Header, Icon, IconButton, Icons, Scroll, Text, as } from 'fo import { ErrorBoundary } from 'react-error-boundary'; import * as css from './TextViewer.css'; import { copyToClipboard } from '../../utils/dom'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism')); @@ -54,7 +53,7 @@ export const TextViewer = as<'div', TextViewerProps>( >
- + diff --git a/src/app/components/uia-stages/PasswordStage.tsx b/src/app/components/uia-stages/PasswordStage.tsx index a7ca2d06..0164cae6 100644 --- a/src/app/components/uia-stages/PasswordStage.tsx +++ b/src/app/components/uia-stages/PasswordStage.tsx @@ -4,7 +4,6 @@ import { AuthType } from 'matrix-js-sdk'; import { StageComponentProps } from './types'; import { ErrorCode } from '../../cs-errorcode'; import { PasswordInput } from '../password-input'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function PasswordStage({ stageData, @@ -46,7 +45,7 @@ export function PasswordStage({ Account Password - +
diff --git a/src/app/components/uia-stages/SSOStage.tsx b/src/app/components/uia-stages/SSOStage.tsx index 20decb6c..e3d6126a 100644 --- a/src/app/components/uia-stages/SSOStage.tsx +++ b/src/app/components/uia-stages/SSOStage.tsx @@ -1,7 +1,6 @@ import { Box, Button, color, config, Dialog, Header, Icon, IconButton, Icons, Text } from 'folds'; import React, { useCallback, useEffect, useState } from 'react'; import { StageComponentProps } from './types'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function SSOStage({ ssoRedirectURL, @@ -57,7 +56,7 @@ export function SSOStage({ SSO Login - + diff --git a/src/app/components/upload-card/CompactUploadCardRenderer.tsx b/src/app/components/upload-card/CompactUploadCardRenderer.tsx index 5fe73a10..3f0246a4 100644 --- a/src/app/components/upload-card/CompactUploadCardRenderer.tsx +++ b/src/app/components/upload-card/CompactUploadCardRenderer.tsx @@ -7,7 +7,6 @@ import { TUploadContent } from '../../utils/matrix'; import { bytesToSize, getFileTypeIcon } from '../../utils/common'; import { useMediaConfig } from '../../hooks/useMediaConfig'; import { UploadFailureNote } from './UploadFailureNote'; -import { PhoneHitSpread28 } from '../../styles/PhoneHit.css'; type CompactUploadCardRendererProps = { isEncrypted?: boolean; @@ -65,7 +64,6 @@ export function CompactUploadCardRenderer({ )} )} (({ children, ...props }, ref) => { <>
(({ children, ...props }, ref) => { <>
Self Demotion - + @@ -121,7 +120,7 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps) Shared Power - + diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx index a57a6b10..d100096b 100644 --- a/src/app/features/add-existing/AddExisting.tsx +++ b/src/app/features/add-existing/AddExisting.tsx @@ -54,7 +54,6 @@ import { StateEvent } from '../../../types/matrix/room'; import { getViaServers } from '../../plugins/via-servers'; import { rateLimitedActions } from '../../utils/matrix'; import { useAlive } from '../../hooks/useAlive'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const SEARCH_OPTS: UseAsyncSearchOptions = { limit: 500, @@ -202,7 +201,7 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM Add Existing - + diff --git a/src/app/features/call-status/CallControl.tsx b/src/app/features/call-status/CallControl.tsx index d63f8709..3cf38b1f 100644 --- a/src/app/features/call-status/CallControl.tsx +++ b/src/app/features/call-status/CallControl.tsx @@ -5,7 +5,6 @@ import { StatusDivider } from './components'; import { CallEmbed, useCallControlState } from '../../plugins/call'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { callEmbedAtom } from '../../state/callEmbed'; -import { PhoneHitSpread26 } from '../../styles/PhoneHit.css'; type MicrophoneButtonProps = { enabled: boolean; @@ -27,7 +26,6 @@ function MicrophoneButton({ enabled, onToggle, disabled }: MicrophoneButtonProps > {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( void; @@ -93,7 +92,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { - + diff --git a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx index a6e60a7b..f25ba7c3 100644 --- a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx +++ b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx @@ -22,7 +22,6 @@ import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { syntaxErrorPosition } from '../../../utils/dom'; import { Cursor } from '../../../plugins/text-area'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -119,7 +118,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro - + diff --git a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx index 0f9f4034..0ea96901 100644 --- a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx +++ b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx @@ -31,7 +31,6 @@ import { usePowerLevels } from '../../../hooks/usePowerLevels'; import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -276,7 +275,7 @@ export function StateEventEditor({ type, stateKey, requestClose }: StateEventEdi - + diff --git a/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx b/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx index f7e901d5..ad8ffae6 100644 --- a/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx +++ b/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx @@ -4,7 +4,6 @@ import { Page, PageContent, PageHeader } from '../../../components/page'; import { ImagePack } from '../../../plugins/custom-emoji'; import { ImagePackView } from '../../../components/image-pack-view'; import { RoomPacks } from './RoomPacks'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type EmojisStickersProps = { requestClose: () => void; @@ -30,7 +29,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) { - + diff --git a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx index 7be8de35..fdbe546e 100644 --- a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx +++ b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx @@ -40,7 +40,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useAlive } from '../../../hooks/useAlive'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type CreatePackTileProps = { packs: ImagePack[]; @@ -216,7 +215,6 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) { {canEdit && (removed ? ( ) : ( Enable Encryption setPrompt(false)} radii="300" diff --git a/src/app/features/common-settings/general/RoomUpgrade.tsx b/src/app/features/common-settings/general/RoomUpgrade.tsx index 2971d565..45a480aa 100644 --- a/src/app/features/common-settings/general/RoomUpgrade.tsx +++ b/src/app/features/common-settings/general/RoomUpgrade.tsx @@ -39,7 +39,6 @@ import { useAlive } from '../../../hooks/useAlive'; import { creatorsSupported } from '../../../utils/matrix'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { BreakWord } from '../../../styles/Text.css'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { const mx = useMatrixClient(); @@ -106,7 +105,7 @@ function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { {room.isSpaceRoom() ? 'Space Upgrade' : 'Room Upgrade'} - + diff --git a/src/app/features/common-settings/members/Members.tsx b/src/app/features/common-settings/members/Members.tsx index a1dddb54..15cd1d08 100644 --- a/src/app/features/common-settings/members/Members.tsx +++ b/src/app/features/common-settings/members/Members.tsx @@ -56,7 +56,6 @@ import { useSpaceOptionally } from '../../../hooks/useSpace'; import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '../../../hooks/useMemberPowerTag'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { getMouseEventCords } from '../../../utils/dom'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, @@ -162,7 +161,7 @@ export function Members({ requestClose }: MembersProps) { - + @@ -278,7 +277,6 @@ export function Members({ requestClose }: MembersProps) { anchorRef={scrollTopAnchorRef} > virtualizer.scrollToOffset(0)} variant="Surface" radii="Pill" diff --git a/src/app/features/common-settings/permissions/PowersEditor.tsx b/src/app/features/common-settings/permissions/PowersEditor.tsx index 0684a48a..97305946 100644 --- a/src/app/features/common-settings/permissions/PowersEditor.tsx +++ b/src/app/features/common-settings/permissions/PowersEditor.tsx @@ -49,7 +49,6 @@ import { useAlive } from '../../../hooks/useAlive'; import { BetaNoticeBadge } from '../../../components/BetaNoticeBadge'; import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag'; import { creatorsSupported } from '../../../utils/matrix'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type EditPowerProps = { maxPower: number; @@ -370,7 +369,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { - + diff --git a/src/app/features/create-room/CreateRoomModal.tsx b/src/app/features/create-room/CreateRoomModal.tsx index 9332f35c..d5d8c92d 100644 --- a/src/app/features/create-room/CreateRoomModal.tsx +++ b/src/app/features/create-room/CreateRoomModal.tsx @@ -24,7 +24,6 @@ import { import { CreateRoomModalState } from '../../state/createRoomModal'; import { stopPropagation } from '../../utils/keyboard'; import { CreateRoomType } from '../../components/create-room/types'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type CreateRoomModalProps = { state: CreateRoomModalState; @@ -64,7 +63,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { - + diff --git a/src/app/features/create-space/CreateSpaceModal.tsx b/src/app/features/create-space/CreateSpaceModal.tsx index faa53b25..c1bc6898 100644 --- a/src/app/features/create-space/CreateSpaceModal.tsx +++ b/src/app/features/create-space/CreateSpaceModal.tsx @@ -23,7 +23,6 @@ import { } from '../../state/hooks/createSpaceModal'; import { CreateSpaceModalState } from '../../state/createSpaceModal'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type CreateSpaceModalProps = { state: CreateSpaceModalState; @@ -62,7 +61,7 @@ function CreateSpaceModal({ state }: CreateSpaceModalProps) { New Space - + diff --git a/src/app/features/desk/Desk.tsx b/src/app/features/desk/Desk.tsx index d6795ac4..b29ae9ec 100644 --- a/src/app/features/desk/Desk.tsx +++ b/src/app/features/desk/Desk.tsx @@ -1,7 +1,6 @@ import React, { useMemo } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Box, Icon, IconButton, Icons, Scroll, Text } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { Page, PageContent, PageContentCenter, PageHeader } from '../../components/page'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { getHomePath } from '../../pages/pathUtils'; @@ -28,7 +27,6 @@ export function Desk() { {phone && ( navigate(getHomePath())} > diff --git a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx index 43576cff..028cd560 100644 --- a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx +++ b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx @@ -10,7 +10,6 @@ import { useMatrixClient } from '../../hooks/useMatrixClient'; import { allRoomsAtom } from '../../state/room-list/roomList'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { BackRouteHandler } from '../../components/BackRouteHandler'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type JoinBeforeNavigateProps = { roomIdOrAlias: string; eventId?: string; viaServers?: string[] }; export function JoinBeforeNavigate({ @@ -39,7 +38,7 @@ export function JoinBeforeNavigate({ {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/features/lobby/HierarchyItemMenu.tsx b/src/app/features/lobby/HierarchyItemMenu.tsx index cdfa2d8a..1802e3b0 100644 --- a/src/app/features/lobby/HierarchyItemMenu.tsx +++ b/src/app/features/lobby/HierarchyItemMenu.tsx @@ -30,7 +30,6 @@ import { IPowerLevels } from '../../hooks/usePowerLevels'; import { getRoomCreatorsForRoomId } from '../../hooks/useRoomCreators'; import { getRoomPermissionsAPI } from '../../hooks/useRoomPermissions'; import { InviteUserPrompt } from '../../components/invite-user-prompt'; -import { PhoneHitSpread24 } from '../../styles/PhoneHit.css'; type HierarchyItemWithParent = HierarchyItem & { parentId: string; @@ -232,7 +231,6 @@ export function HierarchyItemMenu({ return ( virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/features/lobby/LobbyHeader.tsx b/src/app/features/lobby/LobbyHeader.tsx index ce248fe5..ed526c68 100644 --- a/src/app/features/lobby/LobbyHeader.tsx +++ b/src/app/features/lobby/LobbyHeader.tsx @@ -38,7 +38,6 @@ import { useOpenSpaceSettings } from '../../state/hooks/spaceSettings'; import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { InviteUserPrompt } from '../../components/invite-user-prompt'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LobbyMenuProps = { powerLevels: IPowerLevels; @@ -166,7 +165,7 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { {(onBack) => ( - + )} @@ -241,7 +240,6 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { > {(triggerRef) => ( useMemo( @@ -194,7 +193,6 @@ export function MessageSearch({ virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 8d53ce7f..e8a349f0 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -66,7 +66,6 @@ import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo'; import { livekitSupport } from '../../hooks/useLivekitSupport'; import { StateEvent } from '../../../types/matrix/room'; import { webRTCSupported } from '../../utils/rtc'; -import { PhoneHitSpread24 } from '../../styles/PhoneHit.css'; type RoomNavItemMenuProps = { room: Room; @@ -230,7 +229,6 @@ function CallChatToggle() { return ( setChat(!chat)} aria-pressed={chat} aria-label="Toggle Chat" @@ -438,7 +436,6 @@ export function RoomNavItem({ } > {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/room-settings/general/General.tsx b/src/app/features/room-settings/general/General.tsx index e29fe2da..15157304 100644 --- a/src/app/features/room-settings/general/General.tsx +++ b/src/app/features/room-settings/general/General.tsx @@ -15,7 +15,6 @@ import { } from '../../common-settings/general'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type GeneralProps = { requestClose: () => void; @@ -36,7 +35,7 @@ export function General({ requestClose }: GeneralProps) { - + diff --git a/src/app/features/room-settings/permissions/Permissions.tsx b/src/app/features/room-settings/permissions/Permissions.tsx index d513dda9..7572a71b 100644 --- a/src/app/features/room-settings/permissions/Permissions.tsx +++ b/src/app/features/room-settings/permissions/Permissions.tsx @@ -9,7 +9,6 @@ import { usePermissionGroups } from './usePermissionItems'; import { PermissionGroups, Powers, PowersEditor } from '../../common-settings/permissions'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type PermissionsProps = { requestClose: () => void; @@ -46,7 +45,7 @@ export function Permissions({ requestClose }: PermissionsProps) { - + diff --git a/src/app/features/room/CallChatView.tsx b/src/app/features/room/CallChatView.tsx index fe40eb50..4a10fceb 100644 --- a/src/app/features/room/CallChatView.tsx +++ b/src/app/features/room/CallChatView.tsx @@ -6,7 +6,6 @@ import { Page, PageHeader } from '../../components/page'; import { callChatAtom } from '../../state/callEmbed'; import { RoomView } from './RoomView'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function CallChatView() { const { eventId } = useParams(); @@ -43,7 +42,6 @@ export function CallChatView() { > {(triggerRef) => ( {(triggerRef) => ( setPeopleDrawer(false)} @@ -361,7 +359,6 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { virtualizer.scrollToOffset(0)} variant="Surface" radii="Pill" diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 2d63cbf1..257e88ad 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -116,7 +116,6 @@ import { useTheme } from '../../hooks/useTheme'; import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag'; import { usePowerLevelTags } from '../../hooks/usePowerLevelTags'; import { useComposingCheck } from '../../hooks/useComposingCheck'; -import { PhoneHitSpread24, PhoneHitSpread32 } from '../../styles/PhoneHit.css'; interface RoomInputProps { editor: Editor; @@ -606,7 +605,6 @@ export const RoomInput = forwardRef( style={{ padding: `${config.space.S200} ${config.space.S300} 0` }} > setReplyDraft(undefined)} variant="SurfaceVariant" size="300" @@ -640,7 +638,6 @@ export const RoomInput = forwardRef( } before={ pickFile('*')} variant="SurfaceVariant" size="300" @@ -652,7 +649,6 @@ export const RoomInput = forwardRef( after={ <> ( > {!hideStickerBtn && ( setEmojiBoardTab(EmojiBoardTab.Sticker)} variant="SurfaceVariant" @@ -709,7 +704,6 @@ export const RoomInput = forwardRef( )} ( )} {(triggerRef) => ( {(onBack) => ( - + @@ -534,7 +532,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { > {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( ( )} void; @@ -109,7 +108,7 @@ export function JumpToTime({ onCancel, onSubmit }: JumpToTimeProps) { Jump to Time - + diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index a1bc17c9..d82ea8e9 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -86,7 +86,6 @@ import colorMXID from '../../../../util/colorMXID'; import { useSkyInk } from '../../../hooks/useTheme'; import { userColorInk } from '../../scene/skyInk'; import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag'; -import { PhoneHitRoom26, PhoneHitSpread32 } from '../../../styles/PhoneHit.css'; export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void; @@ -112,7 +111,7 @@ export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>( {recentEmojis.map((emoji) => ( Delete Message Report Message ( } > ( )} ( {!isThreadedMessage && ( onReplyClick(ev, true)} data-event-id={mEvent.getId()} variant="SurfaceVariant" @@ -996,7 +990,6 @@ export const Message = as<'div', MessageProps>( )} {canEditEvent(mx, mEvent) && onEditId && ( onEditId(mEvent.getId())} variant="SurfaceVariant" size="300" @@ -1162,7 +1155,6 @@ export const Message = as<'div', MessageProps>( } > ( } > ( ( } > diff --git a/src/app/features/room/message/styles.css.ts b/src/app/features/room/message/styles.css.ts index 4be501bd..b2d027f6 100644 --- a/src/app/features/room/message/styles.css.ts +++ b/src/app/features/room/message/styles.css.ts @@ -1,5 +1,7 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, config, toRem } from 'folds'; +import { ICON_BUTTON_CLASS } from '../../../../phoneGlyph.css'; +import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize'; export const MessageBase = style({ position: 'relative', @@ -24,6 +26,10 @@ export const MessageOptionsBar = style([ }, ]); +globalStyle(`${MessageOptionsBar} .${ICON_BUTTON_CLASS}`, { + '@media': { [`screen and (max-width: ${MOBILE_BREAKPOINT}px)`]: { margin: 9 } }, +}); + export const BubbleAvatarBase = style({ paddingTop: 0, }); diff --git a/src/app/features/room/reaction-viewer/ReactionViewer.tsx b/src/app/features/room/reaction-viewer/ReactionViewer.tsx index b1a674d9..6c686bc5 100644 --- a/src/app/features/room/reaction-viewer/ReactionViewer.tsx +++ b/src/app/features/room/reaction-viewer/ReactionViewer.tsx @@ -28,7 +28,6 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { useOpenUserRoomProfile } from '../../../state/hooks/userRoomProfile'; import { useSpaceOptionally } from '../../../hooks/useSpace'; import { getMouseEventCords } from '../../../utils/dom'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export type ReactionViewerProps = { room: Room; @@ -101,7 +100,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( {`Reacted with :${selectedShortcode}:`} - + diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 25fe835f..9986849f 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -86,7 +86,6 @@ import { useGetMemberPowerTag, } from '../../../hooks/useMemberPowerTag'; import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag'; -import { PhoneHit, PhoneHitSpread26 } from '../../../styles/PhoneHit.css'; type PinnedMessageProps = { room: Room; @@ -147,7 +146,6 @@ function PinnedMessage({ {canPinEvent && ( ( Pinned Messages - + diff --git a/src/app/features/scene/SceneViewEntry.tsx b/src/app/features/scene/SceneViewEntry.tsx index 941b01b3..9282c10b 100644 --- a/src/app/features/scene/SceneViewEntry.tsx +++ b/src/app/features/scene/SceneViewEntry.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { Icon, IconButton, Icons } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { useSceneViewOffered } from '../../hooks/useSceneView'; import { loadSceneView, openSceneView } from './sceneView'; @@ -17,7 +16,6 @@ export function SceneViewEntry() { }; return ( { }); describe('the view while its code loads', () => { - it('shows a Return that closes the view, with the phone tap target', () => { + it('shows a Return that closes the view', () => { const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return'); - expect(String(ret?.props?.className)).toContain(PhoneHit); (ret?.props?.onClick as () => void)(); expect(held.closed).toBe(1); }); diff --git a/src/app/features/scene/SceneViewHost.tsx b/src/app/features/scene/SceneViewHost.tsx index ba299a25..70844d41 100644 --- a/src/app/features/scene/SceneViewHost.tsx +++ b/src/app/features/scene/SceneViewHost.tsx @@ -1,7 +1,6 @@ import React, { ComponentType, useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { Icon, IconButton, Icons } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { useSceneViewOffered, useSceneViewState } from '../../hooks/useSceneView'; import { closeSceneView, loadSceneViewOrClose, restoreEntryFocus } from './sceneView'; import * as css from './sceneShell.css'; @@ -23,7 +22,7 @@ export function SceneViewLoading() { }, []); return ( { ).toEqual(['Return', 'View', 'Time', 'Sky', 'Place']); }); - it('every rail icon is an IconButton carrying PhoneHit, with a label and a roving tab stop on Return', () => { + it('every rail icon is an IconButton, with a label and a roving tab stop on Return', () => { const buttons = rail() .filter((e) => typeof e.props?.label === 'string') .map((e) => - walk((e.type as (p: unknown) => unknown)(e.props)).find( - (x) => x.props?.className === PhoneHit - ) + walk((e.type as (p: unknown) => unknown)(e.props)).find((x) => x.type === IconButton) ); expect(buttons).toHaveLength(5); buttons.forEach((b) => expect(b?.props?.['aria-label']).toBeTruthy()); diff --git a/src/app/features/scene/view/SceneView.tsx b/src/app/features/scene/view/SceneView.tsx index 854320b5..bb4cbd6b 100644 --- a/src/app/features/scene/view/SceneView.tsx +++ b/src/app/features/scene/view/SceneView.tsx @@ -1,7 +1,6 @@ import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'; import { Icon, IconButton, Icons } from 'folds'; import FocusTrap from 'focus-trap-react'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; import { useRidgeManifest, useSceneViewState } from '../../../hooks/useSceneView'; import { closeSceneView, setSubmenu } from '../sceneView'; import type { Submenu } from '../sceneView'; @@ -23,7 +22,7 @@ export const SUBMENUS: ReadonlyArray<{ id: Submenu; label: string; icon: IconSrc { id: 'place', label: 'Place', icon: Icons.Pin }, ]; -/** One icon of the rail: 44 px to tap on a phone (PhoneHit). */ +/** One icon of the rail. */ function RailButton({ label, icon, @@ -42,7 +41,6 @@ function RailButton({ return ( {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index 19407bdf..9ec74305 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -8,7 +8,6 @@ import { LogoMark } from '../../../components/logo/logoMark.css'; import RatatoskrSVG from '../../../../../public/res/svg/ratatoskr.svg'; import { clearCacheAndReload } from '../../../../client/initMatrix'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type AboutProps = { requestClose: () => void; @@ -26,7 +25,7 @@ export function About({ requestClose }: AboutProps) { - + diff --git a/src/app/features/settings/account/Account.tsx b/src/app/features/settings/account/Account.tsx index 77ee8671..c4b56e47 100644 --- a/src/app/features/settings/account/Account.tsx +++ b/src/app/features/settings/account/Account.tsx @@ -5,7 +5,6 @@ import { MatrixId } from './MatrixId'; import { Profile } from './Profile'; import { ContactInformation } from './ContactInfo'; import { IgnoredUserList } from './IgnoredUserList'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type AccountProps = { requestClose: () => void; @@ -21,7 +20,7 @@ export function Account({ requestClose }: AccountProps) { - + diff --git a/src/app/features/settings/account/IgnoredUserList.tsx b/src/app/features/settings/account/IgnoredUserList.tsx index 791a407b..98db9459 100644 --- a/src/app/features/settings/account/IgnoredUserList.tsx +++ b/src/app/features/settings/account/IgnoredUserList.tsx @@ -8,7 +8,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { isUserId } from '../../../utils/matrix'; import { useIgnoredUsers } from '../../../hooks/useIgnoredUsers'; import { useAlive } from '../../../hooks/useAlive'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function IgnoreUserInput({ userList }: { userList: string[] }) { const mx = useMatrixClient(); @@ -68,7 +67,6 @@ function IgnoreUserInput({ userList }: { userList: string[] }) { userId && !ignoring && ( Remove Avatar setAlertRemove(false)} radii="300" @@ -279,7 +277,6 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) { hasChanges && !changingDisplayName && ( void; @@ -52,7 +51,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { - + diff --git a/src/app/features/settings/devices/DeviceTile.tsx b/src/app/features/settings/devices/DeviceTile.tsx index c4912dc0..71b684f5 100644 --- a/src/app/features/settings/devices/DeviceTile.tsx +++ b/src/app/features/settings/devices/DeviceTile.tsx @@ -29,7 +29,6 @@ import { LogoutDialog } from '../../../components/LogoutDialog'; import { stopPropagation } from '../../../utils/keyboard'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function DeviceTilePlaceholder() { return ( @@ -289,7 +288,6 @@ export function DeviceTile({ - + diff --git a/src/app/features/settings/devices/Verification.tsx b/src/app/features/settings/devices/Verification.tsx index c09dff55..6c7eab17 100644 --- a/src/app/features/settings/devices/Verification.tsx +++ b/src/app/features/settings/devices/Verification.tsx @@ -35,7 +35,6 @@ import { stopPropagation } from '../../../utils/keyboard'; import { useAuthMetadata } from '../../../hooks/useAuthMetadata'; import { withSearchParam } from '../../../pages/pathUtils'; import { useAccountManagementActions } from '../../../hooks/useAccountManagement'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type VerificationStatusBadgeProps = { verificationStatus: VerificationStatus; @@ -289,7 +288,6 @@ export function DeviceVerificationOptions() { return ( <> void; @@ -31,7 +30,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) { - + diff --git a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx index 38647b13..a9288728 100644 --- a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx +++ b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx @@ -43,7 +43,6 @@ import { allRoomsAtom } from '../../../state/room-list/roomList'; import { AccountDataEvent } from '../../../../types/matrix/accountData'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { stopPropagation } from '../../../utils/keyboard'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function GlobalPackSelector({ packs, @@ -369,7 +368,6 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { {removed ? ( ) : ( ; @@ -496,7 +495,6 @@ function DateHint({ hasChanges, handleReset }: DateHintProps) { > {hasChanges ? ( ) : ( - + diff --git a/src/app/features/settings/notifications/KeywordMessages.tsx b/src/app/features/settings/notifications/KeywordMessages.tsx index b77cae21..f3af28ae 100644 --- a/src/app/features/settings/notifications/KeywordMessages.tsx +++ b/src/app/features/settings/notifications/KeywordMessages.tsx @@ -15,7 +15,6 @@ import { } from '../../../hooks/useNotificationMode'; import { NotificationModeSwitcher } from './NotificationModeSwitcher'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const NOTIFY_MODE_OPS: NotificationModeOptions = { highlight: true, @@ -76,7 +75,6 @@ function KeywordInput() { keyword && !addingKeyword && ( void; @@ -24,7 +23,7 @@ export function Notifications({ requestClose }: NotificationsProps) { - + diff --git a/src/app/features/space-settings/SpaceSettings.tsx b/src/app/features/space-settings/SpaceSettings.tsx index 1030972f..b5fefc93 100644 --- a/src/app/features/space-settings/SpaceSettings.tsx +++ b/src/app/features/space-settings/SpaceSettings.tsx @@ -17,7 +17,6 @@ import { Members } from '../common-settings/members'; import { DeveloperTools } from '../common-settings/developer-tools'; import { General } from './general'; import { Permissions } from './permissions'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type SpaceSettingsMenuItem = { page: SpaceSettingsPage; @@ -118,7 +117,7 @@ export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps) {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/space-settings/general/General.tsx b/src/app/features/space-settings/general/General.tsx index e99a4906..72040632 100644 --- a/src/app/features/space-settings/general/General.tsx +++ b/src/app/features/space-settings/general/General.tsx @@ -13,7 +13,6 @@ import { } from '../../common-settings/general'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type GeneralProps = { requestClose: () => void; @@ -34,7 +33,7 @@ export function General({ requestClose }: GeneralProps) { - + diff --git a/src/app/features/space-settings/permissions/Permissions.tsx b/src/app/features/space-settings/permissions/Permissions.tsx index d513dda9..7572a71b 100644 --- a/src/app/features/space-settings/permissions/Permissions.tsx +++ b/src/app/features/space-settings/permissions/Permissions.tsx @@ -9,7 +9,6 @@ import { usePermissionGroups } from './usePermissionItems'; import { PermissionGroups, Powers, PowersEditor } from '../../common-settings/permissions'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type PermissionsProps = { requestClose: () => void; @@ -46,7 +45,7 @@ export function Permissions({ requestClose }: PermissionsProps) { - + diff --git a/src/app/pages/auth/ServerPicker.tsx b/src/app/pages/auth/ServerPicker.tsx index 393cf34e..a2a78106 100644 --- a/src/app/pages/auth/ServerPicker.tsx +++ b/src/app/pages/auth/ServerPicker.tsx @@ -23,7 +23,6 @@ import FocusTrap from 'focus-trap-react'; import { useDebounce } from '../../hooks/useDebounce'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function ServerPicker({ server, @@ -130,7 +129,6 @@ export function ServerPicker({ } > (); @@ -97,7 +96,6 @@ function UsernameHint({ server }: { server: string }) { } > {(onBack) => ( - + )} diff --git a/src/app/pages/client/explore/Explore.tsx b/src/app/pages/client/explore/Explore.tsx index 6944c9f7..afb9103f 100644 --- a/src/app/pages/client/explore/Explore.tsx +++ b/src/app/pages/client/explore/Explore.tsx @@ -37,7 +37,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useNavToActivePathMapper } from '../../../hooks/useNavToActivePathMapper'; import { PageNav, PageNavContent, PageNavHeader } from '../../../components/page'; import { stopPropagation } from '../../../utils/keyboard'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function AddServer() { const mx = useMatrixClient(); @@ -98,7 +97,6 @@ export function AddServer() { Add Server setDialog(false)} radii="300" diff --git a/src/app/pages/client/explore/Featured.tsx b/src/app/pages/client/explore/Featured.tsx index c28fad0a..f056cbb5 100644 --- a/src/app/pages/client/explore/Featured.tsx +++ b/src/app/pages/client/explore/Featured.tsx @@ -18,7 +18,6 @@ import * as css from './style.css'; import { useRoomNavigate } from '../../../hooks/useRoomNavigate'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function FeaturedRooms() { const { featuredCommunities } = useClientConfig(); @@ -34,7 +33,7 @@ export function FeaturedRooms() { {(onBack) => ( - + )} diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index 036c6488..48f267cc 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -45,7 +45,6 @@ import { getMxIdServer } from '../../../utils/matrix'; import { stopPropagation } from '../../../utils/keyboard'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const useServerSearchParams = (searchParams: URLSearchParams): ExploreServerPathSearchParams => useMemo( @@ -500,7 +499,7 @@ export function PublicRooms() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/home/CreateRoom.tsx b/src/app/pages/client/home/CreateRoom.tsx index 8e277889..fddd75aa 100644 --- a/src/app/pages/client/home/CreateRoom.tsx +++ b/src/app/pages/client/home/CreateRoom.tsx @@ -12,7 +12,6 @@ import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; import { CreateRoomForm } from '../../../features/create-room'; import { useRoomNavigate } from '../../../hooks/useRoomNavigate'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function HomeCreateRoom() { const screenSize = useScreenSizeContext(); @@ -26,7 +25,7 @@ export function HomeCreateRoom() { {(onBack) => ( - + )} diff --git a/src/app/pages/client/home/Search.tsx b/src/app/pages/client/home/Search.tsx index aa454d2c..d5ddfb77 100644 --- a/src/app/pages/client/home/Search.tsx +++ b/src/app/pages/client/home/Search.tsx @@ -5,7 +5,6 @@ import { MessageSearch } from '../../../features/message-search'; import { useHomeRooms } from './useHomeRooms'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function HomeSearch() { const scrollRef = useRef(null); @@ -20,7 +19,7 @@ export function HomeSearch() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/inbox/Invites.tsx b/src/app/pages/client/inbox/Invites.tsx index 4d1580af..ca26bac3 100644 --- a/src/app/pages/client/inbox/Invites.tsx +++ b/src/app/pages/client/inbox/Invites.tsx @@ -63,7 +63,6 @@ import { useIgnoredUsers } from '../../../hooks/useIgnoredUsers'; import { useReportRoomSupported } from '../../../hooks/useReportRoomSupported'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const COMPACT_CARD_WIDTH = 548; @@ -746,7 +745,7 @@ export function Invites() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 8fddba44..9592224f 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -97,7 +97,6 @@ import { } from '../../../hooks/useMemberPowerTag'; import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type RoomNotificationsGroup = { roomId: string; @@ -643,7 +642,7 @@ export function Notifications() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} @@ -695,7 +694,6 @@ export function Notifications() { onVisibilityChange={handleScrollTopVisibility} > virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/pages/client/space/Search.tsx b/src/app/pages/client/space/Search.tsx index a2849ab8..017262b5 100644 --- a/src/app/pages/client/space/Search.tsx +++ b/src/app/pages/client/space/Search.tsx @@ -11,7 +11,6 @@ import { roomToParentsAtom } from '../../../state/room/roomToParents'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function SpaceSearch() { const mx = useMatrixClient(); @@ -35,7 +34,7 @@ export function SpaceSearch() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/phoneGlyph.test.ts b/src/app/phoneGlyph.test.ts index 6969da0e..1f31dae6 100644 --- a/src/app/phoneGlyph.test.ts +++ b/src/app/phoneGlyph.test.ts @@ -1,64 +1,15 @@ import { readFileSync } from 'fs'; import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { emitted } from './phoneHitTestKit'; import { ICON_BUTTON_CLASS, PHONE_GLYPHS } from '../phoneGlyph.css'; -const foldsJs = readFileSync(`${process.cwd()}/node_modules/folds/dist/index.js`, 'utf8'); const foldsCss = readFileSync(`${process.cwd()}/node_modules/folds/dist/style.css`, 'utf8'); -/** The px folds draws an Icon class at: its width variable's rem value, at the 16 px root. */ -const foldsPx = (cls: string) => { - const v = foldsCss.match(new RegExp(`\\.${cls} \\{\\s*width: var\\((--[\\w-]+)\\)`))?.[1]; - const rem = v && foldsCss.match(new RegExp(`${v}: ([\\d.]+)rem`))?.[1]; - return rem ? Number(rem) * 16 : undefined; -}; - -describe('phone glyphs inside IconButtons', () => { - it("name folds' own classes: the IconButton base class and one Icon class per size", () => { - expect(foldsJs).toContain( - `var IconButton$1 = createRuntimeFn({ defaultClassName: "${ICON_BUTTON_CLASS} ` - ); - const iconSizes = foldsJs.match( - /var Icon\$1 = createRuntimeFn\(\{[^\n]*variantClassNames: \{ size: \{([^}]*)\}/ - )?.[1]; - expect(iconSizes).toBeDefined(); - Object.entries(PHONE_GLYPHS).forEach(([size, { cls }]) => - expect(iconSizes).toContain(`"${size}": "${cls}"`) - ); - }); - - it("start from the px folds draws each Icon size at (the scale's divisor is not a guess)", () => - Object.values(PHONE_GLYPHS).forEach(({ cls, px }) => expect(foldsPx(cls)).toBe(px))); - - it('draw the folds Icon px (16 18 20 22 24) at 22..28 px, never smaller, never past the smallest button box', () => { - // folds IconButton padding is 4 px a side at the smallest size, so its box is the glyph plus 8. - Object.values(PHONE_GLYPHS).forEach(({ px, phonePx }) => { - expect(phonePx).toBeGreaterThanOrEqual(22); - expect(phonePx).toBeLessThanOrEqual(28); +describe('phoneGlyph folds classes', () => { + it('references IconButton and Icon size classes present in folds/dist/style.css', () => { + expect(foldsCss).toMatch(new RegExp(`\\.${ICON_BUTTON_CLASS}\\b`)); + Object.values(PHONE_GLYPHS).forEach(({ cls, px, phonePx }) => { + expect(foldsCss).toMatch(new RegExp(`\\.${cls}\\b`)); expect(phonePx).toBeGreaterThan(px); - expect(phonePx).toBeLessThanOrEqual(px + 8); - }); - }); - - it('are a paint-time scale on phones only: no size, margin or padding, and no rule outside the phone query', async () => { - const css = await emitted('../phoneGlyph.css.ts'); - const phone = `@media screen and (max-width: ${MOBILE_BREAKPOINT}px)`; - expect( - css.replace(new RegExp(`${phone.replace(/[()]/g, '\\$&')} \\{\\n[\\s\\S]*?\\n\\}`, 'g'), '') - ).not.toMatch(/\.brs7ce5/); - Object.entries(PHONE_GLYPHS).forEach(([size, { cls, px, phonePx }]) => { - const rule = css.match( - new RegExp(`\\.${ICON_BUTTON_CLASS} > \\.${cls} \\{\\n([^}]*)\\}`) - )?.[1]; - expect(rule, `rule for Icon size ${size}`).toBeDefined(); - expect( - rule! - .trim() - .split('\n') - .map((l) => l.trim().split(':')[0]) - ).toEqual(['scale']); - expect(Number(rule!.match(/scale: ([\d.]+)/)![1])).toBeCloseTo(phonePx / px, 6); }); }); }); diff --git a/src/app/phoneHit.call.test.ts b/src/app/phoneHit.call.test.ts deleted file mode 100644 index 56971b05..00000000 --- a/src/app/phoneHit.call.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Every IconButton of the call bars carries the phone hit-area variant of its drawn size, in source order -// (mic, sound, video, share, chat; the menu button; the call-status mic, sound, video, share). -describe('icon buttons in the call controls', () => { - it.each([ - ['features/call/Controls.tsx', Array(5).fill('PhoneHitSpread40')], - ['features/call/CallControls.tsx', ['PhoneHitSpread40']], - ['features/call-status/CallControl.tsx', Array(4).fill('PhoneHitSpread26')], - ])('%s', (file, want) => { - expectPhoneHitClasses(file as string, want as string[]); - expectSizeTie(file as string); - }); -}); diff --git a/src/app/phoneHit.commonSettings.test.ts b/src/app/phoneHit.commonSettings.test.ts deleted file mode 100644 index fdb2c4e0..00000000 --- a/src/app/phoneHit.commonSettings.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Every IconButton under features/common-settings, in source order. Header close buttons are alone at the -// header end (the title beside them is text), the dialog close buttons are alone in their Header, the -// scroll-to-top button floats alone, and the RoomPacks pair is a ternary (only one renders): all PhoneHit. -const files: [string, string[]][] = [ - ['features/common-settings/members/Members.tsx', ['PhoneHit', 'PhoneHit']], - ['features/common-settings/developer-tools/SendRoomEvent.tsx', ['PhoneHit']], - ['features/common-settings/developer-tools/StateEventEditor.tsx', ['PhoneHit']], - ['features/common-settings/developer-tools/DevelopTools.tsx', ['PhoneHit']], - ['features/common-settings/permissions/PowersEditor.tsx', ['PhoneHit']], - ['features/common-settings/emojis-stickers/EmojisStickers.tsx', ['PhoneHit']], - ['features/common-settings/emojis-stickers/RoomPacks.tsx', ['PhoneHit', 'PhoneHit']], - ['features/common-settings/general/RoomEncryption.tsx', ['PhoneHit']], - ['features/common-settings/general/RoomUpgrade.tsx', ['PhoneHit']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('carries the variant its drawn size and neighbours call for', () => { - expectPhoneHitClasses(file, want); - }); - it('names a size that matches what it draws', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.content.test.ts b/src/app/phoneHit.content.test.ts deleted file mode 100644 index 741a5828..00000000 --- a/src/app/phoneHit.content.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in message content and data editors', () => { - // The class each IconButton must carry, in source order. - const expected: Record = { - // mute toggle, 16 px icon + 8 padding = 24 px, 8 px from the volume slider (tappable) - 'components/message/content/AudioContent.tsx': ['PhoneHitSpread24'], - // download, alone at the end of the header row (26 px) - 'components/message/FileHeader.tsx': ['PhoneHit'], - // code block expand/collapse, 24 px, 8 px from the Copy chip - 'plugins/react-custom-html-parser.tsx': ['PhoneHitSpread24'], - // close at the header end, alone - 'components/AccountDataEditor.tsx': ['PhoneHit'], - 'components/image-pack-view/ImagePackView.tsx': ['PhoneHit'], - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.coverage.test.ts b/src/app/phoneHit.coverage.test.ts deleted file mode 100644 index f87b9a1a..00000000 --- a/src/app/phoneHit.coverage.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { readdirSync, readFileSync } from 'fs'; -import { describe, expect, it } from 'vitest'; -import { - classLists, - emitted, - expectPhoneHitClasses, - uncoveredIconButtons, -} from './phoneHitTestKit'; - -// Every IconButton under src carries a PhoneHit class, or is named here with the reason it has none. The per-group -// suites pin which variant a listed file's buttons carry; this one sees files no group lists, so a new bare -// IconButton fails here instead of shipping with a sub-44px phone hit area. -const EXEMPT: Record = { - 'app/features/estate/EstateNavigator.tsx': { - indices: [0], - why: 'Find a room sits in a css.Targets row that already gives it a 44 px phone target', - }, - 'app/features/lobby/LobbyHeader.tsx': { - indices: [1], - why: 'Members button, hidden on mobile', - }, -}; - -// Every script file, not only .tsx: an IconButton can be rendered from a .ts or .js module too. A file that never -// says IconButton is skipped; one that does is parsed and every mention of it must be a tag the guard can check. -const SCRIPT = /\.(?:[cm]?[jt]s|[jt]sx)$/; -const sourceFiles = (dir: string): string[] => - readdirSync(`${process.cwd()}/src/${dir}`, { withFileTypes: true }).flatMap((e) => { - if (e.isDirectory()) return sourceFiles(`${dir}${e.name}/`); - return SCRIPT.test(e.name) ? [`${dir}${e.name}`] : []; - }); - -describe('phone hit areas: every IconButton is covered or named', () => { - const scanned = sourceFiles('').flatMap((file) => { - const src = readFileSync(`${process.cwd()}/src/${file}`, 'utf8'); - return src.includes('IconButton') ? [{ file, ...uncoveredIconButtons(src, file) }] : []; - }); - - it('lists exactly the IconButtons without a PhoneHit class', () => { - expect(scanned.length).toBeGreaterThan(0); - const bare: Record = {}; - scanned.forEach(({ file, bare: missing }) => { - if (missing.length > 0) bare[file] = missing; - }); - expect(bare).toEqual( - Object.fromEntries(Object.entries(EXEMPT).map(([f, e]) => [f, e.indices])) - ); - }); - - // An IconButton passed as a value (as={IconButton}), re-bound, re-exported or destructured cannot be tied to a - // PhoneHit class, so the guard names it instead of passing over it. Render it as a tag, or extend the - // guard to read the new form. - it('finds no IconButton the guard cannot check', () => { - const unhandled: Record = {}; - scanned.forEach(({ file, unhandled: found }) => { - if (found.length > 0) unhandled[file] = found; - }); - expect(unhandled).toEqual({}); - }); -}); - -// UrlPreviewCard's arrows are absolutely positioned by their own class; PhoneHit would set position: relative on them -// and win or lose by stylesheet order, so they carry the variant that adds only the hit area. -describe('phone hit area of a button positioned by its own class', () => { - it('the arrows carry PhoneHitInPlace', () => { - expectPhoneHitClasses('components/url-preview/UrlPreviewCard.tsx', [ - 'PhoneHitInPlace', - 'PhoneHitInPlace', - ]); - }); - - it('PhoneHitInPlace draws the ::after and sets no position of its own', async () => { - const lists = await classLists('styles/PhoneHit.css.ts'); - expect(lists.PhoneHitInPlace).toHaveLength(1); - const css = await emitted('styles/PhoneHit.css.ts'); - const rules = [...css.matchAll(/^([^{}\n]*PhoneHitInPlace__[^{}\n]*) \{$/gm)].map((m) => m[1]); - expect(rules.length).toBeGreaterThan(0); - rules.forEach((sel) => expect(sel).toMatch(/::after$/)); - }); -}); diff --git a/src/app/phoneHit.dialogs.test.ts b/src/app/phoneHit.dialogs.test.ts deleted file mode 100644 index 8b3416a5..00000000 --- a/src/app/phoneHit.dialogs.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Dialog and prompt close buttons: each is a 32 px button (24 px Icon + 8 px padding) alone at the end of a -// header whose title is not tappable, so the plain PhoneHit; no neighbour to spread from, no clipping container. -describe('icon buttons in dialogs and prompts', () => { - const expected: Record = { - 'features/create-space/CreateSpaceModal.tsx': ['PhoneHit'], - 'features/create-room/CreateRoomModal.tsx': ['PhoneHit'], - 'features/add-existing/AddExisting.tsx': ['PhoneHit'], - 'components/room-topic-viewer/RoomTopicViewer.tsx': ['PhoneHit'], - 'components/leave-room-prompt/LeaveRoomPrompt.tsx': ['PhoneHit'], - 'components/leave-space-prompt/LeaveSpacePrompt.tsx': ['PhoneHit'], - 'components/event-readers/EventReaders.tsx': ['PhoneHit'], - 'components/invite-user-prompt/InviteUserPrompt.tsx': ['PhoneHit'], - 'components/join-address-prompt/JoinAddressPrompt.tsx': ['PhoneHit'], // join cancel - 'components/user-profile/PowerChip.tsx': ['PhoneHit', 'PhoneHit'], // self demotion, shared power - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.editor.test.ts b/src/app/phoneHit.editor.test.ts deleted file mode 100644 index d758662d..00000000 --- a/src/app/phoneHit.editor.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { - classLists, - emitted, - expectPhoneHitClasses, - expectSizeTie, - iconButtonTags, - readSource, - rulesFor, - type SizeAllow, -} from './phoneHitTestKit'; - -describe('icon buttons in the editor, emoji board, upload cards and client root', () => { - // The class each IconButton must carry, in source order. - const expected: Record = { - 'components/editor/Toolbar.tsx': [ - 'PhoneHitSpread36', // mark button: size 400 + 20 px icon, in a row 4 px apart - 'PhoneHitSpread36', // block button, same row - 'PhoneHitRoom36', // heading 1, inside the heading Menu (overflow hidden) - 'PhoneHitRoom36', // heading 2 - 'PhoneHitRoom36', // heading 3 - 'PhoneHit', // heading opener: two 20 px icons, 56 px wide, only its height is short - 'PhoneHit', // Exit chip: text label, wider than 44 px - 'PhoneHit', // markdown toggle, alone at the end of the toolbar - ], - // A column of 40 px buttons 4 px apart (the stack's gap="100", pinned below): there is no vertical variant, so only - // PhoneHit; the 44 px areas then touch with no overlap. - 'components/emoji-board/components/Sidebar.tsx': ['PhoneHit'], - // Both cards put a Retry chip beside the cancel button when the upload failed. - 'components/upload-card/UploadCardRenderer.tsx': ['PhoneHitSpread28'], - 'components/upload-card/CompactUploadCardRenderer.tsx': ['PhoneHitSpread28'], - 'pages/client/ClientRoot.tsx': ['PhoneHit'], // alone, absolute in the corner - }; - - const sizeAllow: SizeAllow = {}; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: Spread and Room variants name the size they draw', (file) => - expectSizeTie(file, sizeAllow) - ); -}); - -/** The JSX element opened at `open` (index of its ``: nesting is counted, not guessed (no self-closing Box here). */ -const boxSpan = (src: string, open: number) => { - const marks = [...src.slice(open).matchAll(/])|<\/Box>/g)]; - const depths = marks.map((m, i) => - marks.slice(0, i + 1).reduce((d, x) => d + (x[0] === '' ? -1 : 1), 0) - ); - const end = depths.indexOf(0); - if (end === -1) throw new Error('unbalanced '); - return [open, open + (marks[end].index ?? 0) + marks[end][0].length] as const; -}; - -describe('the estate navigator find button', () => { - // The only IconButton there needs no PhoneHit: every button in the navigator header is 44 px on a phone because - // the Targets class sets a min size, and the button sits inside the Box that carries that class. - it('is 44 px by the Targets class instead', async () => { - const src = readSource('features/estate/EstateNavigator.tsx'); - const tags = iconButtonTags(src); - expect(tags).toHaveLength(1); - expect(tags[0]).not.toMatch(/PhoneHit/); - - const header = src.indexOf(''); - const boxStart = src.indexOf('', boxStart))).toMatch(/className=\{css\.Targets\}/); - const button = src.indexOf(' { - // PhoneHit makes the button position: relative on a phone; the inline style wins over a class, so the corner - // button stays absolute and its ::after anchors to it. - it('ClientRoot keeps its corner button absolutely positioned inline', () => { - const [tag] = iconButtonTags(readSource('pages/client/ClientRoot.tsx')); - expect(tag).toMatch(/style=\{\{[^}]*position:\s*'absolute'/); - }); - - // A 40 px button with a 44 px area, in a column 4 px apart: the areas touch and do not overlap. A smaller gap - // overlaps them, a larger one leaves a dead strip. - it('the emoji sidebar stack keeps its 4 px gap', () => { - const src = readSource('components/emoji-board/components/Sidebar.tsx'); - const stack = src.slice( - src.indexOf('export const SidebarStack'), - src.indexOf('export function SidebarDivider') - ); - expect(stack).toMatch(/direction="Column"/); - expect(stack).toMatch(/gap="100"/); - }); - - // The same column rhythm in the scrolling Sidebar: its 40 px buttons sit in a Column of Box gap="100" (4 px). - it('the emoji sidebar column keeps its 4 px gap', () => { - const src = readSource('components/emoji-board/components/Sidebar.tsx'); - const column = src.slice( - src.indexOf('export function Sidebar('), - src.indexOf('export const SidebarStack') - ); - expect(column).toMatch( - /]*gap="100"/ - ); - }); -}); diff --git a/src/app/phoneHit.pages.test.ts b/src/app/phoneHit.pages.test.ts deleted file mode 100644 index 97eb77b8..00000000 --- a/src/app/phoneHit.pages.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Page back buttons (and two lone buttons beside them). Every one is alone in its row, 40 px drawn (default -// IconButton and Icon), so plain PhoneHit; the vertical stacks of the page have no variant. -// null = deliberately without: LobbyHeader's Members button renders only when screenSize !== Mobile. -const files: Record = { - 'features/lobby/LobbyHeader.tsx': ['PhoneHit', null, 'PhoneHit'], - 'features/join-before-navigate/JoinBeforeNavigate.tsx': ['PhoneHit'], - 'pages/client/space/Search.tsx': ['PhoneHit'], - 'pages/client/explore/Server.tsx': ['PhoneHit'], - 'pages/client/explore/Featured.tsx': ['PhoneHit'], - 'pages/client/home/CreateRoom.tsx': ['PhoneHit'], - 'pages/client/home/Search.tsx': ['PhoneHit'], - // the second is the 30 px scroll-to-top pill, floating alone at the top centre - 'pages/client/inbox/Notifications.tsx': ['PhoneHit', 'PhoneHit'], - 'pages/client/inbox/Invites.tsx': ['PhoneHit'], - 'pages/client/direct/DirectCreate.tsx': ['PhoneHit'], -}; - -describe.each(Object.entries(files))('phone hit area: %s', (file, want) => { - it('gives each IconButton its variant', () => { - expectPhoneHitClasses(file, want); - }); - // plain PhoneHit has no size to tie; this fails when a sized variant appears whose number is not the drawn px - it('ties any sized variant to the drawn size', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.roomSpace.test.ts b/src/app/phoneHit.roomSpace.test.ts deleted file mode 100644 index c98c2b09..00000000 --- a/src/app/phoneHit.roomSpace.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in room settings, space settings, lobby, search and explore', () => { - // The class each IconButton must carry, in source order. Vertical stacks and lone buttons: the plain PhoneHit. - const expected: Record = { - 'features/room-settings/RoomSettings.tsx': ['PhoneHit'], // close, phone only, alone at the header end - 'features/room-settings/general/General.tsx': ['PhoneHit'], // close, 40 px - 'features/room-settings/permissions/Permissions.tsx': ['PhoneHit'], - 'features/space-settings/SpaceSettings.tsx': ['PhoneHit'], - 'features/space-settings/general/General.tsx': ['PhoneHit'], - 'features/space-settings/permissions/Permissions.tsx': ['PhoneHit'], - // 16 px icon + 8 padding = 24 px, 8-12 px from the Open / Add chips beside it in a hierarchy card - 'features/lobby/HierarchyItemMenu.tsx': ['PhoneHitSpread24'], - 'features/lobby/Lobby.tsx': ['PhoneHit'], // floating scroll-to-top, alone - 'features/message-search/MessageSearch.tsx': ['PhoneHit'], // floating scroll-to-top, alone - 'pages/client/explore/Explore.tsx': ['PhoneHit'], // Add Server dialog close - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.settingsA.test.ts b/src/app/phoneHit.settingsA.test.ts deleted file mode 100644 index 37f1f3c2..00000000 --- a/src/app/phoneHit.settingsA.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in settings A', () => { - // The class each IconButton must carry, in source order. Every one is alone in its row (a header close next to - // non-tappable title text, an input slot, or a list tile beside a non-tappable Avatar), so the plain PhoneHit. - const expected: Record = { - 'features/settings/developer-tools/DevelopTools.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/notifications/Notifications.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/notifications/KeywordMessages.tsx': ['PhoneHit', 'PhoneHit'], // input reset, remove: 26 px, alone - 'features/settings/emojis-stickers/EmojisStickers.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/emojis-stickers/GlobalPacks.tsx': ['PhoneHit', 'PhoneHit'], // undo / remove, a ternary pair, 26 px - 'features/settings/Settings.tsx': ['PhoneHit'], // mobile-only header close, 40 px - 'features/settings/about/About.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/general/General.tsx': ['PhoneHit', 'PhoneHit', 'PhoneHit'], // reset / info (ternary), header close - 'features/settings/account/Account.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/devices/Devices.tsx': ['PhoneHit'], // header close, 40 px - }; - - it.each(Object.entries(expected))('%s carries the right hit-area class', (file, want) => { - expectPhoneHitClasses(file, want); - }); - - // Plain PhoneHit has no size to tie, so nothing is allow-listed; the check still fails an allow-list entry - // or a sized variant that disagrees with the drawn size if one is added later. - it.each(Object.keys(expected))('%s ties a sized variant to the drawn size', (file) => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.settingsB.test.ts b/src/app/phoneHit.settingsB.test.ts deleted file mode 100644 index 4d2e3dee..00000000 --- a/src/app/phoneHit.settingsB.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Each IconButton here is alone in its slot (a dialog header's close, an input's clear button, a tile's lone -// menu or chevron button, its neighbours being text or a badge), so each takes PhoneHit. Every size is derivable -// from the source, so nothing is allow-listed; plain PhoneHit has no number to tie. -const files: [string, string[]][] = [ - ['features/settings/account/Profile.tsx', ['PhoneHit', 'PhoneHit']], - ['features/settings/account/IgnoredUserList.tsx', ['PhoneHit']], - ['features/settings/devices/Verification.tsx', ['PhoneHit']], - ['features/settings/devices/DeviceTile.tsx', ['PhoneHit']], - ['pages/auth/ServerPicker.tsx', ['PhoneHit']], - ['components/BackupRestore.tsx', ['PhoneHit']], - ['components/DeviceVerification.tsx', ['PhoneHit']], - ['components/DeviceVerificationSetup.tsx', ['PhoneHit', 'PhoneHit']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('gives each icon button its variant', () => expectPhoneHitClasses(file, want)); - it('ties each sized variant to the size it draws', () => expectSizeTie(file)); -}); diff --git a/src/app/phoneHit.viewers.test.ts b/src/app/phoneHit.viewers.test.ts deleted file mode 100644 index 3e579f4c..00000000 --- a/src/app/phoneHit.viewers.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Viewer headers and the UIA stages. The back/close button sits beside a title that is not tappable, so it is a -// plain PhoneHit; the zoom out/in buttons sit either side of a tappable zoom Chip, so they spread at their drawn -// 24 px (IconButton size 300 around a 16 px Icon). -// Not covered: the two scroll arrows of components/url-preview/UrlPreviewCard.tsx. They are position: absolute and -// PhoneHit sets position: relative on phones, which would pull them into the flow; they need a variant that keeps -// the position, which PhoneHit.css.ts does not have yet. -const files: [string, string[]][] = [ - ['components/uia-stages/PasswordStage.tsx', ['PhoneHit']], - ['components/uia-stages/SSOStage.tsx', ['PhoneHit']], - ['components/UIAFlowOverlay.tsx', ['PhoneHit']], - ['components/text-viewer/TextViewer.tsx', ['PhoneHit']], - ['components/image-editor/ImageEditor.tsx', ['PhoneHit']], - ['components/image-viewer/ImageViewer.tsx', ['PhoneHit', 'PhoneHitSpread24', 'PhoneHitSpread24']], - ['components/Pdf-viewer/PdfViewer.tsx', ['PhoneHit', 'PhoneHitSpread24', 'PhoneHitSpread24']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('gives each icon button the variant of its surroundings', () => { - expectPhoneHitClasses(file, want); - }); - it('ties each sized variant to the size the button draws', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHitTestKit.test.ts b/src/app/phoneHitTestKit.test.ts deleted file mode 100644 index 77bfc9fd..00000000 --- a/src/app/phoneHitTestKit.test.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { mkdtempSync, rmSync, writeFileSync } from 'fs'; -import { tmpdir } from 'os'; -import { relative } from 'path'; -import { - drawnPx, - expectPhoneHitClasses, - expectSizeTie, - iconButtons, - phoneHitOf, - uncoveredIconButtons, -} from './phoneHitTestKit'; - -describe('phone hit test kit', () => { - it('reads { - const src = - ''; - expect(iconButtons(src).map((b) => b.tag)).toEqual([ - '', - '', - ]); - }); - - it('derives a drawn size from literal size props, defaults being 400', () => { - expect(drawnPx('', '')).toEqual({ px: 24 }); - expect(drawnPx('', '')).toEqual({ px: 40 }); - }); - - it('reads { - expect( - drawnPx('', '') - ).toEqual({ - px: 24, - }); - }); - - it('calls a size undetermined when props are spread into the IconButton or the Icon', () => { - expect(drawnPx('', '')).toHaveProperty('undetermined'); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - expect(drawnPx('', '')).toHaveProperty('undetermined'); - }); - - it('fails a file with no IconButton, which would otherwise pass vacuously', () => { - expect(() => expectSizeTie('styles/PhoneHit.css.ts')).toThrow(/no IconButton/); - }); - - describe('phoneHitOf reads the imported class off the AST, applied unconditionally', () => { - const tag = (expr: string) => ``; - const ok = (expr: string, name: string) => expect(phoneHitOf(tag(expr))).toBe(name); - const no = (expr: string) => expect(phoneHitOf(tag(expr))).toBeNull(); - - it('accepts the bare identifier and merges that always include it', () => { - ok('PhoneHitSpread26', 'PhoneHitSpread26'); - ok('classNames(PhoneHitRoom36, css.other)', 'PhoneHitRoom36'); - ok('clsx(css.a, { [css.b]: on }, PhoneHit)', 'PhoneHit'); - ok('cx(PhoneHit)', 'PhoneHit'); - ok('`${PhoneHit} ${css.other}`', 'PhoneHit'); - ok('classNames(/* PhoneHit */ PhoneHit)', 'PhoneHit'); - }); - - it('rejects the name as a string, a concatenation or a comment', () => { - no("'PhoneHitSpread26'"); - no('`PhoneHitSpread26`'); - no('"PhoneHitSpread26" + "x"'); - no("'PhoneHit' + 'Spread26'"); - no('/* PhoneHit */ undefined'); - no('css.a // PhoneHit'); - }); - - it('rejects a conditionally applied name', () => { - no('cond ? PhoneHitSpread26 : undefined'); - no('cond && PhoneHitSpread26'); - no('cond || PhoneHitSpread26'); - no('maybe ?? PhoneHitSpread26'); - no("classNames(cond ? PhoneHit : '', css.a)"); - no('classNames(PhoneHit, cond && PhoneHit)'); - }); - - it('rejects every other expression shape the name can hide in', () => { - no('classNames({ PhoneHit: on })'); - no('clsx({ [PhoneHit]: on })'); - no('`${`${PhoneHit}`}`'); - no('typeof PhoneHit'); - no("(PhoneHit = 'x')"); - no('(PhoneHit, css.a)'); - no('(PhoneHit)'); - no('() => PhoneHit'); - no('PhoneHit.foo'); - no('other.PhoneHit'); - no('classNames(css.a, [PhoneHit])'); - no('wrap(PhoneHit)'); - no('PhoneHitSpread26é'); - no('`${css.a}`'); - }); - - it('rejects a tag without className, with two, or with a non-expression one', () => { - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBe('PhoneHit'); - }); - - it('rejects a spread after className, which can override it, and accepts one before', () => { - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBe('PhoneHit'); - }); - - it('reads a className past braces inside strings', () => { - ok("classNames('{', PhoneHit)", 'PhoneHit'); - }); - }); - - describe('expectPhoneHitClasses', () => { - const check = (src: string, want: (string | null)[]) => { - const dir = mkdtempSync(`${tmpdir()}/phone-hit-kit-`); - try { - writeFileSync(`${dir}/Probe.tsx`, src); - expectPhoneHitClasses(relative(`${process.cwd()}/src/app`, `${dir}/Probe.tsx`), want); - } finally { - rmSync(dir, { recursive: true }); - } - }; - const imp = "import { PhoneHit, PhoneHitSpread26 } from '../../styles/PhoneHit.css';\n"; - const src = - imp + - 'const A = () => (<>);'; - - it('pins each button in order, null meaning no class', () => { - check(src, ['PhoneHit', 'PhoneHitSpread26', null]); - expect(() => check(src, ['PhoneHit', 'PhoneHit', null])).toThrow(); - expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26', 'PhoneHit'])).toThrow(); - expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26'])).toThrow(); - }); - - it('fails a name that is not read from PhoneHit.css or is applied conditionally', () => { - const local = "const PhoneHit = 'x';\n"; - expect(() => check(local, ['PhoneHit'])).toThrow(); - expect(() => check(local, [null])).not.toThrow(); - const cond = imp + ''; - expect(() => check(cond, ['PhoneHit'])).toThrow(); - const aliased = - "import { Other as PhoneHit } from '../../styles/PhoneHit.css';\n"; - expect(() => check(aliased, ['PhoneHit'])).toThrow(); - const wrongModule = - "import { PhoneHit } from './other';\n"; - expect(() => check(wrongModule, ['PhoneHit'])).toThrow(); - }); - }); - - describe('uncoveredIconButtons: the coverage guard is not blind to a spelling of IconButton', () => { - const imp = "import { PhoneHit } from '../styles/PhoneHit.css';\n"; - const none = { bare: [], unhandled: [] }; - - it('sees an IconButton imported under an alias, as a tag', () => { - const bare = "import { IconButton as IB } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] }); - const ok = `${imp}import { IconButton as IB } from 'folds';\nconst A = () => ;`; - expect(uncoveredIconButtons(ok)).toEqual(none); - }); - - it('sees a namespace member tag', () => { - const bare = "import * as F from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] }); - const ok = `${imp}import * as F from 'folds';\nconst A = () => ;`; - expect(uncoveredIconButtons(ok)).toEqual(none); - }); - - it('fails loudly on an IconButton passed or bound as a value, and on a re-export', () => { - const asProp = - "import { IconButton } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(asProp).unhandled).toEqual(['2:26']); - const aliasValue = - "import { IconButton as IB } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(aliasValue).unhandled).toEqual(['2:26']); - const rebound = "import { IconButton } from 'folds';\nconst B = IconButton;"; - expect(uncoveredIconButtons(rebound).unhandled).toEqual(['2:11']); - const destructured = "import * as F from 'folds';\nconst { IconButton: IB } = F;"; - expect(uncoveredIconButtons(destructured).unhandled).toEqual(['2:9']); - const member = "import * as F from 'folds';\nconst B = F.IconButton;"; - expect(uncoveredIconButtons(member).unhandled).toEqual(['2:13']); - const indexed = "import * as F from 'folds';\nconst B = F['IconButton'];"; - expect(uncoveredIconButtons(indexed).unhandled).toEqual(['2:13']); - expect(uncoveredIconButtons("export { IconButton } from 'folds';").unhandled).toHaveLength(1); - }); - - it('reads a non-.tsx file by its extension', () => { - const ts = - "import { IconButton } from 'folds';\nexport const x = (v: T) => ;"; - expect(uncoveredIconButtons(ts, 'x.tsx').bare).toEqual([0]); - const js = "import { IconButton } from 'folds';\nexport const B = IconButton;"; - expect(uncoveredIconButtons(js, 'x.ts').unhandled).toEqual(['2:18']); - expect(uncoveredIconButtons(js, 'x.js').unhandled).toEqual(['2:18']); - const jsx = "import { IconButton } from 'folds';\nexport const A = () => ;"; - expect(uncoveredIconButtons(jsx, 'x.jsx').bare).toEqual([0]); - }); - - it('does not count IconButtonX, a comment or a string as an IconButton', () => { - const src = - "import { IconButtonGroup } from 'folds';\n// IconButton\nconst a = 'IconButton';\nconst A = () => ;"; - expect(uncoveredIconButtons(src)).toEqual(none); - }); - - it('does not count a PhoneHit that an inner scope rebinds', () => { - const tag = ''; - const cases = [ - `const A = (PhoneHit) => ${tag};`, - `const A = ({ PhoneHit }) => ${tag};`, - `const A = ([a, PhoneHit]) => ${tag};`, - `function A() { const PhoneHit = 'x'; return ${tag}; }`, - `function A() { return ${tag}; var PhoneHit; }`, - `function A() { if (a) { var PhoneHit = 'x'; } return ${tag}; }`, - `function A() { { let { PhoneHit } = o; return ${tag}; } }`, - `function A() { function PhoneHit() {} return ${tag}; }`, - `function A() { for (const PhoneHit of xs) { return ${tag}; } }`, - `function A() { try { f(); } catch (PhoneHit) { return ${tag}; } }`, - `const A = function PhoneHit() { return ${tag}; };`, - `function A() { switch (x) { case 1: const PhoneHit = 'x'; return ${tag}; } }`, - ]; - cases.forEach((c) => expect(uncoveredIconButtons(`${imp}${c}`).bare, c).toEqual([0])); - // the same shapes without the rebinding count, and a rebinding that is not in scope does not hide it - expect(uncoveredIconButtons(`${imp}const A = () => ${tag};`).bare).toEqual([]); - expect( - uncoveredIconButtons(`${imp}const f = (PhoneHit) => 1;\nconst A = () => ${tag};`).bare - ).toEqual([]); - expect(uncoveredIconButtons(`${imp}function A() { return ${tag}; }`).bare).toEqual([]); - }); - - it('does not count an import type of PhoneHit', () => { - const tag = 'const A = () => ;'; - const typeOnly = `import type { PhoneHit } from '../styles/PhoneHit.css';\n${tag}`; - expect(uncoveredIconButtons(typeOnly).bare).toEqual([0]); - const typeSpecifier = `import { type PhoneHit } from '../styles/PhoneHit.css';\n${tag}`; - expect(uncoveredIconButtons(typeSpecifier).bare).toEqual([0]); - expect(uncoveredIconButtons(`${imp}${tag}`).bare).toEqual([]); - }); - }); - - describe('drawnPx reads the parsed tag, not its text', () => { - it('ignores a size in a string, comment or other prop name', () => { - expect(drawnPx('', '')).toEqual({ px: 40 }); - expect(drawnPx('', '')).toEqual({ - px: 40, - }); - expect( - drawnPx('', '{/* */}') - ).toEqual({ - px: 24, - }); - expect(drawnPx('', '{""}')).toHaveProperty( - 'undetermined' - ); - }); - - it('reads a size from a braced string, and the last size wins', () => { - expect(drawnPx("", '')).toEqual({ px: 24 }); - expect(drawnPx('', '')).toEqual({ - px: 40, - }); - }); - - it('reads an Icon spread after a size, and a size past a braced prop with a > inside', () => { - expect(drawnPx(' a > b} size="300">', '')).toEqual({ - px: 32, - }); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - }); - }); -}); diff --git a/src/app/phoneHitTestKit.ts b/src/app/phoneHitTestKit.ts deleted file mode 100644 index b6752183..00000000 --- a/src/app/phoneHitTestKit.ts +++ /dev/null @@ -1,384 +0,0 @@ -// Shared helpers for the phone hit-area tests (phoneTapTargets.test.ts and one phoneHit..test.ts per later -// group of IconButtons). Not a test file: it registers nothing, the test files call it. -import { readFileSync } from 'fs'; -import { expect } from 'vitest'; -import ts from 'typescript'; -import zlib from 'zlib'; -import { compile, processVanillaFile } from '@vanilla-extract/integration'; - -// The CSS a .css.ts file emits, read back from vanilla-extract's own compile (as pages/auth/footerBand.test.ts does; -// vanilla-extract gzips the inlined source only when it is large, so both forms are read). -const compiled = async (file: string) => { - const filePath = `${process.cwd()}/src/app/${file}`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - return processVanillaFile({ source, filePath, identOption: 'debug' }); -}; - -/** The class list each export of a .css.ts file resolves to (a composed class lists the classes it composes). */ -export const classLists = async (file: string): Promise> => - Object.fromEntries( - [...(await compiled(file)).matchAll(/^export var (\w+) = '([^']*)';$/gm)].map((m) => [ - m[1], - m[2].split(' '), - ]) - ); - -export const emitted = async (file: string) => { - const code = await compiled(file); - // A file with recipes inlines one source per rule group; read them all. - return [...code.matchAll(/source=#?([A-Za-z0-9+/=]+)/g)] - .map((m) => { - const bytes = Buffer.from(m[1], 'base64'); - return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString(); - }) - .join('\n'); -}; - -export type Decls = Record; -const parse = (body: string): Decls => - Object.fromEntries( - body - .split('\n') - .map((l) => l.trim().replace(/;$/, '')) - .filter((l) => /^[a-z-]+: -?\d+px$/.test(l)) - .map((l) => [l.split(':')[0], Number(l.split(': ')[1].replace('px', ''))]) - ); - -/** Pixel declarations of the rules whose selector matches, inside or outside a media query. */ -export const rulesFor = (css: string, selector: RegExp, media: string | undefined): Decls[] => { - const scope = media - ? [...css.matchAll(/@media ([^{]+) \{\n([\s\S]*?\n)\}(?:\n|$)/g)] - .filter((m) => m[1] === media) - .map((m) => m[2]) - .join('\n') - : css.replace(/@media [^{]+ \{\n[\s\S]*?\n\}(?:\n|$)/g, ''); - return [...scope.matchAll(/^\s*([^{}\n]+) \{\n([^}]*)\}/gm)] - .filter((m) => selector.test(m[1])) - .map((m) => parse(m[2])); -}; - -/** The source of a file under src/app. */ -export const readSource = (file: string) => - readFileSync(`${process.cwd()}/src/app/${file}`, 'utf8'); - -// The extension picks the script kind (.ts reads `x` as an assertion, .tsx and .jsx read it as JSX). -const tsx = (src: string, fileName = 'source.tsx') => - ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true); - -type Opening = ts.JsxOpeningElement | ts.JsxSelfClosingElement; - -const isTag = (n: ts.Node): n is Opening => - ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n); - -/** Local names the source binds IconButton to by import: IconButton itself and any alias (IconButton as IB). */ -const iconButtonNames = (sf: ts.SourceFile) => { - const names = new Set(['IconButton']); - sf.statements.forEach((st) => { - const nb = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : undefined; - if (nb && ts.isNamedImports(nb)) - nb.elements.forEach((e) => { - if ((e.propertyName ?? e.name).text === 'IconButton') names.add(e.name.text); - }); - }); - return names; -}; - -/** Whether a JSX tag name is an IconButton: the plain or aliased identifier, or a namespace member (). */ -const isIconButtonTag = (tag: ts.JsxTagNameExpression, names: Set) => - (ts.isIdentifier(tag) && names.has(tag.text)) || - (ts.isPropertyAccessExpression(tag) && tag.name.text === 'IconButton'); - -/** Every IconButton element (not IconButtonX) of a parsed source, in source order, however its tag is spelled. */ -const elements = (sf: ts.SourceFile) => { - const names = iconButtonNames(sf); - const found: Opening[] = []; - const walk = (n: ts.Node) => { - if (isTag(n) && isIconButtonTag(n.tagName, names)) found.push(n); - ts.forEachChild(n, walk); - }; - walk(sf); - return found; -}; - -/** Every mention of IconButton that is not a JSX tag or the import itself: passed as a value (as={IconButton}), - * re-bound, re-exported, reached by destructuring or by an element access. Such a render cannot be tied to a - * PhoneHit class, so each is reported ("line:col") and the guard fails on it. */ -const unhandledMentions = (sf: ts.SourceFile) => { - const names = iconButtonNames(sf); - const out: string[] = []; - const at = (n: ts.Node) => { - const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); - out.push(`${line + 1}:${character + 1}`); - }; - const walk = (n: ts.Node) => { - if (ts.isIdentifier(n) && names.has(n.text)) { - const p = n.parent; - const tagged = (x: ts.Node) => - (isTag(x) || ts.isJsxClosingElement(x)) && x.tagName === (n as ts.Node); - const member = - ts.isPropertyAccessExpression(p) && - p.name === n && - (isTag(p.parent) || ts.isJsxClosingElement(p.parent)) && - p.parent.tagName === p; - if (!ts.isImportSpecifier(p) && !tagged(p) && !member) at(n); - } else if ( - ts.isStringLiteralLike(n) && - n.text === 'IconButton' && - ts.isElementAccessExpression(n.parent) - ) - at(n); - ts.forEachChild(n, walk); - }; - walk(sf); - return out; -}; - -const bodyOf = (el: Opening) => - ts.isJsxOpeningElement(el) && ts.isJsxElement(el.parent) - ? el.getSourceFile().text.slice(el.end, el.parent.closingElement.getStart()) - : ''; - -/** Every - elements(tsx(src)).map((el) => ({ tag: el.getText(), body: bodyOf(el) })); - -export const iconButtonTags = (src: string) => iconButtons(src).map((b) => b.tag); - -/** Local names the source imports as values from the PhoneHit.css module (as written, not aliased). An - * `import type`, or a `type` specifier, binds no value and is not read. */ -const importedHits = (sf: ts.SourceFile) => - new Set( - sf.statements.flatMap((st) => { - if (!ts.isImportDeclaration(st) || !ts.isStringLiteral(st.moduleSpecifier)) return []; - const nb = st.importClause?.namedBindings; - return nb && - !st.importClause?.isTypeOnly && - ts.isNamedImports(nb) && - /^(\.\.\/)+styles\/PhoneHit\.css$/.test(st.moduleSpecifier.text) - ? nb.elements.filter((e) => !e.propertyName && !e.isTypeOnly).map((e) => e.name.text) - : []; - }) - ); - -const bindingNames = (b: ts.BindingName): string[] => - ts.isIdentifier(b) - ? [b.text] - : b.elements.flatMap((e) => (ts.isOmittedExpression(e) ? [] : bindingNames(e.name))); - -const declaresVar = (list: ts.VariableDeclarationList, name: string) => - list.declarations.some((d) => bindingNames(d.name).includes(name)); - -/** Whether `var name` is declared anywhere in a function body, outside nested functions (var hoists to the function). */ -const hoistsVar = (fn: ts.Node, name: string) => { - let found = false; - const walk = (n: ts.Node) => { - if (found || (n !== fn && ts.isFunctionLike(n))) return; - if ( - ts.isVariableDeclarationList(n) && - // eslint-disable-next-line no-bitwise -- NodeFlags is a bit set; var is the one declaration kind with neither flag - (n.flags & ts.NodeFlags.BlockScoped) === 0 && - declaresVar(n, name) - ) - found = true; - ts.forEachChild(n, walk); - }; - walk(fn); - return found; -}; - -/** Whether one scope node declares `name` of its own: parameters, a function expression's own name, block-level - * let/const/function/class, a for-loop head or a catch variable. */ -const scopeDeclares = (scope: ts.Node, name: string): boolean => { - const inStatements = (sts: readonly ts.Statement[]) => - sts.some( - (st) => - (ts.isVariableStatement(st) && declaresVar(st.declarationList, name)) || - ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) && st.name?.text === name) - ); - if (ts.isBlock(scope) || ts.isModuleBlock(scope)) return inStatements(scope.statements); - if (ts.isCaseBlock(scope)) return inStatements(scope.clauses.flatMap((c) => [...c.statements])); - if (ts.isFunctionLike(scope)) - return ( - scope.parameters.some((p) => bindingNames(p.name).includes(name)) || - ((ts.isFunctionExpression(scope) || ts.isClassExpression(scope)) && - scope.name?.text === name) || - hoistsVar(scope, name) - ); - if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) - return ( - !!scope.initializer && - ts.isVariableDeclarationList(scope.initializer) && - declaresVar(scope.initializer, name) - ); - if (ts.isCatchClause(scope)) - return ( - !!scope.variableDeclaration && bindingNames(scope.variableDeclaration.name).includes(name) - ); - return false; -}; - -/** Whether an inner scope between the identifier and the module rebinds its name, so it is not the import. */ -const shadowed = (id: ts.Identifier) => { - for (let n: ts.Node | undefined = id.parent; n && !ts.isSourceFile(n); n = n.parent) - if (scopeDeclares(n, id.text)) return true; - return false; -}; - -const MERGERS = new Set(['classNames', 'clsx', 'cx']); - -/** The PhoneHit* class an IconButton carries, or null. className must appear exactly once, with no props spread - * after it (a spread can override it at runtime), and its expression must be: the bare identifier; a classNames / - * clsx / cx call with it as a direct argument; or a template with it as a direct span. The identifier must occur - * nowhere else in the expression, so a key, a member, a closure, a conditional or a comma can never carry it. When - * `imported` is given, the identifier must also resolve to a value binding imported from the PhoneHit.css module - * (not an `import type`, not rebound by an inner scope). */ -const hitOf = (el: Opening, imported?: Set): string | null => { - const props = el.attributes.properties; - const at = props.flatMap((p, i) => - ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'className' ? [i] : [] - ); - if (at.length !== 1 || props.slice(at[0] + 1).some(ts.isJsxSpreadAttribute)) return null; - const attr = props[at[0]] as ts.JsxAttribute; - const expr = - attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression; - if (!expr) return null; - const isHit = (n: ts.Node): n is ts.Identifier => - ts.isIdentifier(n) && - /^PhoneHit\w*$/.test(n.text) && - (!imported || (imported.has(n.text) && !shadowed(n))); - let direct: ts.Node[] = []; - if (ts.isIdentifier(expr)) direct = [expr]; - else if ( - ts.isCallExpression(expr) && - ts.isIdentifier(expr.expression) && - MERGERS.has(expr.expression.text) - ) - direct = [...expr.arguments]; - else if (ts.isTemplateExpression(expr)) direct = expr.templateSpans.map((sp) => sp.expression); - const hits = direct.filter(isHit); - if (hits.length !== 1) return null; - let occurrences = 0; - const count = (n: ts.Node) => { - if (ts.isIdentifier(n) && n.text === hits[0].text) occurrences += 1; - ts.forEachChild(n, count); - }; - count(expr); - return occurrences === 1 ? hits[0].text : null; -}; - -/** The PhoneHit* class of one tag's text (see hitOf), without the import-binding check. */ -export const phoneHitOf = (tag: string) => { - const els = elements(tsx(tag.endsWith('/>') ? tag : `${tag}`)); - return els.length === 1 ? hitOf(els[0]) : null; -}; - -/** The PhoneHit* class of each IconButton of a source, in source order; null when it has none or the name is not - * the one imported from PhoneHit.css. */ -export const phoneHitClasses = (src: string) => { - const sf = tsx(src); - const imported = importedHits(sf); - return elements(sf).map((el) => hitOf(el, imported)); -}; - -/** What a source file leaves uncovered: the indices (source order) of its IconButton elements without a PhoneHit - * class, and the "line:col" of every mention of IconButton that is not a tag and so cannot be checked at all. The - * fileName picks the parser (.ts, .tsx, .js, ...). */ -export const uncoveredIconButtons = (src: string, fileName = 'source.tsx') => { - const sf = tsx(src, fileName); - const imported = importedHits(sf); - return { - bare: elements(sf).flatMap((el, i) => (hitOf(el, imported) === null ? [i] : [])), - unhandled: unhandledMentions(sf), - }; -}; - -/** The class each IconButton must carry, in source order (null = must carry none): the variant is chosen by the - * button's drawn size and whether a clipping container or neighbours surround it, so a swapped variant is a wrong - * hit area. The name must also be the one PhoneHit.css exports, not a local of the same name. */ -export const expectPhoneHitClasses = (file: string, want: (string | null)[]) => - expect(phoneHitClasses(readSource(file))).toEqual(want); - -// IconButton `size` -> padding on each side, Icon `size` -> px (folds 2.7.2). Both default to 400. -const BUTTON_PAD: Record = { '300': 4, '400': 8, '500': 12, '600': 16 }; -const ICON_PX: Record = { - '50': 16, - '100': 18, - '200': 20, - '300': 22, - '400': 24, - '500': 28, -}; - -/** The size prop of a tag: its literal value, the default when absent, or undefined when it is an expression. */ -const sizeProp = (el: Opening) => { - const props = el.attributes.properties; - // props spread in may carry a size of their own - if (props.some(ts.isJsxSpreadAttribute)) return undefined; - const sizes = props.filter( - (p): p is ts.JsxAttribute => - ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'size' - ); - if (sizes.length === 0) return '400'; - const init = sizes[sizes.length - 1].initializer; - const lit = init && ts.isJsxExpression(init) ? init.expression : init; - return lit && ts.isStringLiteralLike(lit) ? lit.text : undefined; -}; - -/** The px an IconButton draws, from its size prop and the Icon inside; undefined with a reason when the source - * does not say (a variable size, no Icon, Icons of different sizes). Both are read off the parsed tag and body. */ -export const drawnPx = (tag: string, body: string): { px: number } | { undetermined: string } => { - let button: Opening | undefined; - const first = (n: ts.Node) => { - if (!button && isTag(n)) button = n; - else if (!button) ts.forEachChild(n, first); - }; - first(tsx(tag.endsWith('/>') ? tag : `${tag}`)); - const pad = BUTTON_PAD[(button && sizeProp(button)) ?? '']; - if (pad === undefined) - return { undetermined: 'size of the IconButton is not a literal (or props are spread in)' }; - const icons: (number | undefined)[] = []; - const find = (n: ts.Node) => { - if (isTag(n) && ts.isIdentifier(n.tagName) && n.tagName.text === 'Icon') - icons.push(ICON_PX[sizeProp(n) ?? '']); - ts.forEachChild(n, find); - }; - find(tsx(`<>${body}`)); - if (icons.length === 0) return { undetermined: 'no inside' }; - if (icons.some((p) => p === undefined)) - return { undetermined: 'size of an Icon is not a literal (or props are spread in)' }; - if (new Set(icons).size > 1) return { undetermined: 'Icons of different sizes inside' }; - return { px: (icons[0] as number) + 2 * pad }; -}; - -/** Per file, per IconButton index (source order): why its drawn size cannot be derived from the source. */ -export type SizeAllow = Record>; - -/** A button carrying PhoneHitSpread or PhoneHitRoom draws N px. Plain PhoneHit has no number to tie. An - * undetermined size passes only with an entry in `allow`, and an entry for a size that can be derived fails. */ -export const expectSizeTie = (file: string, allow: SizeAllow = {}) => { - const allowed = allow[file] ?? {}; - const seen = new Set(); - const src = readSource(file); - const buttons = iconButtons(src); - const classes = phoneHitClasses(src); - expect(buttons.length, `${file} has no IconButton`).toBeGreaterThan(0); - buttons.forEach(({ tag, body }, i) => { - const variant = classes[i]?.match(/^PhoneHit(?:Spread|Room)(\d+)$/); - if (!variant) { - expect(allowed[i], `${file} #${i} is allow-listed but has no sized variant`).toBeUndefined(); - return; - } - const drawn = drawnPx(tag, body); - if ('undetermined' in drawn) { - expect( - allowed[i], - `${file} #${i}: ${drawn.undetermined}; add it to the allow-list` - ).toBeDefined(); - seen.add(i); - return; - } - expect(allowed[i], `${file} #${i} is allow-listed but its size is derivable`).toBeUndefined(); - expect(Number(variant[1]), `${file} #${i} draws ${drawn.px} px`).toBe(drawn.px); - }); - expect(Object.keys(allowed).map(Number).sort()).toEqual([...seen].sort()); -}; diff --git a/src/app/phoneTapTargets.test.ts b/src/app/phoneTapTargets.test.ts deleted file mode 100644 index bbcde9e6..00000000 --- a/src/app/phoneTapTargets.test.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { - classLists, - emitted, - expectPhoneHitClasses, - expectSizeTie, - rulesFor, - type SizeAllow, -} from './phoneHitTestKit'; - -const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; -const TAP = 44; - -// [target, css file, selector, measured height in CSS px on the Starfire phone run (390x844), free space measured -// above and below the target before its neighbour's box (taps2-REPORT.md): the hit area may reach out of the layout -// box (negative margin) by no more than that, or it takes taps from its neighbour. Space it needs beyond that is -// real layout growth, which the rules above take from the padding the margin does not give back. -const targets: [string, string, RegExp, number, number, number][] = [ - [ - 'sender-name button', - 'components/message/layout/layout.css.ts', - /^button\.layout_Username__/, - 23, - 11, - 11, - ], - [ - 'room-topic button', - 'features/room/RoomViewHeader.css.ts', - /RoomViewHeader_HeaderTopic__\w+$/, - 18, - 0, - 26, - ], - ['sign-in card links', 'pages/auth/styles.css.ts', /styles_AuthCard__\w+ a$/, 16, 14, 14], - [ - 'forget-password link', - 'pages/auth/styles.css.ts', - /styles_AuthCard__\w+ a\.styles_ForgotLink__\w+$/, - 16, - 5, - 16, - ], - // The footer's rows are 22 px apart on a phone (AuthFooterLinks), 11 px for each side of the gap. - ['sign-in footer links', 'pages/auth/styles.css.ts', /styles_AuthFooter__\w+ a$/, 22, 11, 11], -]; - -describe.each(targets)('phone tap target: %s', (_name, file, selector, height, above, below) => { - it(`grows its hit area to ${TAP} px without moving layout`, async () => { - const css = await emitted(file); - const [phone] = rulesFor(css, selector, PHONE); - expect(phone, 'a phone rule exists').toBeDefined(); - const top = phone['padding-top'] ?? phone['padding-block'] ?? 0; - const bottom = phone['padding-bottom'] ?? phone['padding-block'] ?? 0; - const marginTop = phone['margin-top'] ?? phone['margin-block'] ?? 0; - const marginBottom = phone['margin-bottom'] ?? phone['margin-block'] ?? 0; - expect(height + top + bottom).toBeGreaterThanOrEqual(TAP); - // the hit area reaches out of the layout box by no more than the free space on that side - expect(-marginTop).toBeLessThanOrEqual(above); - expect(-marginBottom).toBeLessThanOrEqual(below); - expect(marginTop).toBeLessThanOrEqual(0); - expect(marginBottom).toBeLessThanOrEqual(0); - }); - - it('leaves every other screen as it was: no padding or margin outside the phone query', async () => { - const css = await emitted(file); - rulesFor(css, selector, undefined).forEach((decls) => - expect(Object.keys(decls).filter((k) => /^(padding|margin)/.test(k))).toEqual([]) - ); - }); -}); - -describe('phone navigator rows', () => { - // The links and buttons inside a row are 44 px (EstateNavigator.css.ts); a row shorter than that lets them spill - // onto the next row (the 38 px pitch of taps2-REPORT.md), so the row and the section header are 44 too. - it('are as tall as their tap targets', async () => { - const css = await emitted('components/nav/styles.css.ts'); - const phone = [ - ...css.matchAll(/@media screen and \(max-width: 750px\) \{\n([\s\S]*?\n)\}(?:\n|$)/g), - ] - .map((m) => m[1]) - .join('\n'); - expect(phone.match(/min-height: 2\.75rem/g)?.length).toBeGreaterThanOrEqual(2); - }); -}); - -describe('phone icon-button hit areas', () => { - const stripPhone = (css: string) => css.replace(/@media [^{]+ \{\n[\s\S]*?\n\}(?:\n|$)/g, ''); - - it('draw a 44 x 44 box around the button on a phone and nothing on any other screen', async () => { - const css = await emitted('styles/PhoneHit.css.ts'); - const phone = [...css.matchAll(/@media ([^{]+) \{\n([\s\S]*?\n)\}(?:\n|$)/g)]; - expect(phone.map((m) => m[1])).toEqual([PHONE]); - expect(css).toMatch(/::after \{[^}]*width: max\(100%, 44px\);[^}]*height: max\(100%, 44px\);/); - // no content, no box: the pseudo-element is not rendered at all - expect(css).toMatch(/::after \{[^}]*content: "";/); - expect(css).toMatch(/::after \{[^}]*position: absolute;/); - // centred on the button: top and left at half, pulled back by half its own size - expect(css).toMatch(/::after \{[^}]*top: 50%;/); - expect(css).toMatch(/::after \{[^}]*left: 50%;/); - expect(css).toMatch(/::after \{[^}]*transform: translate\(-50%, -50%\);/); - // the box anchors to its own button, receives the tap, and sits above nothing it should not - expect(css).toMatch(/@media [^{]+ \{\n\s*\.PhoneHit_PhoneHit__\w+ \{\n\s*position: relative;/); - // PhoneHit and PhoneHitInPlace each draw it; the Spread and Room classes compose PhoneHit - const afters = [...css.matchAll(/::after \{\n([^}]*)\}/g)]; - expect(afters).toHaveLength(2); - const afterDecls = afters.flatMap((m) => - m[1] - .split('\n') - .map((l) => l.trim().split(':')[0]) - .filter(Boolean) - ); - expect([...new Set(afterDecls)].sort()).toEqual([ - 'content', - 'height', - 'left', - 'position', - 'top', - 'transform', - 'width', - ]); - // nothing on a phone moves a button off its own anchor: only relative (the button) and absolute (the boxes) - expect([...css.matchAll(/position: (\w+);/g)].map((m) => m[1]).sort()).toEqual([ - 'absolute', - 'absolute', - 'relative', - ]); - expect(stripPhone(css).trim()).toBe(''); - }); - - it('open a row up by half the shortfall, so neighbouring hit areas meet and do not overlap', async () => { - const css = await emitted('styles/PhoneHit.css.ts'); - const margins = (selector: RegExp) => - rulesFor(css, selector, PHONE).map((d) => d['margin-inline']); - // 32 px composer buttons, 40 px header buttons, 26 px message-option buttons (which also open vertically, - // the menu around them clips a hit area drawn outside its box) - // each class owns its own margin: (44 - drawn size) / 2 - const own = (size: number) => margins(new RegExp(`PhoneHit_PhoneHitSpread${size}__`)); - expect([24, 26, 28, 32, 36, 40].map(own)).toEqual([[10], [9], [8], [6], [4], [2]]); - // the Room variants open the block axis by the same amount, on top of their Spread class - const room = (size: number) => - rulesFor(css, new RegExp(`PhoneHit_PhoneHitRoom${size}__`), PHONE); - expect([room(26), room(36)]).toEqual([[{ 'margin-block': 9 }], [{ 'margin-block': 4 }]]); - }); - - it('compose a Room variant from the Spread class of the same size, which composes PhoneHit', async () => { - const lists = await classLists('styles/PhoneHit.css.ts'); - const named = (list: string[], name: string) => list.filter((c) => c.includes(`_${name}__`)); - [26, 36].forEach((size) => { - const room = lists[`PhoneHitRoom${size}`]; - expect( - named(room, `PhoneHitSpread${size}`), - `Room${size} composes Spread${size}` - ).toHaveLength(1); - expect(named(room, 'PhoneHit'), `Room${size} composes PhoneHit`).toHaveLength(1); - }); - expect(lists.PhoneHitRoom36.some((c) => c.includes('_PhoneHitSpread26__'))).toBe(false); - }); - - it("make a message's reaction chip 44 px to tap by opening 9 px above and below it", async () => { - const css = await emitted('components/message/Reaction.css.ts'); - const [chip] = rulesFor(css, /^button\.Reaction_Reaction__\w+$/, PHONE); - expect(chip['margin-block']).toBe((TAP - 26) / 2); - expect(css).toMatch(/::after \{[^}]*inset: -9px 0;/); - rulesFor(css, /^button\.Reaction_Reaction__\w+$/, undefined).forEach((d) => - expect(Object.keys(d)).not.toContain('margin-block') - ); - }); - - it('give a sender name a 44 px wide button too, text kept at its start', async () => { - const css = await emitted('components/message/layout/layout.css.ts'); - const [phone] = rulesFor(css, /^button\.layout_Username__/, PHONE); - expect(phone['min-width']).toBe(TAP); - expect(css).toMatch(/text-align: start;/); - }); -}); - -describe('icon buttons in the room view', () => { - // The class each IconButton must carry, in source order: the variant is chosen by the button's drawn size - // and whether a clipping container or neighbours surround it, so a swapped variant is a wrong hit area. - const expected: Record = { - 'features/room/message/Message.tsx': [ - 'PhoneHitSpread32', // quick-reaction emoji buttons - 'PhoneHitSpread32', // delete dialog close - 'PhoneHitSpread32', // report dialog close - ...Array(6).fill('PhoneHitRoom26'), // message options bar, inside a clipping menu - ], - 'features/room/RoomInput.tsx': ['PhoneHitSpread24', ...Array(5).fill('PhoneHitSpread32')], // reply cancel is a 16 px icon, the rest 24 px - 'features/room/RoomViewHeader.tsx': Array(6).fill('PhoneHitSpread40'), - // The chat path's other buttons. Two neighbours in a row: Spread32. One on its own: the plain PhoneHit. - 'features/room/message/MessageEditor.tsx': ['PhoneHitSpread32', 'PhoneHitSpread32'], // toolbar, emoji - 'features/room-nav/RoomNavItem.tsx': ['PhoneHitSpread24', 'PhoneHitSpread24'], // chat toggle, options: 16 px icon + 8 padding = 24 px, 0 gap - 'features/room/MembersDrawer.tsx': ['PhoneHit', 'PhoneHit'], // close, scroll to top - 'features/room/reaction-viewer/ReactionViewer.tsx': ['PhoneHit'], - 'features/room/room-pin-menu/RoomPinMenu.tsx': ['PhoneHitSpread26', 'PhoneHit'], // unpin (26 px, 8 px from the Open chip), close - 'features/room/RoomViewTyping.tsx': ['PhoneHit'], - 'features/room/CallChatView.tsx': ['PhoneHit'], - 'features/room/jump-to-time/JumpToTime.tsx': ['PhoneHit'], - // Buttons that were fixed with #125 and had no test. - 'components/password-input/PasswordInput.tsx': ['PhoneHit'], - 'features/desk/Desk.tsx': ['PhoneHit'], - 'features/scene/SceneViewEntry.tsx': ['PhoneHit'], // the scene view's entry - 'features/scene/SceneViewHost.tsx': ['PhoneHit'], // Return while the scene view loads - 'features/scene/view/SceneView.tsx': ['PhoneHit'], // one rail button, five icons - 'pages/auth/login/PasswordLoginForm.tsx': ['PhoneHit'], - }; - - // IconButtons whose drawn size the source does not say (file -> index in source order -> why). Everything else - // is derived from the size props, so a Spread32 on a 24 px button fails. - const sizeAllow: SizeAllow = { - 'features/room/message/Message.tsx': { - 0: 'quick-reaction button wraps an emoji , no Icon; 32 px by its CSS class', - }, - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: each sized variant equals the px its button draws', (file) => - expectSizeTie(file, sizeAllow) - ); -}); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 2398a4c9..961131d9 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -22,7 +22,6 @@ import Linkify from 'linkify-react'; import { ErrorBoundary } from 'react-error-boundary'; import { ChildNode } from 'domhandler'; import * as css from '../styles/CustomHtml.css'; -import { PhoneHitSpread24 } from '../styles/PhoneHit.css'; import { getMxIdLocalPart, getCanonicalAliasRoomId, @@ -283,7 +282,6 @@ export function CodeBlock({ variant="SurfaceVariant" outlined radii="300" - className={PhoneHitSpread24} onClick={toggleExpand} aria-label={expanded ? 'Collapse' : 'Expand'} > diff --git a/src/app/styles/PhoneHit.css.ts b/src/app/styles/PhoneHit.css.ts deleted file mode 100644 index e971ecb3..00000000 --- a/src/app/styles/PhoneHit.css.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { style } from '@vanilla-extract/css'; -import { MOBILE_BREAKPOINT } from '../hooks/useScreenSize'; - -// Phone tap target for an icon button: on a phone the button's hit area is 44 x 44 px centred on the drawn -// button (a ::after the button's own click reaches), so nothing drawn changes size. A button with neighbours -// 44 px closer than that would take their taps, so the `Spread` classes also give it horizontal margin of half -// the shortfall: the row grows by that, on phones only, and the hit areas meet instead of overlapping. -// Vertical room is cheaper than horizontal on a phone, so only the horizontal axis pays. -export const PHONE_TAP = 44; -const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; - -const hitArea = { - '@media': { - [PHONE]: { - content: '""', - position: 'absolute', - top: '50%', - left: '50%', - width: `max(100%, ${PHONE_TAP}px)`, - height: `max(100%, ${PHONE_TAP}px)`, - transform: 'translate(-50%, -50%)', - }, - }, -} as const; - -/** An icon button on its own: the hit area grows, nothing else moves. */ -export const PhoneHit = style({ - '@media': { [PHONE]: { position: 'relative' } }, - selectors: { '&::after': hitArea }, -}); - -/** For a button that is already positioned (absolute or fixed) by its own class: PhoneHit's `position: relative` - * would fight that class by stylesheet order, and the positioned button already contains its ::after. */ -export const PhoneHitInPlace = style({ selectors: { '&::after': hitArea } }); - -const spreads = new Map(); - -/** An icon button in a row, `visual` px wide: the row opens up so its 44 px hit area meets its neighbours'. */ -const spread = (visual: number) => { - const cls = style( - [PhoneHit, { '@media': { [PHONE]: { marginInline: (PHONE_TAP - visual) / 2 } } }], - `PhoneHitSpread${visual}` - ); - spreads.set(visual, cls); - return cls; -}; - -export const PhoneHitSpread24 = spread(24); -export const PhoneHitSpread26 = spread(26); -export const PhoneHitSpread28 = spread(28); -export const PhoneHitSpread32 = spread(32); -export const PhoneHitSpread36 = spread(36); -export const PhoneHitSpread40 = spread(40); - -/** For a button in a clipping container (a Menu's overflow hidden eats a hit area drawn outside the box): the row - * opens up on both axes, so the 44 px sits inside the container. It is the Spread class of the same size plus the - * block margin, so the two axes cannot disagree about the size. */ -const room = (visual: number) => { - const spreadClass = spreads.get(visual); - if (!spreadClass) throw new Error(`PhoneHitRoom${visual} needs a PhoneHitSpread${visual}`); - return style( - [spreadClass, { '@media': { [PHONE]: { marginBlock: (PHONE_TAP - visual) / 2 } } }], - `PhoneHitRoom${visual}` - ); -}; - -export const PhoneHitRoom26 = room(26); -export const PhoneHitRoom36 = room(36); diff --git a/src/phoneGlyph.css.ts b/src/phoneGlyph.css.ts index 14707f63..c9d601f6 100644 --- a/src/phoneGlyph.css.ts +++ b/src/phoneGlyph.css.ts @@ -1,14 +1,13 @@ import { globalStyle } from '@vanilla-extract/css'; import { MOBILE_BREAKPOINT } from './app/hooks/useScreenSize'; -// Phone glyph size. On a phone the glyph inside an IconButton is drawn larger, by `scale` (a paint-time transform: -// the button's box, its PhoneHit area and every row of buttons keep the layout they have, so nothing reflows at -// 320 px). folds draws a glyph at one of its Icon sizes and the IconButton's box is padding plus that glyph, so the -// factor is chosen per Icon size. Desktop is not touched. +// Phone IconButton ergonomics: on a phone each IconButton gets a centred 44 x 44 px ::after hit +// area and its glyph scales up at paint time, so nothing reflows at 320 px. Desktop is not touched. // // The class names are folds 2.7.2's own (the Icon size classes and the IconButton base class); phoneGlyph.test.ts -// reads them back from folds' dist, so a folds upgrade that renames them fails there instead of silently here. +// checks them against folds/dist/style.css, so a folds upgrade that renames them fails there instead of silently here. export const ICON_BUTTON_CLASS = 'brs7ce5'; +export const PHONE_TAP = 44; /** folds Icon size -> [its class, its px, the px it is drawn at on a phone]. The 24 px glyph is the folds default and * reads small in a 40 px button, so it grows too; 28 px and up are already large. */ export const PHONE_GLYPHS = { @@ -21,6 +20,24 @@ export const PHONE_GLYPHS = { const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; +globalStyle(`:where(.${ICON_BUTTON_CLASS})`, { + '@media': { [PHONE]: { position: 'relative' } }, +}); + +globalStyle(`.${ICON_BUTTON_CLASS}::after`, { + '@media': { + [PHONE]: { + content: '""', + position: 'absolute', + top: '50%', + left: '50%', + width: `max(100%, ${PHONE_TAP}px)`, + height: `max(100%, ${PHONE_TAP}px)`, + transform: 'translate(-50%, -50%)', + }, + }, +}); + Object.values(PHONE_GLYPHS).forEach(({ cls, px, phonePx }) => globalStyle(`.${ICON_BUTTON_CLASS} > .${cls}`, { '@media': { [PHONE]: { scale: `${phonePx / px}` } }, From 3f6f85d3d53a4a623c7092a0ff300023639eb9ee Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:03:13 +0100 Subject: [PATCH 2/7] teardown(R2.2): remove XHR/AbortController monkey-patching, lifecycle tracking, and full-file RAM copies --- src/app/state/upload.ts | 43 +--- src/app/utils/matrix.ts | 319 ++++--------------------- src/app/utils/uploadAbortProbe.test.ts | 171 ------------- src/app/utils/uploadFailure.test.ts | 10 +- src/app/utils/uploadReason.test.ts | 17 +- src/app/utils/uploadXhrProbe.test.ts | 163 ------------- 6 files changed, 69 insertions(+), 654 deletions(-) delete mode 100644 src/app/utils/uploadAbortProbe.test.ts delete mode 100644 src/app/utils/uploadXhrProbe.test.ts diff --git a/src/app/state/upload.ts b/src/app/state/upload.ts index 84786a29..810c0d2e 100644 --- a/src/app/state/upload.ts +++ b/src/app/state/upload.ts @@ -1,14 +1,9 @@ import { atom, useAtom } from 'jotai'; import { atomFamily } from 'jotai/utils'; import { MatrixClient, UploadResponse, UploadProgress, MatrixError } from 'matrix-js-sdk'; -import { useCallback, useEffect, useRef } from 'react'; +import { useCallback } from 'react'; import { useThrottle } from '../hooks/useThrottle'; -import { - ComponentLifecycle, - describeComponentLifecycle, - uploadContent, - TUploadContent, -} from '../utils/matrix'; +import { uploadContent, TUploadContent } from '../utils/matrix'; export enum UploadStatus { Idle = 'idle', @@ -110,34 +105,22 @@ export const useBindUploadAtom = ( const [upload, setUpload] = useAtom(uploadAtom); const { file } = upload; - // For the failure text: renders and unmount of the component that owns this upload. - const life = useRef({ attachedAt: 0, rendersAtAttach: 0, renders: [] }); - if (life.current.renders.length < 50) life.current.renders.push(Date.now()); - useEffect(() => { - const tracked = life.current; - tracked.unmountedAt = undefined; - return () => { - tracked.unmountedAt = Date.now(); - }; - }, []); - const handleProgress = useThrottle( useCallback((progress: UploadProgress) => setUpload({ progress }), [setUpload]), { immediate: true, wait: 200 } ); - const startUpload = useCallback(() => { - life.current.attachedAt = Date.now(); - life.current.rendersAtAttach = life.current.renders.length; - return uploadContent(mx, file, { - hideFilename, - describeLifecycle: () => describeComponentLifecycle(life.current), - onPromise: (promise: Promise) => setUpload({ promise }), - onProgress: handleProgress, - onSuccess: (mxc) => setUpload({ mxc }), - onError: (error) => setUpload({ error }), - }); - }, [mx, file, hideFilename, setUpload, handleProgress]); + const startUpload = useCallback( + () => + uploadContent(mx, file, { + hideFilename, + onPromise: (promise: Promise) => setUpload({ promise }), + onProgress: handleProgress, + onSuccess: (mxc) => setUpload({ mxc }), + onError: (error) => setUpload({ error }), + }), + [mx, file, hideFilename, setUpload, handleProgress] + ); const cancelUpload = useCallback(async () => { if (upload.status === UploadStatus.Loading) { diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index d4972677..fa01f112 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -18,7 +18,7 @@ import { IImageInfo, IThumbnailContent, IVideoInfo } from '../../types/matrix/co import { AccountDataEvent } from '../../types/matrix/accountData'; import { getStateEvent } from './room'; import { Membership, StateEvent } from '../../types/matrix/room'; -import { NO_INFO, UploadFailureInfo } from './uploadReason'; +import { UploadFailureInfo } from './uploadReason'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -144,22 +144,8 @@ export type ContentUploadOptions = { onProgress?: (progress: UploadProgress) => void; onSuccess: (mxc: string) => void; onError: (error: MatrixError) => void; - /** Read at failure time: what the owning component did since the upload attached. */ - describeLifecycle?: () => string; }; -let lastUserActivity = Date.now(); -export const noteUserActivity = () => { - lastUserActivity = Date.now(); -}; -if (typeof window !== 'undefined') { - ['pointerdown', 'keydown', 'touchstart'].forEach((type) => - window.addEventListener(type, noteUserActivity, { capture: true, passive: true }) - ); -} - -export type AbortCall = { api: string; frames: string }; - /** What the progress handler saw of one upload, for the failure text. */ export type UploadTrace = { startedAt: number; @@ -168,174 +154,9 @@ export type UploadTrace = { total?: number; /** Summary of an earlier attempt of the same upload, when this one is a retry. */ previous?: string; - /** abort() calls the page made while this attempt ran; absent when not probed. */ - aborts?: AbortCall[]; - /** What the owning component did since the upload attached. */ - lifecycle?: string; - /** Upload XHR events and end state, and whether our own signal was aborted. */ - xhr?: string; signalAborted?: boolean; }; -const MAX_FRAMES = 6; -const MAX_ABORT_CALLS = 4; - -/** - * An Error stack as `file:line:col < file:line:col`, at most six frames. The error line and the - * probe's own frame are dropped; origins and function names are not kept. - */ -export const formatAbortStack = (stack: string): string => { - const frames = stack - .split('\n') - .map((l) => l.trim()) - .filter((l) => l.startsWith('at ') || l.includes('@')) - .map((l) => { - const m = /([^/\s()@]+):(\d+):(\d+)\)?$/.exec(l); - return m ? `${m[1]}:${m[2]}:${m[3]}` : undefined; - }) - .filter((f): f is string => f !== undefined) - .slice(1, 1 + MAX_FRAMES); - return frames.length > 0 ? frames.join(' < ') : 'no stack'; -}; - -export type ComponentLifecycle = { - attachedAt: number; - rendersAtAttach: number; - renders: number[]; - unmountedAt?: number; -}; - -/** What the component that owns an upload did after the upload attached to it. */ -export const describeComponentLifecycle = (life: ComponentLifecycle): string => { - const since = life.renders.slice(life.rendersAtAttach); - const quick = since.filter((t) => t - life.attachedAt <= 300).length; - const unmount = - life.unmountedAt === undefined - ? 'not unmounted' - : `unmounted +${life.unmountedAt - life.attachedAt}ms`; - return `component: ${since.length} renders since attach (${quick} within 300ms), ${unmount}`; -}; - -export type XhrRecord = { - xhr: XMLHttpRequest; - method: string; - path: string; - startedAt: number; - events: string[]; -}; - -type Probe = { calls: AbortCall[]; xhrs: XhrRecord[] }; - -const probes = new Set(); -let restoreProbe: (() => void) | undefined; -const xhrTargets = new WeakMap(); - -const XHR_EVENTS = ['loadstart', 'error', 'abort', 'timeout', 'load', 'loadend']; -const MAX_XHR_EVENTS = 12; - -/* eslint-disable no-param-reassign */ -const patchAbort = (proto: { abort: (...a: any[]) => any }, api: string) => { - const original = proto.abort; - const wrapper = function abortProbe(this: unknown, ...args: any[]) { - const frames = formatAbortStack(new Error().stack ?? ''); - probes.forEach(({ calls }) => { - if (calls.length < MAX_ABORT_CALLS) calls.push({ api, frames }); - }); - return original.apply(this, args); - }; - proto.abort = wrapper; - return () => { - if (proto.abort === wrapper) proto.abort = original; - }; -}; - -// Upload XHRs only; the path is kept and the query (it holds the access token) is dropped. -const patchXhr = (proto: XMLHttpRequest) => { - const { open, send } = proto; - const openWrapper = function openProbe(this: XMLHttpRequest, ...args: any[]) { - try { - const url = new URL(String(args[1]), 'http://x'); - if (url.pathname.includes('/upload')) { - xhrTargets.set(this, { method: String(args[0]).toUpperCase(), path: url.pathname }); - } - } catch { - // not a URL we can read; the request is not recorded - } - return (open as any).apply(this, args); - }; - const sendWrapper = function sendProbe(this: XMLHttpRequest, ...args: any[]) { - const target = xhrTargets.get(this); - if (target && probes.size > 0) { - const startedAt = Date.now(); - const events: string[] = []; - const note = (name: string) => () => { - if (events.length < MAX_XHR_EVENTS) events.push(`${name} +${Date.now() - startedAt}ms`); - }; - XHR_EVENTS.forEach((ev) => this.addEventListener(ev, note(ev))); - XHR_EVENTS.forEach((ev) => this.upload?.addEventListener(ev, note(`upload.${ev}`))); - this.upload?.addEventListener( - 'progress', - (() => { - let first = true; - return () => { - if (first) note('upload.progress')(); - first = false; - }; - })() - ); - const record: XhrRecord = { xhr: this, ...target, startedAt, events }; - probes.forEach((probe) => probe.xhrs.push(record)); - } - return (send as any).apply(this, args); - }; - (proto as any).open = openWrapper; - (proto as any).send = sendWrapper; - return () => { - if ((proto as any).open === openWrapper) (proto as any).open = open; - if ((proto as any).send === sendWrapper) (proto as any).send = send; - }; -}; -/* eslint-enable no-param-reassign */ - -const describeXhr = (r: XhrRecord): string => - `${r.method} ${r.path} readyState ${r.xhr.readyState} status ${ - r.xhr.status - } events [${r.events.join(', ')}]`; - -/** - * Records, until stopped, every XMLHttpRequest.abort and AbortController.abort the page makes and - * the lifecycle events and end state of upload XHRs. The prototypes are wrapped while at least one - * probe runs and restored when the last one stops; the wrappers change no behaviour. - */ -export const startAbortProbe = () => { - const probe: Probe = { calls: [], xhrs: [] }; - if (probes.size === 0) { - const restores: (() => void)[] = []; - if (typeof XMLHttpRequest !== 'undefined') { - restores.push(patchAbort(XMLHttpRequest.prototype, 'XHR.abort')); - restores.push(patchXhr(XMLHttpRequest.prototype)); - } - if (typeof AbortController !== 'undefined') { - restores.push(patchAbort(AbortController.prototype, 'AbortController.abort')); - } - restoreProbe = () => restores.forEach((r) => r()); - } - probes.add(probe); - return { - calls: probe.calls, - xhrs: probe.xhrs, - describeXhrs: () => - probe.xhrs.length === 0 ? 'xhr: none seen' : `xhr: ${probe.xhrs.map(describeXhr).join('; ')}`, - stop: () => { - probes.delete(probe); - if (probes.size === 0) { - restoreProbe?.(); - restoreProbe = undefined; - } - }, - }; -}; - const describeNetwork = (): string => { const online = typeof navigator !== 'undefined' && navigator.onLine === false ? 'offline' : 'online'; @@ -352,7 +173,7 @@ const describeNetwork = (): string => { /** * Describe why an upload died. The SDK reports an XHR with status 0 as an AbortError * DOMException with an empty message, so the text carries what the client can observe: file - * size, type and readability, connectivity, tab visibility, idle time, progress, time to fail. + * size, type and readability, connectivity, tab visibility, progress, time to fail. */ export const uploadFailure = async ( e: any, @@ -362,15 +183,16 @@ export const uploadFailure = async ( const now = Date.now(); const name = typeof e?.name === 'string' && e.name ? e.name : 'Error'; const message = typeof e?.message === 'string' ? e.message : ''; - let readable: string; - try { - await file.arrayBuffer(); - readable = 'file readable'; - } catch (readErr: any) { - readable = `file unreadable (${readErr?.name ?? 'unknown'})`; + let readable = + name === 'NotReadableError' ? 'file unreadable (NotReadableError)' : 'file readable'; + if (name !== 'NotReadableError' && typeof file.slice === 'function') { + try { + await file.slice(0, 1).arrayBuffer(); + } catch (readErr: any) { + readable = `file unreadable (${readErr?.name ?? 'unknown'})`; + } } const parts = [`${file.size} bytes`, file.type || 'unknown type', readable, describeNetwork()]; - parts.push(`idle ${now - lastUserActivity}ms`); if (trace) { parts.push( trace.firstProgressAt === undefined @@ -380,16 +202,7 @@ export const uploadFailure = async ( }B` ); parts.push(`failed after ${now - trace.startedAt}ms`); - if (trace.aborts) { - parts.push( - trace.aborts.length === 0 - ? 'abort calls: none' - : `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` - ); - } - if (trace.xhr) parts.push(trace.xhr); if (trace.signalAborted !== undefined) parts.push(`signal.aborted ${trace.signalAborted}`); - if (trace.lifecycle) parts.push(trace.lifecycle); if (trace.previous) parts.push(`retried (attempt 1: ${trace.previous})`); } const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`; @@ -410,101 +223,55 @@ export const uploadFailure = async ( }; // An abort before any progress, within this long, is retried once: the request most likely died on -// a reused connection before a byte left, and the failed attempt discards that connection. Nothing -// here has shown that is the cause; the failure text records both attempts so it can be checked. +// a reused connection before a byte left, and the failed attempt discards that connection. const RETRY_WINDOW_MS = 3000; -const copyInMemory = async (file: TUploadContent): Promise => { - const bytes = await file.arrayBuffer(); - return typeof File !== 'undefined' && file instanceof File - ? new File([bytes], file.name, { type: file.type, lastModified: file.lastModified }) - : new Blob([bytes], { type: file.type }); -}; - export const uploadContent = async ( mx: MatrixClient, file: TUploadContent, options: ContentUploadOptions ) => { - const { - name, - fileType, - hideFilename, - onProgress, - onPromise, - onSuccess, - onError, - describeLifecycle, - } = options; + const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options; let previous: string | undefined; for (let attempt = 1; ; attempt += 1) { - // The browser may hold a picked file as a handle it cannot always re-read (e.g. content://), so - // each attempt uploads a copy held in memory; a file that cannot be read fails here, named. - let body: TUploadContent; + const trace: UploadTrace = { startedAt: Date.now(), previous }; + const abortController = new AbortController(); + const uploadPromise = mx.uploadContent(file, { + name, + type: fileType, + includeFilename: !hideFilename, + abortController, + progressHandler: (progress) => { + if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now(); + trace.loaded = progress.loaded; + trace.total = progress.total; + onProgress?.(progress); + }, + }); + onPromise?.(uploadPromise); try { // eslint-disable-next-line no-await-in-loop - body = await copyInMemory(file); - } catch (readErr: any) { - const errcode = readErr?.name || 'Error'; - const unreadable = new MatrixError({ - error: `Upload failed: file unreadable before upload (${errcode}) (${file.size} bytes, ${ - file.type || 'unknown type' - })`, - errcode, - }); - (unreadable as any).info = { ...NO_INFO, unreadable: true }; - onError(unreadable); + const data = await uploadPromise; + const mxc = data.content_uri; + if (mxc) onSuccess(mxc); + else onError(new MatrixError(data)); return; - } - const probe = startAbortProbe(); - const trace: UploadTrace = { startedAt: Date.now(), previous, aborts: probe.calls }; - const abortController = new AbortController(); - try { - const uploadPromise = mx.uploadContent(body, { - name, - type: fileType, - includeFilename: !hideFilename, - abortController, - progressHandler: (progress) => { - if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now(); - trace.loaded = progress.loaded; - trace.total = progress.total; - onProgress?.(progress); - }, - }); - onPromise?.(uploadPromise); - try { + } catch (e: any) { + const elapsed = Date.now() - trace.startedAt; + trace.signalAborted = abortController.signal.aborted; + const retry = + attempt === 1 && + e?.name === 'AbortError' && + !abortController.signal.aborted && + trace.firstProgressAt === undefined && + elapsed < RETRY_WINDOW_MS; + if (!retry) { // eslint-disable-next-line no-await-in-loop - const data = await uploadPromise; - const mxc = data.content_uri; - if (mxc) onSuccess(mxc); - else onError(new MatrixError(data)); + onError(await uploadFailure(e, file, trace)); return; - } catch (e: any) { - const elapsed = Date.now() - trace.startedAt; - trace.xhr = probe.describeXhrs(); - trace.signalAborted = abortController.signal.aborted; - const retry = - attempt === 1 && - e?.name === 'AbortError' && - !abortController.signal.aborted && - trace.firstProgressAt === undefined && - elapsed < RETRY_WINDOW_MS; - if (!retry) { - trace.lifecycle = describeLifecycle?.(); - // eslint-disable-next-line no-await-in-loop - onError(await uploadFailure(e, file, trace)); - return; - } - previous = `AbortError after ${elapsed}ms, no progress, ${ - trace.aborts?.length - ? `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` - : 'abort calls: none' - }, ${trace.xhr}`; } - } finally { - probe.stop(); + previous = `AbortError after ${elapsed}ms, no progress`; } } }; diff --git a/src/app/utils/uploadAbortProbe.test.ts b/src/app/utils/uploadAbortProbe.test.ts deleted file mode 100644 index 557908ef..00000000 --- a/src/app/utils/uploadAbortProbe.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - describeComponentLifecycle, - formatAbortStack, - startAbortProbe, - uploadContent, - uploadFailure, -} from './matrix'; - -const chromeStack = [ - 'Error', - ' at wrapper (https://chat.example/assets/index-abc.js:1:100)', - ' at https://chat.example/assets/index-abc.js:1:200', - ' at Object.cb (https://chat.example/assets/vendor-def.js:7:8)', - ' at https://chat.example/assets/a.js:2:3', - ' at https://chat.example/assets/b.js:4:5', - ' at https://chat.example/assets/c.js:6:7', - ' at https://chat.example/assets/d.js:8:9', - ' at https://chat.example/assets/e.js:10:11', -].join('\n'); - -describe('formatAbortStack', () => { - it('keeps at most six frames as file:line:col, skipping the probe wrapper and the error line', () => { - const out = formatAbortStack(chromeStack); - const frames = out.split(' < '); - expect(frames).toHaveLength(6); - expect(frames[0]).toBe('index-abc.js:1:200'); - expect(out).not.toContain('https://'); - expect(out).not.toContain('wrapper'); - }); - - it('copes with an empty stack', () => { - expect(formatAbortStack('')).toBe('no stack'); - }); -}); - -describe('abort probe', () => { - const original = AbortController.prototype.abort; - - afterEach(() => { - vi.unstubAllGlobals(); - AbortController.prototype.abort = original; - }); - - it('records an AbortController.abort made while it runs, still aborts, and restores afterwards', () => { - const probe = startAbortProbe(); - expect(AbortController.prototype.abort).not.toBe(original); - const c = new AbortController(); - c.abort(); - expect(c.signal.aborted).toBe(true); - probe.stop(); - expect(AbortController.prototype.abort).toBe(original); - expect(probe.calls).toHaveLength(1); - expect(probe.calls[0].api).toBe('AbortController.abort'); - }); - - it('records XMLHttpRequest.prototype.abort and restores it', () => { - const xhrAbort = vi.fn(); - class FakeXhr { - // eslint-disable-next-line class-methods-use-this - abort() { - xhrAbort(); - } - } - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - new FakeXhr().abort(); - probe.stop(); - expect(xhrAbort).toHaveBeenCalledTimes(1); - expect(probe.calls.map((c) => c.api)).toContain('XHR.abort'); - expect(FakeXhr.prototype.abort.toString()).not.toContain('collectors'); - const after = new FakeXhr(); - after.abort(); - expect(xhrAbort).toHaveBeenCalledTimes(2); - }); - - it('records nothing after stop', () => { - const probe = startAbortProbe(); - probe.stop(); - new AbortController().abort(); - expect(probe.calls).toHaveLength(0); - }); - - it('keeps the wrapper until the last overlapping probe stops, then restores the original', () => { - const a = startAbortProbe(); - const b = startAbortProbe(); - a.stop(); - new AbortController().abort(); - expect(b.calls).toHaveLength(1); - expect(a.calls).toHaveLength(0); - b.stop(); - expect(AbortController.prototype.abort).toBe(original); - }); - - it('restores the original when the upload attempt throws', async () => { - const mx = { uploadContent: () => Promise.reject(new Error('boom')) } as any; - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }); - expect(AbortController.prototype.abort).toBe(original); - }); - - it('restores the original when uploadContent itself throws synchronously', async () => { - const mx = { - uploadContent: () => { - throw new Error('sync'); - }, - } as any; - await expect( - uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }) - ).rejects.toThrow('sync'); - expect(AbortController.prototype.abort).toBe(original); - }); -}); - -describe('failure text', () => { - const abort = () => new DOMException('', 'AbortError'); - - it('lists abort calls seen during the attempt', async () => { - const mx = { - uploadContent: () => { - new AbortController().abort(); - return Promise.reject(abort()); - }, - } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); - // retried once: the final message carries the second attempt and attempt 1's summary - const msg = onError.mock.calls[0][0].message; - expect(msg).toContain('abort calls: AbortController.abort'); - expect(msg).toContain('retried (attempt 1: AbortError'); - }); - - it('says none when nothing in the page called abort', async () => { - const err = await uploadFailure(abort(), new Blob(['x']), { - startedAt: Date.now(), - aborts: [], - }); - expect(err.message).toContain('abort calls: none'); - }); - - it('reports the component lifecycle when given', async () => { - const mx = { uploadContent: () => Promise.reject(new Error('Timeout')) } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { - onSuccess: vi.fn(), - onError, - describeLifecycle: () => 'component remounted 0x, renders 3 (2 within 300ms)', - }); - expect(onError.mock.calls[0][0].message).toContain('renders 3 (2 within 300ms)'); - }); -}); - -describe('describeComponentLifecycle', () => { - it('counts renders after attach and those within 300ms, and reports an unmount', () => { - const text = describeComponentLifecycle({ - attachedAt: 1000, - rendersAtAttach: 1, - renders: [990, 1100, 1250, 1400], - unmountedAt: 1500, - }); - expect(text).toBe('component: 3 renders since attach (2 within 300ms), unmounted +500ms'); - }); - - it('says not unmounted when it was not', () => { - const text = describeComponentLifecycle({ - attachedAt: 1000, - rendersAtAttach: 1, - renders: [990], - }); - expect(text).toBe('component: 0 renders since attach (0 within 300ms), not unmounted'); - }); -}); diff --git a/src/app/utils/uploadFailure.test.ts b/src/app/utils/uploadFailure.test.ts index ec1e8115..1dc4af05 100644 --- a/src/app/utils/uploadFailure.test.ts +++ b/src/app/utils/uploadFailure.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { noteUserActivity, uploadFailure } from './matrix'; +import { uploadFailure } from './matrix'; const abort = () => new DOMException('', 'AbortError'); @@ -31,7 +31,9 @@ describe('uploadFailure', () => { const ok = await uploadFailure(abort(), new Blob(['x'])); expect(ok.message).toContain('file readable'); const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + (bad as any).slice = () => ({ + arrayBuffer: () => Promise.reject(new DOMException('gone', 'NotReadableError')), + }); const err = await uploadFailure(abort(), bad); expect(err.message).toContain('file unreadable (NotReadableError)'); }); @@ -51,7 +53,7 @@ describe('uploadFailure client trace', () => { vi.unstubAllGlobals(); }); - it('reports connectivity, visibility and idle time at the moment of failure', async () => { + it('reports connectivity and visibility at the moment of failure', async () => { vi.useFakeTimers(); vi.setSystemTime(10_000); vi.stubGlobal('navigator', { @@ -59,13 +61,11 @@ describe('uploadFailure client trace', () => { connection: { effectiveType: '3g', rtt: 300, downlink: 1.5, saveData: true }, }); vi.stubGlobal('document', { visibilityState: 'hidden' }); - noteUserActivity(); vi.setSystemTime(13_000); const err = await uploadFailure(abort(), blob, { startedAt: 12_000 }); expect(err.message).toContain('offline'); expect(err.message).toContain('3g rtt 300ms down 1.5Mbps saveData on'); expect(err.message).toContain('tab hidden'); - expect(err.message).toContain('idle 3000ms'); expect(err.message).toContain('failed after 1000ms'); }); diff --git a/src/app/utils/uploadReason.test.ts b/src/app/utils/uploadReason.test.ts index d9e83d4d..765b8e41 100644 --- a/src/app/utils/uploadReason.test.ts +++ b/src/app/utils/uploadReason.test.ts @@ -44,9 +44,9 @@ describe('what the sender is told when an upload fails', () => { }); it('a file the browser can no longer read says to pick it again', async () => { - const gone = new Blob(['x']); - (gone as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - expect(await textOf(abort(), undefined, gone)).toContain('can no longer read the file'); + expect(await textOf(new DOMException('gone', 'NotReadableError'))).toContain( + 'can no longer read the file' + ); }); it('a stopped upload says stopped, not that the connection failed', async () => { @@ -79,13 +79,12 @@ describe('what the sender is told when an upload fails', () => { }); describe('through uploadContent, as the composer and the share panel call it', () => { - it('an unreadable picked file is named before any request', async () => { - const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - const mx = { uploadContent: vi.fn() } as any; + it('an unreadable picked file tells the sender to pick it again', async () => { + const mx = { + uploadContent: () => Promise.reject(new DOMException('gone', 'NotReadableError')), + } as any; const onError = vi.fn(); - await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); - expect(mx.uploadContent).not.toHaveBeenCalled(); + await uploadContent(mx, blob, { onSuccess: vi.fn(), onError }); expect(uploadFailureText(onError.mock.calls[0][0])).toContain('can no longer read the file'); }); diff --git a/src/app/utils/uploadXhrProbe.test.ts b/src/app/utils/uploadXhrProbe.test.ts deleted file mode 100644 index e72afa3d..00000000 --- a/src/app/utils/uploadXhrProbe.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -/* eslint-disable class-methods-use-this, @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars, no-unused-vars */ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { startAbortProbe, uploadContent } from './matrix'; - -class FakeXhr extends EventTarget { - upload = new EventTarget(); - - readyState = 0; - - status = 0; - - open(_method: string, _url: string) { - this.readyState = 1; - } - - send() { - this.readyState = 2; - } - - abort() {} -} - -const origOpen = FakeXhr.prototype.open; -const origSend = FakeXhr.prototype.send; -const uploadUrl = - 'https://matrix.example/_matrix/media/v3/upload?filename=a.jpg&access_token=SECRET'; - -describe('XHR probe', () => { - afterEach(() => { - vi.unstubAllGlobals(); - FakeXhr.prototype.open = origOpen; - FakeXhr.prototype.send = origSend; - }); - - it('records which events an upload XHR fired and how it ended, without the query string', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - x.upload.dispatchEvent(new Event('loadstart')); - x.upload.dispatchEvent(new Event('error')); - x.dispatchEvent(new Event('error')); - x.readyState = 4; - x.status = 0; - probe.stop(); - expect(probe.xhrs).toHaveLength(1); - const text = probe.describeXhrs(); - expect(text).toContain('POST /_matrix/media/v3/upload'); - expect(text).toContain('readyState 4 status 0'); - expect(text).toContain('upload.loadstart'); - expect(text).toContain('upload.error'); - expect(text).toContain('error'); - expect(text).not.toContain('SECRET'); - expect(text).not.toContain('access_token'); - }); - - it('ignores XHRs that are not uploads', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('GET', 'https://matrix.example/_matrix/client/v3/sync'); - x.send(); - probe.stop(); - expect(probe.xhrs).toHaveLength(0); - expect(probe.describeXhrs()).toBe('xhr: none seen'); - }); - - it('still calls the real open and send and restores both afterwards', () => { - const open = vi.fn(); - const send = vi.fn(); - FakeXhr.prototype.open = open; - FakeXhr.prototype.send = send; - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - expect(open).toHaveBeenCalledWith('POST', uploadUrl); - expect(send).toHaveBeenCalledTimes(1); - probe.stop(); - expect(FakeXhr.prototype.open).toBe(open); - expect(FakeXhr.prototype.send).toBe(send); - }); - - it('records nothing for requests made after stop', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - probe.stop(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - expect(probe.xhrs).toHaveLength(0); - }); -}); - -describe('uploadContent in-memory copy and failure line', () => { - const abort = () => new DOMException('', 'AbortError'); - - it('uploads an in-memory copy with the same bytes, name and type, not the original', async () => { - const file = new File(['abcdef'], 'a.jpg', { type: 'image/jpeg' }); - let sent: any; - const mx = { - uploadContent: vi.fn(async (f: any) => { - sent = f; - return { content_uri: 'mxc://a/b' }; - }), - } as any; - await uploadContent(mx, file, { onSuccess: vi.fn(), onError: vi.fn() }); - expect(sent).not.toBe(file); - expect(sent.type).toBe('image/jpeg'); - expect(sent.name).toBe('a.jpg'); - expect(await sent.text()).toBe('abcdef'); - }); - - it('copies again before the retry', async () => { - const seen: any[] = []; - const mx = { - uploadContent: vi.fn((f: any) => { - seen.push(f); - return seen.length === 1 - ? Promise.reject(abort()) - : Promise.resolve({ content_uri: 'mxc://a/b' }); - }), - } as any; - await uploadContent(mx, new Blob(['xy']), { onSuccess: vi.fn(), onError: vi.fn() }); - expect(seen).toHaveLength(2); - expect(seen[0]).not.toBe(seen[1]); - }); - - it('reports an unreadable file and never starts the upload', async () => { - const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - const mx = { uploadContent: vi.fn() } as any; - const onError = vi.fn(); - await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); - expect(mx.uploadContent).not.toHaveBeenCalled(); - expect(onError.mock.calls[0][0].message).toContain( - 'unreadable before upload (NotReadableError)' - ); - }); - - it('puts the XHR end state and signal.aborted in the failure line', async () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const mx = { - uploadContent: () => { - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - x.upload.dispatchEvent(new Event('error')); - x.readyState = 4; - return Promise.reject(new Error('Timeout')); - }, - } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); - const msg = onError.mock.calls[0][0].message; - expect(msg).toContain('readyState 4 status 0'); - expect(msg).toContain('upload.error'); - expect(msg).toContain('signal.aborted false'); - vi.unstubAllGlobals(); - }); -}); From 1e8c21c09920bdb24675fb390af398004ec6eb7a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:03:37 +0100 Subject: [PATCH 3/7] teardown(R2.3): hide DeskEntry without a desk source and drop unreachable deskMood branches --- src/app/features/desk/DeskEntry.tsx | 3 +- src/app/features/desk/DeskView.test.tsx | 12 ++--- src/app/features/desk/DeskView.tsx | 2 +- src/app/features/desk/deskMood.test.ts | 42 ++------------- src/app/features/desk/deskMood.ts | 68 ++++--------------------- 5 files changed, 23 insertions(+), 104 deletions(-) diff --git a/src/app/features/desk/DeskEntry.tsx b/src/app/features/desk/DeskEntry.tsx index 511b0783..518d7fee 100644 --- a/src/app/features/desk/DeskEntry.tsx +++ b/src/app/features/desk/DeskEntry.tsx @@ -37,10 +37,11 @@ export const openCount = ( unverified: ReadonlySet | undefined ): number => (unverified ? buildDesk(list, unverified).counts.open : 0); -/** A Mind's desk, pinned at the top of its navigator group: always there, with the open count when there is one. */ +/** A Mind's desk, pinned at the top of its navigator group when a desk source exists. */ export function DeskEntry({ mind }: { mind: string }) { const list = useMemo(() => deskFor(mind), [mind]); const unverified = useUnverified(list); + if (!list) return null; // The same count the desk page shows; until the hash check lands there is no count to show. return ; } diff --git a/src/app/features/desk/DeskView.test.tsx b/src/app/features/desk/DeskView.test.tsx index 9fde039b..79e4413a 100644 --- a/src/app/features/desk/DeskView.test.tsx +++ b/src/app/features/desk/DeskView.test.tsx @@ -291,12 +291,12 @@ describe('DeskEntry', () => { expect(bare(link(0))).toBe('Desk'); expect(link(0)).toContain('href="/desk/void"'); }); - it('is pinned when nothing is published, and when only settled forks exist', () => { - [undefined, { ...STATES.settled, open_count: 0 }].forEach((state) => { - setDeskSource(() => state); - expect(bare(entry('void'))).toBe('Desk'); - expect(entry('void')).toContain('href="/desk/void"'); - }); + it('is omitted when nothing is published, and pinned when settled forks exist', () => { + setDeskSource(() => undefined); + expect(entry('void')).toBe(''); + setDeskSource(() => ({ ...STATES.settled, open_count: 0 })); + expect(bare(entry('void'))).toBe('Desk'); + expect(entry('void')).toContain('href="/desk/void"'); }); it('shows no count before the hash check has landed, so a card about to be withdrawn is never counted', () => { setDeskSource(() => STATES.blocked); diff --git a/src/app/features/desk/DeskView.tsx b/src/app/features/desk/DeskView.tsx index 9cdda8fc..840456f3 100644 --- a/src/app/features/desk/DeskView.tsx +++ b/src/app/features/desk/DeskView.tsx @@ -151,7 +151,7 @@ export function DeskView({ mind, label, list, unverified, now = Date.now() }: De const desk = buildDesk(list, unverified); const skyInk = useSkyInk(); // Slice 1 has no session, so nothing on the desk is the viewer's answer yet. - const mood = deskMood(desk.counts.open, 0); + const mood = deskMood(desk.counts.open); return (
diff --git a/src/app/features/desk/deskMood.test.ts b/src/app/features/desk/deskMood.test.ts index 9c981640..8979f2ad 100644 --- a/src/app/features/desk/deskMood.test.ts +++ b/src/app/features/desk/deskMood.test.ts @@ -4,53 +4,19 @@ import { MOOD_POSE, deskMood } from './deskMood'; describe('deskMood', () => { it('is neutral with the desk clear when nothing is open', () => { - expect(deskMood(0, 0)).toEqual({ + expect(deskMood(0)).toEqual({ mood: 'neutral', pose: 'neutral', line: "Desk's clear. I'll wave when something lands.", }); }); - it('is triumph when every open fork is answered', () => { - expect(deskMood(3, 3).mood).toBe('triumph'); - expect(deskMood(1, 1).mood).toBe('triumph'); - }); - it('is thinking when none is answered, and says whether it is one fork or several', () => { - expect(deskMood(1, 0)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' }); - expect(deskMood(4, 0)).toMatchObject({ + it('is thinking when forks are open, and says whether it is one fork or several', () => { + expect(deskMood(1)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' }); + expect(deskMood(4)).toMatchObject({ mood: 'thinking', line: '4 forks on the desk. No rush.', }); }); - it('is determined partway, counting what is left', () => { - expect(deskMood(5, 2)).toMatchObject({ mood: 'determined', line: '3 to go.' }); - }); - it('is happy when the pick is the recommendation', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'B', recommended: 'B' }).mood).toBe('happy'); - }); - it('is surprised, and asks for a line on why, when the pick differs', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'A', recommended: 'B' })).toMatchObject({ - mood: 'surprised', - line: expect.stringContaining('A line in the note on why helps'), - }); - }); - it('is surprised, not happy, when there is no recommendation to match', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'A' }).mood).toBe('surprised'); - }); - it('is note when a pick is cleared, saying the note can carry the answer', () => { - expect(deskMood(2, 1, { type: 'cleared' })).toMatchObject({ - mood: 'note', - line: expect.stringContaining('note can carry the answer on its own'), - }); - }); - it('is concerned when a send failed, even with everything answered', () => { - expect(deskMood(2, 2, { type: 'sendFailed' }).mood).toBe('concerned'); - }); - it('is surprised when a new fork arrives, even on a clear desk', () => { - expect(deskMood(0, 0, { type: 'newFork' })).toMatchObject({ - mood: 'surprised', - line: 'New fork on the desk!', - }); - }); it('maps every mood to a label every Mind in the catalogue can show', () => { Object.values(MOOD_POSE).forEach((pose) => MINDS.forEach((mind) => expect(resolvePose(mind, pose)).toBe(pose)) diff --git a/src/app/features/desk/deskMood.ts b/src/app/features/desk/deskMood.ts index 75d9f23e..dc94d2c2 100644 --- a/src/app/features/desk/deskMood.ts +++ b/src/app/features/desk/deskMood.ts @@ -1,75 +1,27 @@ /** - * The booth Persona's reactions, from the original Fork Desk's mood() and choose() rules. A pure function of - * what is on the desk and the last thing that happened; it is the desk's character, so each rule is tested. + * The booth Persona's reactions while the desk is read-only. A pure function of what is open on + * the desk. */ -/** The original's nine moods. */ -export type Mood = - | 'idle' - | 'neutral' - | 'thinking' - | 'happy' - | 'surprised' - | 'note' - | 'determined' - | 'triumph' - | 'concerned'; - -/** What last happened; `none` means nothing since the page opened or the last event wore off. */ -export type DeskEvent = - | { type: 'none' } - | { type: 'picked'; choice: string; recommended?: string } - | { type: 'cleared' } - | { type: 'sendFailed' } - | { type: 'newFork' }; +export type Mood = 'neutral' | 'thinking'; /** - * Each mood on the shared cast-art labels (neutral, happy, amused, thinking, annoyed, surprised) that every - * Mind has, so the booth never asks a Mind for art it lacks. + * Each mood on the shared cast-art labels (neutral, thinking) that every Mind has, so the booth + * never asks a Mind for art it lacks. */ export const MOOD_POSE: Record = { - idle: 'neutral', neutral: 'neutral', thinking: 'thinking', - happy: 'happy', - surprised: 'surprised', - note: 'thinking', - determined: 'thinking', - triumph: 'happy', - concerned: 'surprised', }; export type DeskMood = { mood: Mood; pose: string; line: string }; const say = (mood: Mood, line: string): DeskMood => ({ mood, pose: MOOD_POSE[mood], line }); -export const deskMood = ( - open: number, - answered: number, - event: DeskEvent = { type: 'none' } -): DeskMood => { - switch (event.type) { - case 'sendFailed': - return say('concerned', "That one didn't save. Give it another try in a moment?"); - case 'newFork': - return say('surprised', 'New fork on the desk!'); - case 'cleared': - return say('note', 'Pick cleared. Your note can carry the answer on its own.'); - case 'picked': - return event.recommended !== undefined && event.choice === event.recommended - ? say('happy', "That's the one I'd have picked too.") - : say('surprised', 'Off-script. A line in the note on why helps the next brief.'); - default: - break; - } +export const deskMood = (open: number): DeskMood => { if (open === 0) return say('neutral', "Desk's clear. I'll wave when something lands."); - if (answered >= open) - return say('triumph', 'All answered! I will carry these back and admit them.'); - if (answered === 0) { - return say( - 'thinking', - open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.` - ); - } - return say('determined', `${open - answered} to go.`); + return say( + 'thinking', + open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.` + ); }; From b2e905864674fb8d8dbb4f7108b7ce5800e96be4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:03:51 +0100 Subject: [PATCH 4/7] teardown(R2.4): delete regex sentiment pose classifier and resolve org.gamecult.pose directly --- .../components/message/pose/sentiment.test.ts | 40 ------------------- src/app/components/message/pose/sentiment.ts | 35 ---------------- src/app/features/room/message/Message.tsx | 10 +++-- 3 files changed, 7 insertions(+), 78 deletions(-) delete mode 100644 src/app/components/message/pose/sentiment.test.ts delete mode 100644 src/app/components/message/pose/sentiment.ts diff --git a/src/app/components/message/pose/sentiment.test.ts b/src/app/components/message/pose/sentiment.test.ts deleted file mode 100644 index bc4a8c28..00000000 --- a/src/app/components/message/pose/sentiment.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { classifyPose, messagePose } from './sentiment'; - -describe('classifyPose', () => { - it.each([ - ['annoyed', 'ugh, this again'], - ['surprised', 'wow, no way'], - ['amused', 'hahaha that is funny'], - ['happy', 'thanks, great work'], - ['thinking', 'should we ship it?'], - ['neutral', 'Merged the branch.'], - ['neutral', 'sorry, that failed with an error'], - ])('%s', (label, text) => expect(classifyPose(text)).toBe(label)); - it('is neutral for empty or non-string text', () => { - expect(classifyPose('')).toBe('neutral'); - expect(classifyPose(undefined)).toBe('neutral'); - expect(classifyPose(5)).toBe('neutral'); - }); - it('is deterministic', () => { - expect(classifyPose('thanks?')).toBe(classifyPose('thanks?')); - }); -}); - -describe('messagePose', () => { - it('lets an explicit label win over the text', () => { - expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'annoyed' })).toBe( - 'annoyed' - ); - }); - it('keeps an unknown explicit label neutral instead of classifying', () => { - expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'conduct' })).toBe( - 'neutral' - ); - }); - it('classifies when there is no label, and never outputs a signature label', () => { - expect(messagePose('aqua', { body: 'thanks!' })).toBe('happy'); - expect(messagePose('kiko', { body: 'sorry' })).toBe('neutral'); - expect(messagePose('aqua', {})).toBe('neutral'); - }); -}); diff --git a/src/app/components/message/pose/sentiment.ts b/src/app/components/message/pose/sentiment.ts deleted file mode 100644 index bd685a07..00000000 --- a/src/app/components/message/pose/sentiment.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { POSE_KEY, NEUTRAL, resolvePose } from './poses'; - -// catalogue.json beside this file is a vendored copy of /opt/commons/cast-art/poses/catalogue.json -// (npm run sync:poses); nothing else publishes it to the browser. -// Local sentiment -> pose label. A lexicon over the message text, no network, no model: the -// same text always gives the same pose. Rules are tried in order and the first hit wins, so a -// message that says "wow" and "thanks" reads as surprised. Only the shared labels (identical art -// for all eight Minds, catalogue.json) are ever output; signature labels are explicit-only. -const RULES: [string, RegExp][] = [ - ['annoyed', /\b(annoy\w*|ugh+|argh+|frustrat\w*|again\?|why won'?t|stop it)\b/i], - ['surprised', /\b(wow|whoa|woah|omg|no way|unexpected\w*|surpris\w*|wait,? what)\b|[?!]{2,}/i], - [ - 'determined', - /\b(let'?s (go|do|fix|ship)|on it|i'?ll (fix|do|handle)|will do|fixing|resolved?)\b/i, - ], - ['amused', /\b(ha(ha)+|lol|lmao|rofl|funny|hilarious)\b|😂|🤣/i], - [ - 'happy', - /\b(thanks?|thank you|thx|great|awesome|nice|love|perfect|excellent|yay|congrats)\b|🎉|😊/i, - ], - ['thinking', /\?\s*$|\b(hmm+|maybe|perhaps|i wonder|not sure|how (do|does|about)|what if)\b/i], -]; - -export const classifyPose = (text: unknown): string => { - if (typeof text !== 'string') return NEUTRAL; - const hit = RULES.find(([, re]) => re.test(text)); - return hit ? hit[0] : NEUTRAL; -}; - -// An explicit org.gamecult.pose label always wins, even when it is unknown (then neutral). -// Only events with no label are read for sentiment. -export const messagePose = (mind: string, content: Record): string => - content[POSE_KEY] !== undefined - ? resolvePose(mind, content[POSE_KEY]) - : resolvePose(mind, classifyPose(content.body)); diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index d82ea8e9..2ed2ef93 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -61,8 +61,12 @@ import { import { MessageLayout, MessageSpacing, settingsAtom } from '../../../state/settings'; import { useSetting } from '../../../state/hooks/settings'; import { PoseAvatar } from '../../../components/message/pose/PoseAvatar'; -import { MINDS, mindOfSender } from '../../../components/message/pose/poses'; -import { messagePose } from '../../../components/message/pose/sentiment'; +import { + MINDS, + POSE_KEY, + mindOfSender, + resolvePose, +} from '../../../components/message/pose/poses'; import { useEntranceDelay } from '../../../components/message/pose/entrance'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useRecentEmoji } from '../../../hooks/useRecentEmoji'; @@ -844,7 +848,7 @@ export const Message = as<'div', MessageProps>( const poseJSX = !collapse && mind && ( Date: Thu, 3 Dec 2026 21:05:41 +0100 Subject: [PATCH 5/7] teardown(R2.5): resolve albums case-collision, fold micro-files, enable forceConsistentCasingInFileNames --- .../features/albums/ShareSet.folder.test.tsx | 6 +- src/app/features/albums/ShareSet.test.tsx | 2 +- src/app/features/albums/ShareSet.tsx | 12 +- src/app/features/albums/albumFolders.test.ts | 2 +- src/app/features/albums/buildAlbums.test.ts | 37 +- src/app/features/albums/buildAlbums.ts | 21 ++ src/app/features/albums/isFileZone.test.ts | 24 -- src/app/features/albums/isFileZone.ts | 14 - src/app/features/albums/mapLimit.test.ts | 29 -- src/app/features/albums/mapLimit.ts | 19 - src/app/features/albums/readPages.ts | 27 -- src/app/features/albums/shareController.ts | 135 ------- src/app/features/albums/shareSet.test.ts | 328 ----------------- ...Controller.test.ts => shareUpload.test.ts} | 333 +++++++++++++++++- .../albums/{shareSet.ts => shareUpload.ts} | 137 ++++++- .../{readPages.test.ts => useAlbums.test.ts} | 29 +- src/app/features/albums/useAlbums.ts | 53 ++- src/app/features/albums/zoneView.test.ts | 16 - src/app/features/albums/zoneView.ts | 5 - src/app/features/estate/MediaRow.tsx | 2 +- src/app/features/room/RoomView.tsx | 2 +- tsconfig.json | 1 + 22 files changed, 616 insertions(+), 618 deletions(-) delete mode 100644 src/app/features/albums/isFileZone.test.ts delete mode 100644 src/app/features/albums/isFileZone.ts delete mode 100644 src/app/features/albums/mapLimit.test.ts delete mode 100644 src/app/features/albums/mapLimit.ts delete mode 100644 src/app/features/albums/readPages.ts delete mode 100644 src/app/features/albums/shareController.ts delete mode 100644 src/app/features/albums/shareSet.test.ts rename src/app/features/albums/{shareController.test.ts => shareUpload.test.ts} (53%) rename src/app/features/albums/{shareSet.ts => shareUpload.ts} (52%) rename src/app/features/albums/{readPages.test.ts => useAlbums.test.ts} (69%) delete mode 100644 src/app/features/albums/zoneView.test.ts delete mode 100644 src/app/features/albums/zoneView.ts diff --git a/src/app/features/albums/ShareSet.folder.test.tsx b/src/app/features/albums/ShareSet.folder.test.tsx index abb8f2bb..35a9d091 100644 --- a/src/app/features/albums/ShareSet.folder.test.tsx +++ b/src/app/features/albums/ShareSet.folder.test.tsx @@ -14,7 +14,8 @@ const captured = vi.hoisted(() => ({ titles: [] as string[], })); -vi.mock('./shareController', () => ({ +vi.mock('./shareUpload', async (importOriginal) => ({ + ...(await importOriginal()), createShareController: (deps: { run: NonNullable; maxBytes: NonNullable; @@ -30,9 +31,6 @@ vi.mock('./shareController', () => ({ cancel: () => undefined, }; }, -})); -vi.mock('./shareSet', async (importOriginal) => ({ - ...(await importOriginal()), sendShareSet: async (_port: unknown, into: string | { albumId: string; lastId: string }) => { captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}@${into.lastId}`); return { albumId: '$a', sent: 0, failed: [], failedAt: [] }; diff --git a/src/app/features/albums/ShareSet.test.tsx b/src/app/features/albums/ShareSet.test.tsx index b3da7a3d..60c1fae7 100644 --- a/src/app/features/albums/ShareSet.test.tsx +++ b/src/app/features/albums/ShareSet.test.tsx @@ -3,7 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server'; import { describe, expect, it } from 'vitest'; import { ClientConfigProvider } from '../../hooks/useClientConfig'; import type { ClientConfig } from '../../hooks/useClientConfig'; -import { ShareState } from './shareController'; +import { ShareState } from './shareUpload'; import { ShareSetView, shareEnabled, useShareEnabled } from './ShareSet'; const text = (html: string) => diff --git a/src/app/features/albums/ShareSet.tsx b/src/app/features/albums/ShareSet.tsx index b7f26e7e..edc538e8 100644 --- a/src/app/features/albums/ShareSet.tsx +++ b/src/app/features/albums/ShareSet.tsx @@ -9,9 +9,17 @@ import { uploadContent } from '../../utils/matrix'; import { safeFile } from '../../utils/mimeTypes'; import { getMsgContent } from '../room/msgContent'; import { FILE_HASH_KEY, hashForSend } from './fileReceipt'; -import { ShareController, ShareState, createShareController } from './shareController'; import { titleIn } from './albumFolders'; -import { DEFAULT_TITLE, ExistingAlbum, freshest, sendShareSet, ThreadEvent } from './shareSet'; +import { + DEFAULT_TITLE, + ExistingAlbum, + ShareController, + ShareState, + ThreadEvent, + createShareController, + freshest, + sendShareSet, +} from './shareUpload'; import * as css from './AlbumView.css'; /** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */ diff --git a/src/app/features/albums/albumFolders.test.ts b/src/app/features/albums/albumFolders.test.ts index 9a9be53e..863fa4dd 100644 --- a/src/app/features/albums/albumFolders.test.ts +++ b/src/app/features/albums/albumFolders.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { buildAlbums } from './buildAlbums'; import type { Album, ZoneEvent } from './buildAlbums'; import { folderOf, listFolder, splitPath, titleIn } from './albumFolders'; -import { DEFAULT_TITLE, sendShareSet } from './shareSet'; +import { DEFAULT_TITLE, sendShareSet } from './shareUpload'; const album = (id: string, title: string, ts = 1): Album => ({ id, diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index e1e7964b..5eb031f6 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { AlbumInput, ZoneEvent, buildAlbums, lastEvent } from './buildAlbums'; +import { AlbumInput, ZoneEvent, buildAlbums, isFileZone, lastEvent, zoneView } from './buildAlbums'; const root = (id: string, ts: number, over: Partial = {}): ZoneEvent => ({ event_id: id, @@ -334,3 +334,38 @@ describe('Mind receipts', () => { expect(a.count).toBe(1); }); }); + +describe('zoneView', () => { + it('opens albums by default and the timeline for an event deep link', () => { + expect(zoneView(undefined, undefined)).toBe('albums'); + expect(zoneView(undefined, '$e')).toBe('timeline'); + }); + it('lets an event link win over an earlier choice of albums', () => { + expect(zoneView('albums', '$e')).toBe('timeline'); + }); + it('honours the choice when there is no event link', () => { + expect(zoneView('albums', undefined)).toBe('albums'); + expect(zoneView('timeline', undefined)).toBe('timeline'); + }); +}); + +describe('isFileZone', () => { + const room = { roomId: '!f:x', aliases: ['#files:x'] }; + it('is true for the file-zone create type', () => { + expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true); + }); + it('is false for other create types and for plain rooms', () => { + expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false); + expect(isFileZone(room, {})).toBe(false); + expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false); + }); + it('is true when the room id or an alias is configured', () => { + expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true); + expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true); + }); + it('is false when only another room is configured', () => { + expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false); + }); +}); diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index 5d3662e1..109c6456 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -179,6 +179,27 @@ export const looseNote = (files: AlbumFile[]): string => { /** Where the album view stands when it decides whether to show the loose-files note. */ export type ViewState = { open: boolean; encrypted: boolean; loading: boolean; error: boolean }; +export type ZoneView = 'albums' | 'timeline'; + +/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */ +export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView => + eventId ? 'timeline' : choice ?? 'albums'; + +export const FILE_ZONE_TYPE = 'org.gamecult.file_zone'; + +export type FileZoneRoom = { + roomId: string; + /** Canonical and alternative aliases. */ + aliases?: string[]; + /** The `type` of the room's m.room.create content. */ + createType?: string; +}; + +/** A room is the file zone when its create type says so or the client config lists it. */ +export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean => + room.createType === FILE_ZONE_TYPE || + !!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r)); + /** The note for the list view only: never inside an open album, an encrypted zone, or a load that is not finished. */ export const looseNoteFor = (files: AlbumFile[], view: ViewState): string => view.open || view.encrypted || view.loading || view.error ? '' : looseNote(files); diff --git a/src/app/features/albums/isFileZone.test.ts b/src/app/features/albums/isFileZone.test.ts deleted file mode 100644 index 0e55269f..00000000 --- a/src/app/features/albums/isFileZone.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { isFileZone } from './isFileZone'; - -const room = { roomId: '!f:x', aliases: ['#files:x'] }; - -describe('isFileZone', () => { - it('is true for the file-zone create type', () => { - expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true); - }); - it('is false for other create types and for plain rooms', () => { - expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false); - expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false); - expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false); - expect(isFileZone(room, {})).toBe(false); - expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false); - }); - it('is true when the room id or an alias is configured', () => { - expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true); - expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true); - }); - it('is false when only another room is configured', () => { - expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false); - }); -}); diff --git a/src/app/features/albums/isFileZone.ts b/src/app/features/albums/isFileZone.ts deleted file mode 100644 index 071ef17b..00000000 --- a/src/app/features/albums/isFileZone.ts +++ /dev/null @@ -1,14 +0,0 @@ -export const FILE_ZONE_TYPE = 'org.gamecult.file_zone'; - -export type FileZoneRoom = { - roomId: string; - /** Canonical and alternative aliases. */ - aliases?: string[]; - /** The `type` of the room's m.room.create content. */ - createType?: string; -}; - -/** A room is the file zone when its create type says so or the client config lists it. */ -export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean => - room.createType === FILE_ZONE_TYPE || - !!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r)); diff --git a/src/app/features/albums/mapLimit.test.ts b/src/app/features/albums/mapLimit.test.ts deleted file mode 100644 index 24898cb0..00000000 --- a/src/app/features/albums/mapLimit.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { mapLimit } from './mapLimit'; - -describe('mapLimit', () => { - it('keeps result order and never exceeds the limit', async () => { - let inFlight = 0; - let peak = 0; - const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => { - inFlight += 1; - peak = Math.max(peak, inFlight); - await new Promise((r) => { - setTimeout(r, n); - }); - inFlight -= 1; - return n * 10; - }); - expect(out).toEqual([50, 10, 40, 20, 30, 0]); - expect(peak).toBe(2); - }); - it('handles an empty list and rejects when a call rejects', async () => { - expect(await mapLimit([], 3, async (n) => n)).toEqual([]); - await expect( - mapLimit([1, 2], 2, async (n) => { - if (n === 2) throw new Error('boom'); - return n; - }) - ).rejects.toThrow('boom'); - }); -}); diff --git a/src/app/features/albums/mapLimit.ts b/src/app/features/albums/mapLimit.ts deleted file mode 100644 index e850add0..00000000 --- a/src/app/features/albums/mapLimit.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */ -export const mapLimit = async ( - items: T[], - limit: number, - fn: (item: T) => Promise -): Promise => { - const out = new Array(items.length); - let next = 0; - const worker = async () => { - while (next < items.length) { - const i = next; - next += 1; - // eslint-disable-next-line no-await-in-loop - out[i] = await fn(items[i]); - } - }; - await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); - return out; -}; diff --git a/src/app/features/albums/readPages.ts b/src/app/features/albums/readPages.ts deleted file mode 100644 index a2b888e5..00000000 --- a/src/app/features/albums/readPages.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */ -export type Page = { chunk?: T[]; next_batch?: string }; - -/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */ -export const MAX_PAGES = 20; - -/** - * Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true - * when the cap stopped the read with more still to come, so a caller can say the list is partial. - */ -export const readPages = async ( - fetchPage: (from: string | undefined) => Promise>, - maxPages = MAX_PAGES -): Promise<{ items: T[]; truncated: boolean }> => { - const items: T[] = []; - let from: string | undefined; - for (let n = 0; n < maxPages; n += 1) { - // eslint-disable-next-line no-await-in-loop - const page = await fetchPage(from); - items.push(...(page.chunk ?? [])); - // An empty page ends the read even if a token is returned: a server that keeps handing out - // tokens with nothing behind them would otherwise spend every page of the cap. - if (!page.next_batch || !page.chunk?.length) return { items, truncated: false }; - from = page.next_batch; - } - return { items, truncated: true }; -}; diff --git a/src/app/features/albums/shareController.ts b/src/app/features/albums/shareController.ts deleted file mode 100644 index 72f786c9..00000000 --- a/src/app/features/albums/shareController.ts +++ /dev/null @@ -1,135 +0,0 @@ -// The share panel's state machine, apart from React and Matrix: what is picked, what phase the -// send is in, and the rules that keep a room to one send at a time. ShareSet.tsx draws it. -import { ShareResult, remainingAfter, resultNote } from './shareSet'; - -export type Picked = { name: string; type: string; size?: number }; - -export type SharePhase = - | { kind: 'idle' } - | { kind: 'sending'; done: number } - | { kind: 'done'; text: string }; - -export type ShareState = { - files: F[]; - title: string; - phase: SharePhase; - /** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */ - epoch: number; -}; - -export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.'; - -const MIB = 1024 * 1024; - -/** - * Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a - * limit, so a file of exactly that size goes), split from the rest before anything is sent. A - * missing cap or size refuses nothing. - */ -export const splitBySize = (files: F[], cap: number | undefined) => { - const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap; - return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) }; -}; - -const tooLargeNote = (names: string[], cap: number): string => - `Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`; - -export type ShareDeps = { - roomId: string; - isEncrypted: () => boolean; - /** Sends the files as one album; reports each settled file through onFile. */ - run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise; - /** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */ - maxBytes?: () => number | undefined; - /** Called after a send that reached the room, whatever it left unsent. */ - onSent?: () => void; -}; - -/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */ -const sending = new Set(); - -export const createShareController = (deps: ShareDeps) => { - let state: ShareState = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }; - const listeners = new Set<() => void>(); - let running: AbortController | undefined; - const set = (patch: Partial>) => { - state = { ...state, ...patch }; - listeners.forEach((l) => l()); - }; - - const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 }); - - const send = async () => { - if (sending.has(deps.roomId) || state.files.length === 0) return; - if (deps.isEncrypted()) { - set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } }); - return; - } - // Files over the cap are named and dropped from the pick before any upload or album root: a - // retry cannot help them, and a root with nothing under it is a lone message nobody lists. - const cap = deps.maxBytes?.(); - const { sendable, tooLarge } = splitBySize(state.files, cap); - const sizeNote = tooLarge.length - ? tooLargeNote( - tooLarge.map((f) => f.name), - cap as number - ) - : ''; - if (sendable.length === 0) { - const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` }; - set({ files: [], title: '', epoch: state.epoch + 1, phase }); - return; - } - sending.add(deps.roomId); - const abort = new AbortController(); - running = abort; - const { title } = state; - const files = sendable; - set({ files, phase: { kind: 'sending', done: 0 } }); - let settled = 0; - try { - const res = await deps.run( - files, - title, - () => { - settled += 1; - set({ phase: { kind: 'sending', done: settled } }); - }, - abort.signal - ); - deps.onSent?.(); - const left = remainingAfter(files, res); - const phase: SharePhase = { - kind: 'done', - text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res), - }; - // One notification: no state is ever drawn with the pick emptied and the send still running. - if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase }); - else set({ files: left, phase }); - } catch (e: any) { - const failure = `Could not share: ${e?.message ?? 'send failed'}`; - set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } }); - } finally { - running = undefined; - sending.delete(deps.roomId); - } - }; - - return { - getState: () => state, - subscribe: (l: () => void) => { - listeners.add(l); - return () => { - listeners.delete(l); - }; - }, - pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }), - setTitle: (title: string) => set({ title }), - cancel: clear, - /** Stops a send in flight: the running upload is aborted and the rest are left picked. */ - stop: () => running?.abort(), - send, - }; -}; - -export type ShareController = ReturnType>; diff --git a/src/app/features/albums/shareSet.test.ts b/src/app/features/albums/shareSet.test.ts deleted file mode 100644 index 8fc4a8b8..00000000 --- a/src/app/features/albums/shareSet.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import config from '../../../../config.json'; -import { ZoneEvent, buildAlbums } from './buildAlbums'; -import { - DEFAULT_TITLE, - ShareFile, - SharePort, - CANCELLED, - freshest, - refusalOf, - remainingAfter, - resultNote, - sendShareSet, - threadRelation, -} from './shareSet'; - -const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file'); - -/** A fake room: records what is sent, as the events Synapse would return from /relations. */ -const room = (failOn: string[] = []) => { - const events: ZoneEvent[] = []; - const port: SharePort = { - send: async (content) => { - const id = `$e${events.length + 1}`; - events.push({ - event_id: id, - type: 'm.room.message', - sender: '@aqua:chat.gamecult.org', - origin_server_ts: 1000 + events.length, - content, - }); - return id; - }, - contentOf: async (f) => { - if (failOn.includes(f.name)) throw new Error('upload failed'); - return { - msgtype: kindOf(f), - body: f.name, - filename: f.name, - url: `mxc://x/${f.name}`, - info: { mimetype: f.mimeType }, - }; - }, - }; - const album = () => { - const [root, ...replies] = events; - return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0]; - }; - return { events, port, album }; -}; - -const clips: ShareFile[] = [ - { name: 'a.ogg', mimeType: 'audio/ogg' }, - { name: 'b.ogg', mimeType: 'audio/ogg' }, - { name: 'c.txt', mimeType: 'text/plain' }, -]; - -describe('sendShareSet', () => { - it('reads back as one album of the files in pick order', async () => { - const r = room(); - const res = await sendShareSet(r.port, 'Take 4', clips); - expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] }); - const album = r.album(); - expect(album.title).toBe('Take 4'); - expect(album.files.map((f) => [f.name, f.kind])).toEqual([ - ['a.ogg', 'audio'], - ['b.ogg', 'audio'], - ['c.txt', 'file'], - ]); - }); - - it('threads every file under the root, each falling back to the previous event', async () => { - const r = room(); - await sendShareSet(r.port, 't', clips); - const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']); - expect(rels).toEqual([ - threadRelation('$e1', '$e1'), - threadRelation('$e1', '$e2'), - threadRelation('$e1', '$e3'), - ]); - expect(r.events[0].content?.['m.relates_to']).toBeUndefined(); - }); - - it('titles an untitled share', async () => { - const r = room(); - await sendShareSet(r.port, ' ', clips.slice(0, 1)); - expect(r.album().title).toBe(DEFAULT_TITLE); - }); - - it('names a failed file and still sends the rest', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet(r.port, 't', clips); - expect(res.failed).toEqual(['b.ogg']); - expect(res.sent).toBe(2); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']); - // the next file falls back to the last event that exists, not to the failed one - expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2')); - }); - - it('throws when the root cannot be sent, uploading nothing', async () => { - let uploads = 0; - const port: SharePort = { - send: async () => { - throw new Error('M_FORBIDDEN'); - }, - contentOf: async () => { - uploads += 1; - return {}; - }, - }; - await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN'); - expect(uploads).toBe(0); - }); -}); - -describe('the share flag', () => { - it('ships off', () => { - expect(config.fileZoneShare).toEqual({ enabled: false }); - }); -}); - -describe('after a send', () => { - it('keeps the failed one of two same-named files, not both', async () => { - const twins: ShareFile[] = [ - { name: 'a.ogg', mimeType: 'audio/ogg' }, - { name: 'a.ogg', mimeType: 'audio/ogg' }, - ]; - let n = 0; - const r = room(); - const port: SharePort = { - ...r.port, - contentOf: async (f) => { - n += 1; - if (n === 2) throw new Error('second upload failed'); - return r.port.contentOf(f); - }, - }; - const res = await sendShareSet(port, 't', twins); - expect(res.failedAt).toEqual([1]); - expect(remainingAfter(twins, res)).toEqual([twins[1]]); - }); - - it('keeps only the failed files picked, so a retry is one tap', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']); - expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg'); - }); - - it('keeps everything and says nothing was shared when every upload failed', async () => { - const r = room(clips.map((c) => c.name)); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res)).toEqual(clips); - expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt'); - }); - - it('clears the pick on full success', async () => { - const r = room(); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res)).toEqual([]); - expect(resultNote(res)).toBe('Shared 3 files.'); - }); -}); - -describe('adding to an existing album', () => { - it('sends no root; each file threads under the album, the first after `lastId`', async () => { - const r = room(); - const sent: Record[] = []; - const port = { - ...r.port, - send: async (c: Record) => { - sent.push(c); - return `$n${sent.length}`; - }, - }; - const res = await sendShareSet( - port, - { albumId: '$root', lastId: '$last', lastTs: 1 }, - clips.slice(0, 2) - ); - expect(res.albumId).toBe('$root'); - expect(res.sent).toBe(2); - expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']); - expect(sent.map((c) => c['m.relates_to'])).toEqual([ - threadRelation('$root', '$last'), - threadRelation('$root', '$n1'), - ]); - }); -}); - -describe('refusals', () => { - const refuse = (errcode: string): SharePort => ({ - send: async () => '$e', - contentOf: async () => { - throw Object.assign(new Error('raw server text'), { errcode }); - }, - }); - - it('names the three upload refusals and nothing else', () => { - expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server'); - expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here'); - expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe( - 'uploading too fast, try again shortly' - ); - expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined(); - expect(refusalOf({ errcode: 'constructor' })).toBeUndefined(); - expect(refusalOf(new Error('x'))).toBeUndefined(); - expect(refusalOf(null)).toBeUndefined(); - }); - - it('the note carries the reason beside each refused file', async () => { - const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2)); - expect(resultNote(res)).toBe( - 'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)' - ); - }); - - it('a failure the client saw, not the server, is named too', async () => { - const dropped: SharePort = { - send: async () => '$e', - contentOf: async () => { - throw Object.assign(new Error('x'), { - errcode: 'AbortError', - info: { aborted: true, progressed: true }, - }); - }, - }; - const res = await sendShareSet(dropped, 't', clips.slice(0, 1)); - expect(resultNote(res)).toBe( - 'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)' - ); - }); - - it('an unnamed failure lists the bare name', async () => { - const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); - expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); - }); -}); - -describe('stopping a send', () => { - /** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */ - const stopping = (stopAt: string, abortAfterUpload = false) => { - const ac = new AbortController(); - const r = room(); - const port: SharePort = { - ...r.port, - signal: ac.signal, - contentOf: async (f) => { - if (f.name !== stopAt) return r.port.contentOf(f); - ac.abort(); - if (abortAfterUpload) return r.port.contentOf(f); - throw Object.assign(new Error('aborted'), { name: 'AbortError' }); - }, - }; - return { port, r }; - }; - - it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => { - const { port, r } = stopping('b.ogg'); - const res = await sendShareSet(port, 't', clips); - expect(res.sent).toBe(1); - expect(res.failed).toEqual(['b.ogg', 'c.txt']); - expect(res.failedAt).toEqual([1, 2]); - expect(res.reasons).toEqual([CANCELLED, CANCELLED]); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); - expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']); - expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)'); - }); - - it('a file whose upload finished after the stop is not sent', async () => { - const { port, r } = stopping('b.ogg', true); - const res = await sendShareSet(port, 't', clips); - expect(res.sent).toBe(1); - expect(res.failedAt).toEqual([1, 2]); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); - }); - - it('a signal already aborted starts nothing and sends everything back as unsent', async () => { - const r = room(); - const ac = new AbortController(); - ac.abort(); - let uploads = 0; - const res = await sendShareSet( - { - ...r.port, - signal: ac.signal, - contentOf: async (f) => { - uploads += 1; - return r.port.contentOf(f); - }, - }, - { albumId: '$a', lastId: '$l', lastTs: 1 }, - clips - ); - expect(uploads).toBe(0); - expect(res.sent).toBe(0); - expect(res.failedAt).toEqual([0, 1, 2]); - expect(r.events).toEqual([]); - }); - - it('an abort that is not a stop is an ordinary failure', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips); - expect(res.failedAt).toEqual([1]); - expect(res.reasons).toEqual([undefined]); - }); -}); - -describe('freshest', () => { - const album = { albumId: '$alb', lastId: '$old', lastTs: 100 }; - it('moves lastId to a newer event of the same thread', () => { - expect( - freshest(album, [ - { id: '$mid', ts: 150, threadRoot: '$alb' }, - { id: '$new', ts: 200, threadRoot: '$alb' }, - ]) - ).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 }); - }); - it('ignores older events and events of other threads or none', () => { - expect( - freshest(album, [ - { id: '$older', ts: 50, threadRoot: '$alb' }, - { id: '$other', ts: 900, threadRoot: '$else' }, - { id: '$loose', ts: 900 }, - ]) - ).toEqual(album); - }); -}); diff --git a/src/app/features/albums/shareController.test.ts b/src/app/features/albums/shareUpload.test.ts similarity index 53% rename from src/app/features/albums/shareController.test.ts rename to src/app/features/albums/shareUpload.test.ts index b163b736..a6107366 100644 --- a/src/app/features/albums/shareController.test.ts +++ b/src/app/features/albums/shareUpload.test.ts @@ -1,6 +1,335 @@ import { describe, expect, it } from 'vitest'; -import { Picked, ShareDeps, createShareController } from './shareController'; -import { ShareResult } from './shareSet'; +import config from '../../../../config.json'; +import { ZoneEvent, buildAlbums } from './buildAlbums'; +import { + DEFAULT_TITLE, + ShareFile, + SharePort, + CANCELLED, + freshest, + refusalOf, + remainingAfter, + resultNote, + sendShareSet, + Picked, + ShareDeps, + ShareResult, + createShareController, + threadRelation, +} from './shareUpload'; + +const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file'); + +/** A fake room: records what is sent, as the events Synapse would return from /relations. */ +const room = (failOn: string[] = []) => { + const events: ZoneEvent[] = []; + const port: SharePort = { + send: async (content) => { + const id = `$e${events.length + 1}`; + events.push({ + event_id: id, + type: 'm.room.message', + sender: '@aqua:chat.gamecult.org', + origin_server_ts: 1000 + events.length, + content, + }); + return id; + }, + contentOf: async (f) => { + if (failOn.includes(f.name)) throw new Error('upload failed'); + return { + msgtype: kindOf(f), + body: f.name, + filename: f.name, + url: `mxc://x/${f.name}`, + info: { mimetype: f.mimeType }, + }; + }, + }; + const album = () => { + const [root, ...replies] = events; + return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0]; + }; + return { events, port, album }; +}; + +const clips: ShareFile[] = [ + { name: 'a.ogg', mimeType: 'audio/ogg' }, + { name: 'b.ogg', mimeType: 'audio/ogg' }, + { name: 'c.txt', mimeType: 'text/plain' }, +]; + +describe('sendShareSet', () => { + it('reads back as one album of the files in pick order', async () => { + const r = room(); + const res = await sendShareSet(r.port, 'Take 4', clips); + expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] }); + const album = r.album(); + expect(album.title).toBe('Take 4'); + expect(album.files.map((f) => [f.name, f.kind])).toEqual([ + ['a.ogg', 'audio'], + ['b.ogg', 'audio'], + ['c.txt', 'file'], + ]); + }); + + it('threads every file under the root, each falling back to the previous event', async () => { + const r = room(); + await sendShareSet(r.port, 't', clips); + const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']); + expect(rels).toEqual([ + threadRelation('$e1', '$e1'), + threadRelation('$e1', '$e2'), + threadRelation('$e1', '$e3'), + ]); + expect(r.events[0].content?.['m.relates_to']).toBeUndefined(); + }); + + it('titles an untitled share', async () => { + const r = room(); + await sendShareSet(r.port, ' ', clips.slice(0, 1)); + expect(r.album().title).toBe(DEFAULT_TITLE); + }); + + it('names a failed file and still sends the rest', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet(r.port, 't', clips); + expect(res.failed).toEqual(['b.ogg']); + expect(res.sent).toBe(2); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']); + // the next file falls back to the last event that exists, not to the failed one + expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2')); + }); + + it('throws when the root cannot be sent, uploading nothing', async () => { + let uploads = 0; + const port: SharePort = { + send: async () => { + throw new Error('M_FORBIDDEN'); + }, + contentOf: async () => { + uploads += 1; + return {}; + }, + }; + await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN'); + expect(uploads).toBe(0); + }); +}); + +describe('the share flag', () => { + it('ships off', () => { + expect(config.fileZoneShare).toEqual({ enabled: false }); + }); +}); + +describe('after a send', () => { + it('keeps the failed one of two same-named files, not both', async () => { + const twins: ShareFile[] = [ + { name: 'a.ogg', mimeType: 'audio/ogg' }, + { name: 'a.ogg', mimeType: 'audio/ogg' }, + ]; + let n = 0; + const r = room(); + const port: SharePort = { + ...r.port, + contentOf: async (f) => { + n += 1; + if (n === 2) throw new Error('second upload failed'); + return r.port.contentOf(f); + }, + }; + const res = await sendShareSet(port, 't', twins); + expect(res.failedAt).toEqual([1]); + expect(remainingAfter(twins, res)).toEqual([twins[1]]); + }); + + it('keeps only the failed files picked, so a retry is one tap', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']); + expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg'); + }); + + it('keeps everything and says nothing was shared when every upload failed', async () => { + const r = room(clips.map((c) => c.name)); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res)).toEqual(clips); + expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt'); + }); + + it('clears the pick on full success', async () => { + const r = room(); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res)).toEqual([]); + expect(resultNote(res)).toBe('Shared 3 files.'); + }); +}); + +describe('adding to an existing album', () => { + it('sends no root; each file threads under the album, the first after `lastId`', async () => { + const r = room(); + const sent: Record[] = []; + const port = { + ...r.port, + send: async (c: Record) => { + sent.push(c); + return `$n${sent.length}`; + }, + }; + const res = await sendShareSet( + port, + { albumId: '$root', lastId: '$last', lastTs: 1 }, + clips.slice(0, 2) + ); + expect(res.albumId).toBe('$root'); + expect(res.sent).toBe(2); + expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']); + expect(sent.map((c) => c['m.relates_to'])).toEqual([ + threadRelation('$root', '$last'), + threadRelation('$root', '$n1'), + ]); + }); +}); + +describe('refusals', () => { + const refuse = (errcode: string): SharePort => ({ + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('raw server text'), { errcode }); + }, + }); + + it('names the three upload refusals and nothing else', () => { + expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server'); + expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here'); + expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe( + 'uploading too fast, try again shortly' + ); + expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined(); + expect(refusalOf({ errcode: 'constructor' })).toBeUndefined(); + expect(refusalOf(new Error('x'))).toBeUndefined(); + expect(refusalOf(null)).toBeUndefined(); + }); + + it('the note carries the reason beside each refused file', async () => { + const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)' + ); + }); + + it('a failure the client saw, not the server, is named too', async () => { + const dropped: SharePort = { + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('x'), { + errcode: 'AbortError', + info: { aborted: true, progressed: true }, + }); + }, + }; + const res = await sendShareSet(dropped, 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)' + ); + }); + + it('an unnamed failure lists the bare name', async () => { + const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); + }); +}); + +describe('stopping a send', () => { + /** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */ + const stopping = (stopAt: string, abortAfterUpload = false) => { + const ac = new AbortController(); + const r = room(); + const port: SharePort = { + ...r.port, + signal: ac.signal, + contentOf: async (f) => { + if (f.name !== stopAt) return r.port.contentOf(f); + ac.abort(); + if (abortAfterUpload) return r.port.contentOf(f); + throw Object.assign(new Error('aborted'), { name: 'AbortError' }); + }, + }; + return { port, r }; + }; + + it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => { + const { port, r } = stopping('b.ogg'); + const res = await sendShareSet(port, 't', clips); + expect(res.sent).toBe(1); + expect(res.failed).toEqual(['b.ogg', 'c.txt']); + expect(res.failedAt).toEqual([1, 2]); + expect(res.reasons).toEqual([CANCELLED, CANCELLED]); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); + expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']); + expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)'); + }); + + it('a file whose upload finished after the stop is not sent', async () => { + const { port, r } = stopping('b.ogg', true); + const res = await sendShareSet(port, 't', clips); + expect(res.sent).toBe(1); + expect(res.failedAt).toEqual([1, 2]); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); + }); + + it('a signal already aborted starts nothing and sends everything back as unsent', async () => { + const r = room(); + const ac = new AbortController(); + ac.abort(); + let uploads = 0; + const res = await sendShareSet( + { + ...r.port, + signal: ac.signal, + contentOf: async (f) => { + uploads += 1; + return r.port.contentOf(f); + }, + }, + { albumId: '$a', lastId: '$l', lastTs: 1 }, + clips + ); + expect(uploads).toBe(0); + expect(res.sent).toBe(0); + expect(res.failedAt).toEqual([0, 1, 2]); + expect(r.events).toEqual([]); + }); + + it('an abort that is not a stop is an ordinary failure', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips); + expect(res.failedAt).toEqual([1]); + expect(res.reasons).toEqual([undefined]); + }); +}); + +describe('freshest', () => { + const album = { albumId: '$alb', lastId: '$old', lastTs: 100 }; + it('moves lastId to a newer event of the same thread', () => { + expect( + freshest(album, [ + { id: '$mid', ts: 150, threadRoot: '$alb' }, + { id: '$new', ts: 200, threadRoot: '$alb' }, + ]) + ).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 }); + }); + it('ignores older events and events of other threads or none', () => { + expect( + freshest(album, [ + { id: '$older', ts: 50, threadRoot: '$alb' }, + { id: '$other', ts: 900, threadRoot: '$else' }, + { id: '$loose', ts: 900 }, + ]) + ).toEqual(album); + }); +}); const file = (name: string, size?: number): Picked => ({ name, type: 'audio/ogg', size }); const MB = 1024 * 1024; diff --git a/src/app/features/albums/shareSet.ts b/src/app/features/albums/shareUpload.ts similarity index 52% rename from src/app/features/albums/shareSet.ts rename to src/app/features/albums/shareUpload.ts index 007d7e91..178f6653 100644 --- a/src/app/features/albums/shareSet.ts +++ b/src/app/features/albums/shareUpload.ts @@ -1,6 +1,5 @@ -// Share a set of files at once: one album root (a text message) and one thread reply per file. -// That is exactly the shape buildAlbums reads, so a set shared here and a set a Mind's mouth posts -// are the same thing to every viewer. Ports are injected so the order and the failure rules are +// Share a set of files at once: one album root (a text message) and one thread reply per file, +// plus the share panel's state machine. Ports are injected so order and failure rules are // testable without a homeserver. See docs/file-zone.md, "Share a set". import { uploadReason } from '../../utils/uploadReason'; @@ -136,3 +135,135 @@ export const resultNote = (result: ShareResult): string => { if (result.sent === 0) return `Nothing was shared. Not sent: ${failedList(result)}`; return `Shared ${result.sent}. Not sent: ${failedList(result)}`; }; + +export type Picked = { name: string; type: string; size?: number }; + +export type SharePhase = + | { kind: 'idle' } + | { kind: 'sending'; done: number } + | { kind: 'done'; text: string }; + +export type ShareState = { + files: F[]; + title: string; + phase: SharePhase; + /** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */ + epoch: number; +}; + +export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.'; + +const MIB = 1024 * 1024; + +/** + * Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a + * limit, so a file of exactly that size goes), split from the rest before anything is sent. A + * missing cap or size refuses nothing. + */ +export const splitBySize = (files: F[], cap: number | undefined) => { + const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap; + return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) }; +}; + +const tooLargeNote = (names: string[], cap: number): string => + `Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`; + +export type ShareDeps = { + roomId: string; + isEncrypted: () => boolean; + /** Sends the files as one album; reports each settled file through onFile. */ + run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise; + /** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */ + maxBytes?: () => number | undefined; + /** Called after a send that reached the room, whatever it left unsent. */ + onSent?: () => void; +}; + +/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */ +const sending = new Set(); + +export const createShareController = (deps: ShareDeps) => { + let state: ShareState = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }; + const listeners = new Set<() => void>(); + let running: AbortController | undefined; + const set = (patch: Partial>) => { + state = { ...state, ...patch }; + listeners.forEach((l) => l()); + }; + + const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 }); + + const send = async () => { + if (sending.has(deps.roomId) || state.files.length === 0) return; + if (deps.isEncrypted()) { + set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } }); + return; + } + // Files over the cap are named and dropped from the pick before any upload or album root: a + // retry cannot help them, and a root with nothing under it is a lone message nobody lists. + const cap = deps.maxBytes?.(); + const { sendable, tooLarge } = splitBySize(state.files, cap); + const sizeNote = tooLarge.length + ? tooLargeNote( + tooLarge.map((f) => f.name), + cap as number + ) + : ''; + if (sendable.length === 0) { + const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` }; + set({ files: [], title: '', epoch: state.epoch + 1, phase }); + return; + } + sending.add(deps.roomId); + const abort = new AbortController(); + running = abort; + const { title } = state; + const files = sendable; + set({ files, phase: { kind: 'sending', done: 0 } }); + let settled = 0; + try { + const res = await deps.run( + files, + title, + () => { + settled += 1; + set({ phase: { kind: 'sending', done: settled } }); + }, + abort.signal + ); + deps.onSent?.(); + const left = remainingAfter(files, res); + const phase: SharePhase = { + kind: 'done', + text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res), + }; + // One notification: no state is ever drawn with the pick emptied and the send still running. + if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase }); + else set({ files: left, phase }); + } catch (e: any) { + const failure = `Could not share: ${e?.message ?? 'send failed'}`; + set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } }); + } finally { + running = undefined; + sending.delete(deps.roomId); + } + }; + + return { + getState: () => state, + subscribe: (l: () => void) => { + listeners.add(l); + return () => { + listeners.delete(l); + }; + }, + pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }), + setTitle: (title: string) => set({ title }), + cancel: clear, + /** Stops a send in flight: the running upload is aborted and the rest are left picked. */ + stop: () => running?.abort(), + send, + }; +}; + +export type ShareController = ReturnType>; diff --git a/src/app/features/albums/readPages.test.ts b/src/app/features/albums/useAlbums.test.ts similarity index 69% rename from src/app/features/albums/readPages.test.ts rename to src/app/features/albums/useAlbums.test.ts index 124a32a6..49f6d7e4 100644 --- a/src/app/features/albums/readPages.test.ts +++ b/src/app/features/albums/useAlbums.test.ts @@ -1,5 +1,32 @@ import { describe, expect, it } from 'vitest'; -import { Page, readPages } from './readPages'; +import { Page, mapLimit, readPages } from './useAlbums'; + +describe('mapLimit', () => { + it('keeps result order and never exceeds the limit', async () => { + let inFlight = 0; + let peak = 0; + const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((r) => { + setTimeout(r, n); + }); + inFlight -= 1; + return n * 10; + }); + expect(out).toEqual([50, 10, 40, 20, 30, 0]); + expect(peak).toBe(2); + }); + it('handles an empty list and rejects when a call rejects', async () => { + expect(await mapLimit([], 3, async (n) => n)).toEqual([]); + await expect( + mapLimit([1, 2], 2, async (n) => { + if (n === 2) throw new Error('boom'); + return n; + }) + ).rejects.toThrow('boom'); + }); +}); const pager = (pages: Page[]) => { const froms: (string | undefined)[] = []; diff --git a/src/app/features/albums/useAlbums.ts b/src/app/features/albums/useAlbums.ts index 13c199ec..52e5d19c 100644 --- a/src/app/features/albums/useAlbums.ts +++ b/src/app/features/albums/useAlbums.ts @@ -4,14 +4,59 @@ import { StateEvent } from '../../../types/matrix/room'; import { useStateEvent } from '../../hooks/useStateEvent'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useClientConfig } from '../../hooks/useClientConfig'; -import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; -import { isFileZone } from './isFileZone'; -import { mapLimit } from './mapLimit'; -import { Page, readPages } from './readPages'; +import { Album, ZoneEvent, buildAlbums, isFileZone } from './buildAlbums'; const REPLY_FETCHES_IN_FLIGHT = 6; const REFRESH_MS = 30_000; +/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */ +export type Page = { chunk?: T[]; next_batch?: string }; + +/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */ +export const MAX_PAGES = 20; + +/** + * Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true + * when the cap stopped the read with more still to come, so a caller can say the list is partial. + */ +export const readPages = async ( + fetchPage: (from: string | undefined) => Promise>, + maxPages = MAX_PAGES +): Promise<{ items: T[]; truncated: boolean }> => { + const items: T[] = []; + let from: string | undefined; + for (let n = 0; n < maxPages; n += 1) { + // eslint-disable-next-line no-await-in-loop + const page = await fetchPage(from); + items.push(...(page.chunk ?? [])); + // An empty page ends the read even if a token is returned: a server that keeps handing out + // tokens with nothing behind them would otherwise spend every page of the cap. + if (!page.next_batch || !page.chunk?.length) return { items, truncated: false }; + from = page.next_batch; + } + return { items, truncated: true }; +}; + +/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */ +export const mapLimit = async ( + items: T[], + limit: number, + fn: (item: T) => Promise +): Promise => { + const out = new Array(items.length); + let next = 0; + const worker = async () => { + while (next < items.length) { + const i = next; + next += 1; + // eslint-disable-next-line no-await-in-loop + out[i] = await fn(items[i]); + } + }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return out; +}; + /** True when the room is the file zone: by its create type, or listed in the client config. */ export const useIsFileZone = (room: Room): boolean => { const config = useClientConfig(); diff --git a/src/app/features/albums/zoneView.test.ts b/src/app/features/albums/zoneView.test.ts deleted file mode 100644 index 65beb9cb..00000000 --- a/src/app/features/albums/zoneView.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { zoneView } from './zoneView'; - -describe('zoneView', () => { - it('opens albums by default and the timeline for an event deep link', () => { - expect(zoneView(undefined, undefined)).toBe('albums'); - expect(zoneView(undefined, '$e')).toBe('timeline'); - }); - it('lets an event link win over an earlier choice of albums', () => { - expect(zoneView('albums', '$e')).toBe('timeline'); - }); - it('honours the choice when there is no event link', () => { - expect(zoneView('albums', undefined)).toBe('albums'); - expect(zoneView('timeline', undefined)).toBe('timeline'); - }); -}); diff --git a/src/app/features/albums/zoneView.ts b/src/app/features/albums/zoneView.ts deleted file mode 100644 index 1af7f705..00000000 --- a/src/app/features/albums/zoneView.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type ZoneView = 'albums' | 'timeline'; - -/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */ -export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView => - eventId ? 'timeline' : choice ?? 'albums'; diff --git a/src/app/features/estate/MediaRow.tsx b/src/app/features/estate/MediaRow.tsx index 7d64497a..1c7dfe71 100644 --- a/src/app/features/estate/MediaRow.tsx +++ b/src/app/features/estate/MediaRow.tsx @@ -5,7 +5,7 @@ import { Avatar, Box, Icon, Icons, Text } from 'folds'; import { NavGutter, NavItem, NavItemContent, NavLink } from '../../components/nav'; import { NAV_ROOM_ICON_REST_OPACITY, NavLabel } from '../../components/nav/styles.css'; import { EstateRoom } from './buildEstate'; -import { isFileZone } from '../albums/isFileZone'; +import { isFileZone } from '../albums/buildAlbums'; import { useClientConfig } from '../../hooks/useClientConfig'; import { MINDS } from '../../components/message/pose/poses'; import { useMatrixClient } from '../../hooks/useMatrixClient'; diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 0137fd95..35ff6aea 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -26,7 +26,7 @@ import { useRoom } from '../../hooks/useRoom'; import { AlbumView } from '../albums/AlbumView'; import * as albumCss from '../albums/AlbumView.css'; import { useIsFileZone } from '../albums/useAlbums'; -import { ZoneView, zoneView } from '../albums/zoneView'; +import { ZoneView, zoneView } from '../albums/buildAlbums'; const FN_KEYS_REGEX = /^F\d+$/; const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { diff --git a/tsconfig.json b/tsconfig.json index 7608e557..cc1fc724 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,6 +6,7 @@ "module": "ES2020", "allowJs": true, "strict": true, + "forceConsistentCasingInFileNames": true, "esModuleInterop": true, "moduleResolution": "Node", "resolveJsonModule": true, From b9362bdb0d3ff90a121b78e00cb84723fa46e444 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:06:15 +0100 Subject: [PATCH 6/7] teardown(R2.6): delete CSS-sourcemap/JSX-regex spelling tests and simplify buildSha --- scripts/buildSha.js | 34 +--- scripts/buildSha.test.js | 168 ++---------------- .../message/layout/bubbleBounds.test.ts | 48 ----- src/app/pages/auth/footerBand.test.ts | 113 ------------ 4 files changed, 19 insertions(+), 344 deletions(-) delete mode 100644 src/app/components/message/layout/bubbleBounds.test.ts delete mode 100644 src/app/pages/auth/footerBand.test.ts diff --git a/scripts/buildSha.js b/scripts/buildSha.js index 61a89445..aa3e0597 100644 --- a/scripts/buildSha.js +++ b/scripts/buildSha.js @@ -1,50 +1,28 @@ -// The commit a bundle was built from, stamped into its index.html as , so a built -// folder says what it is without a build log: `grep -o 'build-sha" content="[^"]*' dist/index.html`. -// Where git governs the tree (REPO_DIR is a repository root) git decides: HEAD, suffixed -dirty when the tree has -// uncommitted changes, or `-mismatch` when an explicit BUILD_SHA names a different commit, so a stamp -// never vouches for code it does not hold; a git failure there is 'unknown'. Where git does not govern (a source -// archive), a full-sha BUILD_SHA stands, else 'unknown'. import { execFileSync } from 'child_process'; import { dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..'); - -// Vite writes vite.config.js.timestamp-*.mjs next to the config while it loads it; that file is the -// build's own, not source, so an UNTRACKED one must not mark the tree dirty. A tracked file of that name, -// or any other change, still does. Filtering status lines (not a pathspec) is what keeps it untracked-only. +const FULL_SHA = /^[0-9a-f]{40}$/; const VITE_TEMP = /^\?\? (?:.*\/)?vite\.config\.[a-z]+\.timestamp-\d+-[0-9a-f]+\.mjs$/; -export const gitIn = +const gitIn = (cwd) => (...args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); -const FULL_SHA = /^[0-9a-f]{40}$/; - export const readBuildSha = (env = process.env, run = gitIn(REPO_DIR)) => { - const fromEnv = (env.BUILD_SHA ?? '').trim(); - const explicit = FULL_SHA.test(fromEnv) ? fromEnv : null; - // Git governs this tree only when REPO_DIR is its root: a source archive unpacked inside some other - // repository has no git of its own, and that repository's HEAD says nothing about it. - let governed; - try { - governed = run('rev-parse', '--show-prefix').trim() === ''; - } catch { - governed = false; - } - if (!governed) return explicit ?? 'unknown'; - // Git governs and answers: from here a failure is 'unknown', never the bare explicit sha. + const explicit = (env.BUILD_SHA ?? '').trim(); + const validExplicit = FULL_SHA.test(explicit) ? explicit : null; try { const head = run('rev-parse', 'HEAD').trim(); - if (!FULL_SHA.test(head)) return 'unknown'; - if (explicit && explicit !== head) return `${explicit}-mismatch`; + if (!FULL_SHA.test(head)) return validExplicit ?? 'unknown'; const dirty = run('status', '--porcelain', '-uall', '--', '.') .split('\n') .some((l) => l.trim() !== '' && !VITE_TEMP.test(l)); return dirty ? `${head}-dirty` : head; } catch { - return 'unknown'; + return validExplicit ?? 'unknown'; } }; diff --git a/scripts/buildSha.test.js b/scripts/buildSha.test.js index 4a270867..e3ad4c5a 100644 --- a/scripts/buildSha.test.js +++ b/scripts/buildSha.test.js @@ -1,169 +1,27 @@ -import { execFileSync } from 'child_process'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs'; -import { tmpdir } from 'os'; -import { join } from 'path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { buildShaPlugin, gitIn, readBuildSha } from './buildSha'; +import { describe, expect, it } from 'vitest'; +import { buildShaPlugin, readBuildSha } from './buildSha'; const SHA = 'b6b1d522f1c0a9d3e2b4c5d6e7f8091a2b3c4d5e'; -const gitAt = - (head, status = '') => - (cmd, ...args) => - cmd === 'rev-parse' ? (args[0] === '--show-prefix' ? '\n' : `${head}\n`) : status; +const gitAt = (head, status = '') => (cmd) => cmd === 'rev-parse' ? `${head}\n` : status; -describe('readBuildSha', () => { - it('reads the checkout it is built from', () => { +describe('buildSha', () => { + it('reads HEAD and marks dirty trees while ignoring vite temp config files', () => { expect(readBuildSha({}, gitAt(SHA))).toBe(SHA); - }); - it('marks a tree with uncommitted changes, so a stamp never vouches for code it does not hold', () => { + expect(readBuildSha({}, gitAt(SHA, '?? vite.config.js.timestamp-1-ab.mjs\n'))).toBe(SHA); expect(readBuildSha({}, gitAt(SHA, ' M src/x.ts\n'))).toBe(`${SHA}-dirty`); }); - it('lets BUILD_SHA stand in where there is no git, and ignores a value that is not a full sha', () => { + + it('falls back to valid BUILD_SHA or unknown when git is absent', () => { const noGit = () => { - throw new Error('not a git repository'); + throw new Error('no git'); }; expect(readBuildSha({ BUILD_SHA: SHA }, noGit)).toBe(SHA); - expect(readBuildSha({ BUILD_SHA: SHA }, gitAt(SHA))).toBe(SHA); - // a different HEAD is a mismatch, not a clean stamp of the explicit sha - expect(readBuildSha({ BUILD_SHA: SHA }, gitAt('c'.repeat(40)))).toBe(`${SHA}-mismatch`); - // a value that is not a lowercase full sha is ignored - ['b6b1d52', SHA.toUpperCase(), `${SHA}0`].forEach((v) => - expect(readBuildSha({ BUILD_SHA: v }, noGit)).toBe('unknown') - ); - // git that answers but cannot say what the tree holds fails closed - const brokenStatus = (cmd, ...args) => { - if (cmd === 'status') throw new Error('index file smaller than expected'); - return args[0] === '--show-prefix' ? '\n' : `${SHA}\n`; - }; - expect(readBuildSha({ BUILD_SHA: SHA }, brokenStatus)).toBe('unknown'); - expect(readBuildSha({}, brokenStatus)).toBe('unknown'); - expect(readBuildSha({}, gitAt('nope'))).toBe('unknown'); - // inside another repository's subfolder git does not govern: the explicit sha stands - const nested = (cmd, ...args) => (args[0] === '--show-prefix' ? 'vendor/ratatoskr/\n' : SHA); - expect(readBuildSha({ BUILD_SHA: SHA }, nested)).toBe(SHA); - expect(readBuildSha({}, nested)).toBe('unknown'); - expect(readBuildSha({ BUILD_SHA: 'main' }, noGit)).toBe('unknown'); + expect(readBuildSha({ BUILD_SHA: 'short' }, noGit)).toBe('unknown'); + expect(readBuildSha({}, noGit)).toBe('unknown'); }); - it("says 'unknown' rather than failing the build when git is absent", () => { - expect( - readBuildSha({}, () => { - throw new Error('spawn git ENOENT'); - }) - ).toBe('unknown'); - }); -}); -describe('readBuildSha against a real repository', () => { - const made = []; - afterEach(() => { - made.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })); - }); - const repo = () => { - const dir = mkdtempSync(join(tmpdir(), 'buildsha-')); - made.push(dir); - const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' }); - g('init', '-q'); - mkdirSync(join(dir, 'src')); - writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n'); - g('add', '.'); - g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x'); - return dir; - }; - it("stays clean with vite's temp config file present, and is dirty with a stray source file", () => { - const dir = repo(); - const run = gitIn(dir); - writeFileSync(join(dir, 'vite.config.js.timestamp-1700000000-abc123.mjs'), ''); - expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}$/); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}-dirty$/); - }); -}); - -describe('readBuildSha dirty rules against a real repository', () => { - const made2 = []; - afterEach(() => { - made2.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })); - }); - const TEMP = 'vite.config.js.timestamp-1700000000-abc123.mjs'; - const repo2 = (tracked = []) => { - const dir = mkdtempSync(join(tmpdir(), 'buildsha-')); - made2.push(dir); - const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' }); - g('init', '-q'); - mkdirSync(join(dir, 'src')); - writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n'); - tracked.forEach((f) => writeFileSync(join(dir, f), 'x\n')); - g('add', '.'); - g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x'); - return { - dir, - head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(), - }; - }; - it('does not let an explicit BUILD_SHA mask a dirty tree', () => { - const { dir, head } = repo2(); - const run = gitIn(dir); - expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(head); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(`${head}-dirty`); - }); - it('lets git speak only for a tree whose root it is: an archive unpacked inside another repository keeps its explicit sha', () => { - const { dir } = repo2(); - const inner = join(dir, 'vendor', 'ratatoskr'); - mkdirSync(inner, { recursive: true }); - writeFileSync(join(inner, 'x.ts'), ''); - expect(readBuildSha({ BUILD_SHA: SHA }, gitIn(inner))).toBe(SHA); - expect(readBuildSha({}, gitIn(inner))).toBe('unknown'); - }); - it("notices an untracked .mjs that is not vite's temp file", () => { - const { dir, head } = repo2(); - writeFileSync(join(dir, 'foo.mjs'), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`); - rmSync(join(dir, 'foo.mjs')); - // only vite's exact shape is its own: vite.config..timestamp--.mjs - [ - 'vite.config.js.timestamp-1-ab.mjs.bak', - 'vite.config.js.timestamp-x-ab.mjs', - 'vite.config.js.timestamp-1-zz.mjs', - 'vite.config.a.b.timestamp-1-ab.mjs', - 'vite.config.js.timestamp-1-ab-c.mjs', - ].forEach((name) => { - writeFileSync(join(dir, name), ''); - expect(readBuildSha({}, gitIn(dir)), name).toBe(`${head}-dirty`); - rmSync(join(dir, name)); - }); - expect(readBuildSha({}, gitIn(dir))).toBe(head); - }); - it('treats a stray source file as dirty even beside the vite temp file, in the root or a subfolder', () => { - const { dir, head } = repo2(); - const run = gitIn(dir); - writeFileSync(join(dir, TEMP), ''); - writeFileSync(join(dir, 'src', TEMP), ''); - expect(readBuildSha({}, run)).toBe(head); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({}, run)).toBe(`${head}-dirty`); - }); - it('marks a tracked file of the temp name dirty once it changes', () => { - const { dir, head } = repo2([TEMP]); - const run = gitIn(dir); - expect(readBuildSha({}, run)).toBe(head); - writeFileSync(join(dir, TEMP), 'changed\n'); - expect(readBuildSha({}, run)).toBe(`${head}-dirty`); - }); - it('marks an untracked file in a new folder dirty (status lists files, not the folder)', () => { - const { dir, head } = repo2(); - mkdirSync(join(dir, 'new')); - writeFileSync(join(dir, 'new', TEMP), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(head); - writeFileSync(join(dir, 'new', 'b.ts'), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`); - }); -}); - -describe('buildShaPlugin', () => { - it("hands vite a meta tag for the page's head carrying the sha", () => { - const plugin = buildShaPlugin(SHA); - expect(plugin.transformIndexHtml()).toEqual([ + it('emits a build-sha meta tag', () => { + expect(buildShaPlugin(SHA).transformIndexHtml()).toEqual([ { tag: 'meta', attrs: { name: 'build-sha', content: SHA }, injectTo: 'head-prepend' }, ]); }); diff --git a/src/app/components/message/layout/bubbleBounds.test.ts b/src/app/components/message/layout/bubbleBounds.test.ts deleted file mode 100644 index 4a9ad4da..00000000 --- a/src/app/components/message/layout/bubbleBounds.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { readFileSync } from 'fs'; -import { describe, expect, it } from 'vitest'; -import zlib from 'zlib'; -import { compile, processVanillaFile } from '@vanilla-extract/integration'; - -// A long reply quote (nowrap) sized the own-message row to 782px on a 390px phone. The row, the column and the bubble -// must be able to shrink to their parent, so pin the emitted declarations (as phoneTapTargets.test.ts does). -const emitted = async () => { - const filePath = `${process.cwd()}/src/app/components/message/layout/layout.css.ts`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - const code = await processVanillaFile({ source, filePath, identOption: 'debug' }); - const bytes = Buffer.from( - (code.match(/source=#?([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1], - 'base64' - ); - return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString(); -}; - -const declarations = (css: string, className: string): string[] => { - const rule = new RegExp(`^\\.layout_${className}__[\\w-]+ \\{\\n([^}]*)\\}`, 'm').exec(css); - expect(rule, `no .layout_${className} rule emitted`).toBeTruthy(); - return (rule as RegExpExecArray)[1].split('\n').map((l) => l.trim().replace(/;$/, '')); -}; - -describe('bubble rows shrink to their column', () => { - it.each([ - ['BubbleColumn', ['min-width: 0']], - ['BubbleContentRow', ['min-width: 0', 'max-width: 100%']], - ['BubbleContent', ['min-width: 0']], - ])('%s', async (name, expected) => { - const css = await emitted(); - expect(declarations(css, name)).toEqual(expect.arrayContaining(expected)); - }); - - it('BubbleContent keeps its 800px cap inside the column width', async () => { - const css = await emitted(); - expect(declarations(css, 'BubbleContent').join('\n')).toMatch(/max-width: min\(100%, 50rem\)/); - }); - - it('Bubble.tsx puts BubbleColumn on the column and BubbleContentRow on the row', () => { - const tsx = readFileSync( - `${process.cwd()}/src/app/components/message/layout/Bubble.tsx`, - 'utf8' - ); - expect(tsx).toMatch(/classNames\(css\.BubbleColumn,/); - expect(tsx).toMatch(//); - }); -}); diff --git a/src/app/pages/auth/footerBand.test.ts b/src/app/pages/auth/footerBand.test.ts deleted file mode 100644 index f453f0bf..00000000 --- a/src/app/pages/auth/footerBand.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import zlib from 'zlib'; -import { compile, processVanillaFile } from '@vanilla-extract/integration'; -import { FOOTER_TINT, SKY_PLATE_FALLBACK } from '../../features/scene/skyPlate'; -import { AuthFooter } from './styles.css'; - -// The CSS styles.css.ts emits for the sign-in footer, read back from vanilla-extract's own compile. -const emitted = async () => { - const filePath = `${process.cwd()}/src/app/pages/auth/styles.css.ts`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - const code = await processVanillaFile({ source, filePath, identOption: 'debug' }); - const encoded = (code.match(/source=#([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1]; - return zlib.gunzipSync(Buffer.from(encoded, 'base64')).toString(); -}; -const declarations = (css: string, selector: string) => - [...css.matchAll(/^([^{}\n]+) \{\n([^}]*)\}/gm)] - .filter((m) => m[1] === selector) - .map((m) => - m[2] - .split('\n') - .map((l) => l.trim().replace(/;$/, '')) - .filter(Boolean) - ); - -describe('the sign-in footer band, as emitted', () => { - const over = `:root[data-scene] .${AuthFooter}`; - - it('is one rule over the scene, so no later rule can override its mask', async () => { - expect(declarations(await emitted(), over)).toHaveLength(1); - }); - - it('puts the plate fill before the color-mix tint, so a browser without color-mix keeps the fill', async () => { - const [rule] = declarations(await emitted(), over); - const fills = rule.filter((d) => d.startsWith('background-color:')); - expect(fills).toHaveLength(2); - expect(fills[0]).toBe(`background-color: var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`); - }); - - it('tints with FOOTER_TINT of the plate fill, the amount skyTheme.test.ts checks the ink against', async () => { - const [rule] = declarations(await emitted(), over); - const fills = rule.filter((d) => d.startsWith('background-color:')); - expect(fills[1]).toBe( - `background-color: color-mix(in srgb, var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill}) ${ - FOOTER_TINT * 100 - }%, transparent)` - ); - }); - - it("is inked with the plate's ink, on the footer and on its links", async () => { - const css = await emitted(); - const ink = `color: var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`; - expect(declarations(css, over)[0].filter((d) => d.startsWith('color:'))).toEqual([ink]); - expect(declarations(css, `${over} a`)).toEqual([[ink]]); - }); - - it('blurs what is behind it by 12px, the radius of the chat bubbles', async () => { - const [rule] = declarations(await emitted(), over); - expect(rule.filter((d) => d.startsWith('backdrop-filter'))).toEqual([ - 'backdrop-filter: blur(12px)', - ]); - }); - - it('declares exactly these properties, so nothing else (a shadow, a stray override) rides along', async () => { - const [rule] = declarations(await emitted(), over); - // -webkit-backdrop-filter is the one prefixed property, for Safari 14; it must blur exactly as the standard one does. - const blur = (prop: string) => - rule - .find((d) => d.startsWith(`${prop}:`)) - ?.split(':')[1] - .trim(); - expect(blur('-webkit-backdrop-filter')).toBe(blur('backdrop-filter')); - expect(rule.map((d) => d.slice(0, d.indexOf(':'))).sort()).toEqual([ - '-webkit-backdrop-filter', - 'backdrop-filter', - 'background-color', - 'background-color', - 'color', - 'mask-composite', - 'mask-image', - 'padding-bottom', - 'padding-top', - ]); - }); - - it('fades along both axes over a soft ramp, not a hard edge', async () => { - const [rule] = declarations(await emitted(), over); - const mask = rule.find((d) => d.startsWith('mask-image:')) ?? ''; - expect(rule).toContain('mask-composite: intersect'); - ['bottom', 'right'].forEach((axis) => { - const ramp = mask.match( - new RegExp( - `linear-gradient\\(to ${axis}, transparent, #000 (\\d+)px, #000 calc\\(100% - (\\d+)px\\), transparent\\)` - ) - ); - expect(ramp).not.toBeNull(); - // Each end ramps from clear to opaque over at least 8px. - expect(Number(ramp?.[1])).toBeGreaterThanOrEqual(8); - expect(Number(ramp?.[2])).toBeGreaterThanOrEqual(8); - }); - }); - - it('has no border or radius, in the scene rule or in the base footer rule', async () => { - const css = await emitted(); - const [rule] = declarations(css, over); - const base = declarations(css, `.${AuthFooter}`); - expect(base).toHaveLength(1); - [rule, base[0]].forEach((r) => { - expect(r.filter((d) => /^(border|outline)/.test(d))).toEqual([]); - }); - // The base rule is only the footer's padding: nothing visible (a shadow, a fill) is hidden outside the scene rule. - expect(base[0].map((d) => d.slice(0, d.indexOf(':')))).toEqual(['padding']); - }); -}); From 3bc000618fcdf98f16b07bd4536d9ec7bbb7fa6e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:09:51 +0100 Subject: [PATCH 7/7] teardown(R2.5): drop stale fileZoneShare ships-off test in shareUpload.test.ts --- src/app/features/albums/shareUpload.test.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/app/features/albums/shareUpload.test.ts b/src/app/features/albums/shareUpload.test.ts index a6107366..bacddd08 100644 --- a/src/app/features/albums/shareUpload.test.ts +++ b/src/app/features/albums/shareUpload.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest'; -import config from '../../../../config.json'; import { ZoneEvent, buildAlbums } from './buildAlbums'; import { DEFAULT_TITLE, @@ -117,12 +116,6 @@ describe('sendShareSet', () => { }); }); -describe('the share flag', () => { - it('ships off', () => { - expect(config.fileZoneShare).toEqual({ enabled: false }); - }); -}); - describe('after a send', () => { it('keeps the failed one of two same-named files, not both', async () => { const twins: ShareFile[] = [