From e52bb6e3c4eb5519ea20a7f02220f65a1d34933c Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 25 Nov 2026 22:11:10 +0700 Subject: [PATCH] Select multiple sidebar workspaces to archive together (#10798) * feat(app): select multiple sidebar workspaces to archive together Let users enter workspace select mode from Shift+click/tap or the row menu, toggle additional rows with plain clicks without holding Shift, extend ranges with Shift+click, and archive all selected workspaces in one batch with a single worktree warning and undo toast. Tracks live hardware Shift state in the keyboard pipeline (clearing on blur and AppState backgrounding) so Shift+tap and Shift+click also work on native tablets with hardware keyboards where Pressable responder events omit shiftKey. Adds an action layout variant on ToastCard so pill controls inside action toasts share concentric padding and radius. * fix(app): preserve batch undo and selection ownership during bulk archive Keep workspace.archive bound for the full lifetime of sidebar select mode so pressing it at 0 selected or during a worktree check does not fall through to archive the open workspace. On partial archive failures, update the open UndoWindow toast in place with error styling and the failure message instead of calling toast.error, so Undo and Cmd/Ctrl+Z remain available for succeeded workspaces and their layout state is not purged early. Guard isArchiving cleanup with a per-attempt token so an earlier batch cannot unlock a newer batch's worktree check, and read the active workspace lazily at redirect time rather than capturing it at submission. * fix(app): stack sidebar selection bar below toasts and protect newer undo Keep the sidebar selection bar visible alongside active transient toasts (such as Undo or error toasts) by rendering both slots in ToastViewport's sidebar stack instead of hiding the persistent bar while a transient toast is open. Route late archive errors from a superseded batch to the app-level toast when a newer batch holds an open Undo window, so an older failure does not replace the active Undo toast or purge the newer batch's layout state. * fix(app): toggle focused sidebar workspace checkboxes with Space on web React Native Web's Pressable activates Space only for role='button', not role='checkbox'. Handle Space on focused checkbox rows in SidebarWorkspaceContextMenu so keyboard users can toggle rows in either sidebar grouping. * fix(app): ignore repeated Space keydown on focused workspace checkboxes * fix(app): keep Escape owned by select mode during worktree checks --- packages/app/src/components/left-sidebar.tsx | 3 + .../src/components/sidebar-workspace-list.tsx | 158 +++++++- .../sidebar/sidebar-status-list.tsx | 169 ++++++++- .../sidebar/sidebar-toast-region.tsx | 63 +++- .../sidebar/sidebar-workspace-menu.tsx | 47 ++- .../sidebar/sidebar-workspace-row-content.tsx | 115 ++++-- packages/app/src/components/toast-host.tsx | 100 ++++- .../app/src/git/worktree-archive-warning.ts | 38 ++ packages/app/src/i18n/resources/ar.ts | 9 + packages/app/src/i18n/resources/en.ts | 9 + packages/app/src/i18n/resources/es.ts | 9 + packages/app/src/i18n/resources/fr.ts | 9 + packages/app/src/i18n/resources/ja.ts | 9 + packages/app/src/i18n/resources/ko.ts | 9 + packages/app/src/i18n/resources/pt-BR.ts | 9 + packages/app/src/i18n/resources/ru.ts | 9 + packages/app/src/i18n/resources/zh-CN.ts | 9 + packages/app/src/keyboard/index.ts | 1 + .../src/keyboard/internal/shift-modifier.ts | 51 +++ .../src/keyboard/internal/sources/index.ts | 9 + .../src/keyboard/internal/sources/native.ts | 3 + .../app/src/keyboard/native-shortcuts.test.ts | 76 ++++ packages/app/src/keyboard/use-shortcuts.ts | 19 +- packages/app/src/sidebar-selection/index.ts | 8 + .../internal/archive-selected.test.ts | 280 ++++++++++++++ .../internal/archive-selected.ts | 197 ++++++++++ .../internal/selection-state.test.ts | 93 +++++ .../internal/selection-state.ts | 129 +++++++ .../internal/selection-store.ts | 82 ++++ .../sidebar-selection-host.browser.test.tsx | 355 ++++++++++++++++++ .../internal/sidebar-selection-host.tsx | 157 ++++++++ .../internal/workspace-selection-toast.tsx | 83 ++++ .../app/src/workspace/archive-undo/index.ts | 5 + .../archive-undo/internal/undo-window.test.ts | 167 ++++++++ .../archive-undo/internal/undo-window.tsx | 204 ++++++++-- .../internal/workspace-archived-toast.tsx | 19 +- .../app/test-stubs/lucide-react-native.ts | 2 + 37 files changed, 2587 insertions(+), 127 deletions(-) create mode 100644 packages/app/src/keyboard/internal/shift-modifier.ts create mode 100644 packages/app/src/sidebar-selection/index.ts create mode 100644 packages/app/src/sidebar-selection/internal/archive-selected.test.ts create mode 100644 packages/app/src/sidebar-selection/internal/archive-selected.ts create mode 100644 packages/app/src/sidebar-selection/internal/selection-state.test.ts create mode 100644 packages/app/src/sidebar-selection/internal/selection-state.ts create mode 100644 packages/app/src/sidebar-selection/internal/selection-store.ts create mode 100644 packages/app/src/sidebar-selection/internal/sidebar-selection-host.browser.test.tsx create mode 100644 packages/app/src/sidebar-selection/internal/sidebar-selection-host.tsx create mode 100644 packages/app/src/sidebar-selection/internal/workspace-selection-toast.tsx diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index bd6d22a88a..4c20d809d8 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker"; import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu"; import { SidebarSeparator } from "@/components/sidebar/sidebar-separator"; import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region"; +import { SidebarSelectionHost } from "@/sidebar-selection"; import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows"; import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight"; import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu"; @@ -667,6 +668,7 @@ function MobileSidebar({ listHeaderComponent={workspacesSectionHeaderElement} /> )} + @@ -922,6 +924,7 @@ function DesktopSidebar({ listHeaderComponent={workspacesSectionHeaderElement} /> )} + diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index a3566ab0b1..6a092ead09 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -101,7 +101,17 @@ import { import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction"; import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header"; import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row"; -import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility"; +import { + createWorkspaceVisibilityPolicy, + selectSidebarGroupVisibility, +} from "@/components/sidebar/sidebar-group-visibility"; +import { + isShiftPressEvent, + registerSidebarVisibleWorkspaceKeysReader, + useIsSidebarSelectionMode, + useIsWorkspaceBulkSelected, + useSidebarSelectionStore, +} from "@/sidebar-selection"; import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group"; import { SidebarWorkspaceRowFrame, @@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps { archiveLabel?: string; archiveStatus?: "idle" | "pending" | "success"; archivePendingLabel?: string; + onSelectWorkspace?: () => void; onArchive?: () => void; onCopyBranchName?: () => void; onCopyPath?: () => void; @@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({ isHovered, isTouchPlatform, isCreating, + isSelectionMode, showShortcutBadge, shortcutNumber, archiveLabel, archiveStatus, archivePendingLabel, archiveShortcutKeys, + onSelectWorkspace, onArchive, onMarkAsRead, onMarkAsUnread, @@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({ isHovered: boolean; isTouchPlatform: boolean; isCreating: boolean; + isSelectionMode: boolean; showShortcutBadge: boolean; shortcutNumber: number | null; archiveLabel?: string; archiveStatus?: "idle" | "pending" | "success"; archivePendingLabel?: string; archiveShortcutKeys?: ShortcutKey[][] | null; + onSelectWorkspace?: () => void; onArchive?: () => void; onMarkAsRead?: () => void; onMarkAsUnread?: () => void; @@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({ isHovered, isTouchPlatform, showShortcut, + isSelectionMode, }); const kebab = useOpenKebabMenuVisibility(showKebabInSlot); @@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({ onRename={onRename} onMarkAsRead={onMarkAsRead} onMarkAsUnread={onMarkAsUnread} + onSelectWorkspace={onSelectWorkspace} onArchive={onArchive} archiveLabel={archiveLabel} archiveStatus={archiveStatus} @@ -1065,6 +1082,7 @@ function WorkspaceRowInner({ archiveLabel, archiveStatus = "idle", archivePendingLabel, + onSelectWorkspace, onArchive, onCopyBranchName, onCopyPath, @@ -1079,6 +1097,8 @@ function WorkspaceRowInner({ }: WorkspaceRowInnerProps) { const isCompact = useIsCompactFormFactor(); const [isHighlighted, setIsHighlighted] = useState(false); + const isSelectionMode = useIsSidebarSelectionMode(); + const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey); const isTouchPlatform = platformIsNative || isCompact; const interaction = useLongPressDragInteraction({ drag, @@ -1091,30 +1111,75 @@ function WorkspaceRowInner({ ...dragAttributes } = dragHandleProps?.attributes ?? {}; - const { onPress: handlePress, feedback } = useWorkspaceRowPress({ + const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({ didLongPressRef: interaction.didLongPressRef, onPress, selected, }); - const accessibilityState = useMemo(() => ({ selected }), [selected]); + const handleRowPress = useCallback( + (event: GestureResponderEvent) => { + const shiftKey = isShiftPressEvent(event); + if (isSelectionMode || shiftKey) { + if (interaction.didLongPressRef.current) { + interaction.didLongPressRef.current = false; + return; + } + event.preventDefault?.(); + useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey }); + return; + } + handleNavigatePress(); + }, + [handleNavigatePress, interaction.didLongPressRef, isSelectionMode, workspace.workspaceKey], + ); + + const handleRowPressIn = useCallback( + (event: GestureResponderEvent) => { + if (isShiftPressEvent(event)) { + event.preventDefault?.(); + return; + } + if (!isSelectionMode) { + interaction.handlePressIn(event); + } + }, + [interaction, isSelectionMode], + ); + + const rowSelected = isSelectionMode ? isBulkSelected : selected; + const accessibilityState = useMemo( + () => (isSelectionMode ? { checked: isBulkSelected } : { selected }), + [isSelectionMode, isBulkSelected, selected], + ); const isEditingTitle = titleEditor !== null; + const disableDrag = isEditingTitle || isSelectionMode; return ( {({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => { const isDesktop = !isTouchPlatform; const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null; - const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered }); - const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered }); + const workspaceRowStyle = getProjectWorkspaceRowStyle({ + isDragging, + selected: rowSelected, + isHovered, + }); + const backdrop = getSidebarRowBackdrop({ + isDragging, + isHighlighted, + selected: rowSelected, + isHovered, + }); return ( } style={styles.workspaceRowContainer} {...hoverHandlers} @@ -1131,6 +1196,7 @@ function WorkspaceRowInner({ onRename={onRename} onMarkAsRead={onMarkAsRead} onMarkAsUnread={onMarkAsUnread} + onSelectWorkspace={onSelectWorkspace} onArchive={onArchive} archiveLabel={archiveLabel} archiveStatus={archiveStatus} @@ -1140,17 +1206,18 @@ function WorkspaceRowInner({ onTogglePin={onTogglePin} openInFileManagerPath={workspace.workspaceDirectory} disabled={isArchiving} - enabled={!isEditingTitle} - aria-selected={selected} - accessibilityRole="button" + enabled={!isEditingTitle && !isSelectionMode} + aria-selected={isSelectionMode ? undefined : selected} + aria-checked={isSelectionMode ? isBulkSelected : undefined} + accessibilityRole={isSelectionMode ? "checkbox" : "button"} accessibilityState={accessibilityState} style={workspaceRowStyle} highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed} onHighlightChange={setIsHighlighted} - onPressIn={isEditingTitle ? undefined : interaction.handlePressIn} - onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove} - onPressOut={isEditingTitle ? undefined : interaction.handlePressOut} - onPress={isEditingTitle ? undefined : handlePress} + onPressIn={isEditingTitle ? undefined : handleRowPressIn} + onTouchMove={disableDrag ? undefined : interaction.handleTouchMove} + onPressOut={disableDrag ? undefined : interaction.handlePressOut} + onPress={isEditingTitle ? undefined : handleRowPress} testID={`sidebar-workspace-row-${workspace.workspaceKey}`} > { + useSidebarSelectionStore.getState().enter(workspace.workspaceKey); + }, [workspace.workspaceKey]); + const clipboard = useWorkspaceClipboardActions(); const handleCopyPath = useCallback(() => { clipboard.copyPath(workspace); @@ -1317,6 +1392,7 @@ function WorkspaceRowWithMenu({ archiveLabel={t("sidebar.workspace.actions.archive")} archiveStatus={isArchiving ? "pending" : "idle"} archivePendingLabel={t("sidebar.workspace.actions.archiving")} + onSelectWorkspace={handleSelectWorkspace} onArchive={handleArchive} onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined} onCopyPath={handleCopyPath} @@ -2199,6 +2275,62 @@ function ProjectModeList({ selection: selectionEnabled ? activeWorkspaceSelection : null, expanded: pinnedChatsExpanded, }); + + const visibleOrderInputRef = useRef({ + pinnedCollapsed, + leadingPinnedChat, + visiblePinnedChats, + unpinnedProjects, + collapsedProjectKeys, + expandedProjectKeys, + selectionEnabled, + activeWorkspaceSelection, + workspaceEntriesByKey, + }); + visibleOrderInputRef.current = { + pinnedCollapsed, + leadingPinnedChat, + visiblePinnedChats, + unpinnedProjects, + collapsedProjectKeys, + expandedProjectKeys, + selectionEnabled, + activeWorkspaceSelection, + workspaceEntriesByKey, + }; + + useEffect(() => { + return registerSidebarVisibleWorkspaceKeysReader(() => { + const current = visibleOrderInputRef.current; + const keys: string[] = []; + if (!current.pinnedCollapsed) { + if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey); + for (const item of current.visiblePinnedChats) { + keys.push(item.workspaceKey); + } + } + const policy = createWorkspaceVisibilityPolicy( + current.workspaceEntriesByKey, + ); + const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null; + for (const project of current.unpinnedProjects) { + if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) { + continue; + } + const { leadingItem, visibleItems } = selectSidebarGroupVisibility({ + items: project.workspaces, + selection, + expanded: current.expandedProjectKeys.has(project.viewKey), + policy, + }); + if (leadingItem) keys.push(leadingItem.workspaceKey); + for (const item of visibleItems) { + keys.push(item.workspaceKey); + } + } + return keys; + }); + }, []); const nativeScrollGestureProps = useMemo( () => parentGestureRef diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index c3fcb99ae6..914a6a14b7 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -3,14 +3,16 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight"; import { memo, useCallback, + useEffect, useMemo, + useRef, useState, type MutableRefObject, type ReactNode, type Ref, } from "react"; import { useTranslation } from "react-i18next"; -import { View, Text, ScrollView } from "react-native"; +import { View, Text, ScrollView, type GestureResponderEvent } from "react-native"; import { NestableScrollContainer } from "react-native-draggable-flatlist"; import type { GestureType } from "react-native-gesture-handler"; import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store"; @@ -69,7 +71,15 @@ import { } from "@/components/sidebar/sidebar-workspace-menu"; import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header"; import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row"; +import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility"; import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group"; +import { + isShiftPressEvent, + registerSidebarVisibleWorkspaceKeysReader, + useIsSidebarSelectionMode, + useIsWorkspaceBulkSelected, + useSidebarSelectionStore, +} from "@/sidebar-selection"; import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin"; import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list"; import type { DraggableListDragHandleProps } from "@/components/draggable-list.types"; @@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({ () => setPinnedWorkspacesExpanded((current) => !current), [], ); + const [expandedGroupKeys, setExpandedGroupKeys] = useState>(() => new Set()); + const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => { + setExpandedGroupKeys((current) => { + const next = new Set(current); + if (!next.delete(groupKey)) next.add(groupKey); + return next; + }); + }, []); const { leadingItem: leadingPinnedWorkspace, visibleItems: visiblePinnedWorkspaces, @@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({ expanded: pinnedWorkspacesExpanded, }); + const visibleOrderInputRef = useRef({ + pinnedCollapsed, + leadingPinnedWorkspace, + visiblePinnedWorkspaces, + groups, + collapsedWorkspaceGroupKeys, + expandedGroupKeys, + activeWorkspaceSelection, + }); + visibleOrderInputRef.current = { + pinnedCollapsed, + leadingPinnedWorkspace, + visiblePinnedWorkspaces, + groups, + collapsedWorkspaceGroupKeys, + expandedGroupKeys, + activeWorkspaceSelection, + }; + + useEffect(() => { + return registerSidebarVisibleWorkspaceKeysReader(() => { + const current = visibleOrderInputRef.current; + const keys: string[] = []; + if (!current.pinnedCollapsed) { + if (current.leadingPinnedWorkspace) { + keys.push(current.leadingPinnedWorkspace.workspaceKey); + } + for (const item of current.visiblePinnedWorkspaces) { + keys.push(item.workspaceKey); + } + } + for (const group of current.groups) { + if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) { + continue; + } + const { leadingItem, visibleItems } = selectSidebarGroupVisibility({ + items: group.rows, + selection: current.activeWorkspaceSelection, + expanded: current.expandedGroupKeys.has(group.key), + policy: STATUS_GROUP_VISIBILITY, + }); + if (leadingItem) keys.push(leadingItem.workspaceKey); + for (const item of visibleItems) { + keys.push(item.workspaceKey); + } + } + return keys; + }); + }, []); + const statusShortcutIndex = showShortcutBadges ? shortcutIndexByWorkspaceKey : EMPTY_SHORTCUT_INDEX; @@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({ ; + expandedGroupKeys: ReadonlySet; + onToggleGroupWorkspacesExpanded: (groupKey: string) => void; projectIconByProjectViewKey: ReadonlyMap; shortcutIndex: Map; showShortcutBadges: boolean; @@ -328,6 +402,8 @@ function StatusGroupList({ key={group.key} group={group} collapsed={collapsedWorkspaceGroupKeys.has(group.key)} + workspacesExpanded={expandedGroupKeys.has(group.key)} + onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded} projectIconByProjectViewKey={projectIconByProjectViewKey} shortcutIndex={shortcutIndex} showShortcutBadges={showShortcutBadges} @@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = { function StatusGroupRows({ group, collapsed, + workspacesExpanded, + onToggleWorkspacesExpanded, projectIconByProjectViewKey, shortcutIndex, showShortcutBadges, @@ -359,6 +437,8 @@ function StatusGroupRows({ }: { group: SidebarWorkspaceGroup; collapsed: boolean; + workspacesExpanded: boolean; + onToggleWorkspacesExpanded: (groupKey: string) => void; projectIconByProjectViewKey: ReadonlyMap; shortcutIndex: Map; showShortcutBadges: boolean; @@ -368,10 +448,9 @@ function StatusGroupRows({ onToggleWorkspacePin: ToggleSidebarWorkspacePin; }) { const activeWorkspaceSelection = useActiveWorkspaceSelection(); - const [workspacesExpanded, setWorkspacesExpanded] = useState(false); const toggleWorkspacesExpanded = useCallback( - () => setWorkspacesExpanded((current) => !current), - [], + () => onToggleWorkspacesExpanded(group.key), + [group.key, onToggleWorkspacesExpanded], ); const { leadingItem: leadingWorkspace, @@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({ archiveController.archive(); }, [archiveController, isArchiving]); + const handleSelectWorkspace = useCallback(() => { + useSidebarSelectionStore.getState().enter(workspace.workspaceKey); + }, [workspace.workspaceKey]); + const clipboard = useWorkspaceClipboardActions(); const handleCopyPath = useCallback(() => { clipboard.copyPath(workspace); @@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({ archiveLabel={t("sidebar.workspace.actions.archive")} archiveStatus={isArchiving ? "pending" : "idle"} archivePendingLabel={t("sidebar.workspace.actions.archiving")} + onSelectWorkspace={handleSelectWorkspace} onArchive={handleArchive} onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined} onCopyPath={handleCopyPath} @@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps { archiveLabel?: string; archiveStatus?: "idle" | "pending" | "success"; archivePendingLabel?: string; + onSelectWorkspace?: () => void; onArchive?: () => void; onCopyBranchName?: () => void; onCopyPath?: () => void; @@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({ archiveLabel, archiveStatus = "idle", archivePendingLabel, + onSelectWorkspace, onArchive, onCopyBranchName, onCopyPath, @@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({ const isCompact = useIsCompactFormFactor(); const isTouchPlatform = platformIsNative || isCompact; const [isHighlighted, setIsHighlighted] = useState(false); + const isSelectionMode = useIsSidebarSelectionMode(); + const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey); const trailing = useSidebarWorkspaceTrailing(); const { role: _dragRole, @@ -831,23 +919,59 @@ function StatusWorkspaceRowInnerContent({ const isDesktop = !isTouchPlatform; const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null; - const accessibilityState = useMemo(() => ({ selected }), [selected]); + const rowSelected = isSelectionMode ? isBulkSelected : selected; + const accessibilityState = useMemo( + () => (isSelectionMode ? { checked: isBulkSelected } : { selected }), + [isSelectionMode, isBulkSelected, selected], + ); const isEditingTitle = titleEditor !== null; + const disableDrag = isEditingTitle || isSelectionMode; const didLongPressRef = dragInteraction?.didLongPressRef; const startDragPress = dragInteraction?.handlePressIn; const moveDragPress = dragInteraction?.handleTouchMove; const endDragPress = dragInteraction?.handlePressOut; - const { onPress: handlePress, feedback } = useWorkspaceRowPress({ + const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({ didLongPressRef, onPress, selected, }); + const handleRowPress = useCallback( + (event: GestureResponderEvent) => { + const shiftKey = isShiftPressEvent(event); + if (isSelectionMode || shiftKey) { + if (didLongPressRef?.current) { + didLongPressRef.current = false; + return; + } + event.preventDefault?.(); + useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey }); + return; + } + handleNavigatePress(); + }, + [didLongPressRef, handleNavigatePress, isSelectionMode, workspace.workspaceKey], + ); + + const handleRowPressIn = useCallback( + (event: GestureResponderEvent) => { + if (isShiftPressEvent(event)) { + event.preventDefault?.(); + return; + } + if (!isSelectionMode) { + startDragPress?.(event); + } + }, + [isSelectionMode, startDragPress], + ); + return ( {({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => { const showShortcut = showShortcutBadge && shortcutNumber !== null; @@ -865,18 +989,24 @@ function StatusWorkspaceRowInnerContent({ isHovered, isTouchPlatform, showShortcut, + isSelectionMode, }); const workspaceRowStyle = getStatusWorkspaceRowStyle({ - selected, + selected: rowSelected, isHovered, inStatusGroup, isDragging, }); - const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered }); + const backdrop = getSidebarRowBackdrop({ + isDragging, + isHighlighted, + selected: rowSelected, + isHovered, + }); return ( } style={styles.workspaceRowContainer} {...hoverHandlers} @@ -894,6 +1024,7 @@ function StatusWorkspaceRowInnerContent({ onRename={onRename} onMarkAsRead={onMarkAsRead} onMarkAsUnread={onMarkAsUnread} + onSelectWorkspace={onSelectWorkspace} onArchive={onArchive} archiveLabel={archiveLabel} archiveStatus={archiveStatus} @@ -903,16 +1034,18 @@ function StatusWorkspaceRowInnerContent({ onTogglePin={onTogglePin} openInFileManagerPath={workspace.workspaceDirectory} disabled={isArchiving} - enabled={!isEditingTitle} - accessibilityRole="button" + enabled={!isEditingTitle && !isSelectionMode} + aria-selected={isSelectionMode ? undefined : selected} + aria-checked={isSelectionMode ? isBulkSelected : undefined} + accessibilityRole={isSelectionMode ? "checkbox" : "button"} accessibilityState={accessibilityState} style={workspaceRowStyle} highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed} onHighlightChange={setIsHighlighted} - onPressIn={isEditingTitle ? undefined : startDragPress} - onTouchMove={isEditingTitle ? undefined : moveDragPress} - onPressOut={isEditingTitle ? undefined : endDragPress} - onPress={isEditingTitle ? undefined : handlePress} + onPressIn={isEditingTitle ? undefined : handleRowPressIn} + onTouchMove={disableDrag ? undefined : moveDragPress} + onPressOut={disableDrag ? undefined : endDragPress} + onPress={isEditingTitle ? undefined : handleRowPress} testID={`sidebar-workspace-row-${workspace.workspaceKey}`} > void; onMarkAsRead?: () => void; onMarkAsUnread?: () => void; + onSelectWorkspace?: () => void; onArchive?: () => void; archiveLabel?: string; archiveStatus?: "idle" | "pending" | "success"; @@ -1034,6 +1172,7 @@ function StatusWorkspaceActionSlot({ onRename={onRename} onMarkAsRead={onMarkAsRead} onMarkAsUnread={onMarkAsUnread} + onSelectWorkspace={onSelectWorkspace} onArchive={onArchive} archiveLabel={archiveLabel} archiveStatus={archiveStatus} diff --git a/packages/app/src/components/sidebar/sidebar-toast-region.tsx b/packages/app/src/components/sidebar/sidebar-toast-region.tsx index 002bf2f3f3..8cede9fca2 100644 --- a/packages/app/src/components/sidebar/sidebar-toast-region.tsx +++ b/packages/app/src/components/sidebar/sidebar-toast-region.tsx @@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef, + useState, type ReactNode, } from "react"; import { View } from "react-native"; @@ -15,7 +16,13 @@ import Animated, { type SharedValue, } from "react-native-reanimated"; import { StyleSheet } from "react-native-unistyles"; -import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host"; +import { + TOAST_FADE_MS, + ToastViewport, + useToastHost, + type ToastApi, + type ToastState, +} from "@/components/toast-host"; import { ToastApiProvider, useToast } from "@/contexts/toast-context"; interface SidebarToastCoverage { @@ -25,6 +32,10 @@ interface SidebarToastCoverage { } const SidebarToastCoverageContext = createContext(null); +const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>( + null, +); +const SidebarAppToastContext = createContext(null); /** * Shows toasts raised by the sidebar's list over its bottom edge, just above the footer. @@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext(n export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) { const appToast = useToast(); const { api: sidebarToast, toast, dismiss } = useToastHost(); + const [persistentToast, setPersistentToast] = useState(null); const activeRef = useRef(active); const coverageHeight = useSharedValue(0); - const toastVisible = toast !== null; + const toastVisible = toast !== null || persistentToast !== null; useEffect(() => { activeRef.current = active; @@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil return ( - - {children} - - + + + + + {children} + + + + + ); } +/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */ +export function useSidebarAppToast(): ToastApi { + const fallbackToast = useToast(); + return useContext(SidebarAppToastContext) ?? fallbackToast; +} + +/** + * Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active + * transient toast so controls stay reachable while a previous toast is up. + */ +export function useSidebarPersistentToast(toast: ToastState | null): void { + const setPersistentToast = useContext(SidebarPersistentToastContext); + useEffect(() => { + setPersistentToast?.(toast); + }, [setPersistentToast, toast]); + useEffect(() => { + return () => { + setPersistentToast?.(null); + }; + }, [setPersistentToast]); +} + /** * Space at the end of a sidebar list that matches the toast covering it, so the last row can * scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks diff --git a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx index ac872ffbd8..ec95f2a229 100644 --- a/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx +++ b/packages/app/src/components/sidebar/sidebar-workspace-menu.tsx @@ -1,9 +1,10 @@ import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; -import type { PressableStateCallbackType } from "react-native"; +import type { GestureResponderEvent, PressableStateCallbackType } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Archive, + CheckSquare, Circle, CircleCheck, Copy, @@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({ const ThemedMoreVertical = withUnistyles(MoreVertical); const ThemedCopy = withUnistyles(Copy); const ThemedArchive = withUnistyles(Archive); +const ThemedCheckSquare = withUnistyles(CheckSquare); const ThemedCircle = withUnistyles(Circle); const ThemedPencil = withUnistyles(Pencil); const ThemedCircleCheck = withUnistyles(CircleCheck); @@ -69,6 +71,7 @@ const markAsReadLeadingIcon = ( ); const markAsUnreadLeadingIcon = ; +const selectLeadingIcon = ; const archiveLeadingIcon = ; const pinLeadingIcon = ; const unpinLeadingIcon = ; @@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps { onRename?: () => void; onMarkAsRead?: () => void; onMarkAsUnread?: () => void; + onSelectWorkspace?: () => void; onArchive: () => void; archiveLabel?: string; archiveStatus?: "idle" | "pending" | "success"; @@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({ onRename, onMarkAsRead, onMarkAsUnread, + onSelectWorkspace, onArchive, archiveLabel, archiveStatus, @@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({ path={openInFileManagerPath} testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`} /> + {onSelectWorkspace ? ( + + {t("sidebar.workspace.actions.select")} + + ) : null} {onArchive ? ( { + if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) { + return {}; + } + const onPress = triggerProps.onPress; + return { + // React Native Web's Pressable activates Space only for role="button", not checkbox. + onKeyDown: (event: { + key?: string; + repeat?: boolean; + target?: unknown; + currentTarget?: unknown; + preventDefault?: () => void; + }) => { + if (triggerProps.disabled) return; + if (event.target !== event.currentTarget) return; + if (event.key === " " || event.key === "Spacebar") { + event.preventDefault?.(); + if (!event.repeat) { + onPress(event as unknown as GestureResponderEvent); + } + } + }, + }; + }, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]); return ( ({ color: theme.colors.surface0, fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined, }); +const checkedIconMapping = (theme: Theme) => ({ + color: theme.colors.accentForeground, +}); +const ThemedCheck = withUnistyles(Check); const ThemedCircleAlert = withUnistyles(CircleAlert); export function SidebarWorkspaceRowFrame({ workspace, isDragging = false, isEditingTitle = false, + isSelectionMode = false, children, }: { workspace: SidebarWorkspaceEntry; isDragging?: boolean; /** Hover would fade the kebab in over the title being edited and open the hover card. */ isEditingTitle?: boolean; + /** Hover cards would cover neighbouring rows while the user clicks through a selection. */ + isSelectionMode?: boolean; children: (input: { isHovered: boolean; contextMenuOpen: boolean; @@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({ workspace={workspace} prHint={workspace.prHint} isDragging={isDragging} - disabled={contextMenuOpen || isEditingTitle} + disabled={contextMenuOpen || isEditingTitle || isSelectionMode} > {children({ isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle, @@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte isHovered, isLoading, isCreating = false, + isSelectionMode = false, + isBulkSelected = false, shortcutNumber = null, showShortcutBadge = false, reserveIdleStatusIndicatorSpace = true, @@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte isHovered: boolean; isLoading: boolean; isCreating?: boolean; + isSelectionMode?: boolean; + isBulkSelected?: boolean; shortcutNumber?: number | null; showShortcutBadge?: boolean; /** Keep the empty leading slot when the workspace has no active status. */ @@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte const workspaceBranchTextStyle = useMemo( () => [ styles.workspaceBranchText, - isHovered && styles.workspaceBranchTextHovered, + (isHovered || isBulkSelected) && styles.workspaceBranchTextHovered, isCreating && styles.workspaceBranchTextCreating, ], - [isHovered, isCreating], + [isHovered, isBulkSelected, isCreating], ); + let leadingVisual: ReactNode; + if (isSelectionMode) { + leadingVisual = ( + + ); + } else if (leadingProjectName) { + leadingVisual = ( + + ); + } else { + leadingVisual = ( + + ); + } + return ( - {leadingProjectName ? ( - - ) : ( - - )} + {leadingVisual} {titleEditor ? ( @@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte /> - {showShortcutBadge && shortcutNumber !== null ? ( + {!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? ( @@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte ); }); +function WorkspaceSelectionCheckbox({ + checked, + workspaceKey, +}: { + checked: boolean; + workspaceKey: string; +}) { + return ( + + + {checked ? : null} + + + ); +} + function WorkspaceStatusIndicator({ bucket, workspaceKind, @@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({ isHovered, isTouchPlatform, showShortcut, + isSelectionMode = false, }: { workspace: SidebarWorkspaceEntry; trailing: SidebarWorkspaceTrailing; @@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({ isHovered: boolean; isTouchPlatform: boolean; showShortcut: boolean; + isSelectionMode?: boolean; }): { trailingPresentation: SidebarWorkspaceTrailingPresentation; showKebab: boolean; @@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({ reserveSlotWidth: boolean; } { const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing }); - const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut; + const allowRowActions = hasArchiveAction && !isSelectionMode; + const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut; // Touch permanently replaces the stats with the menu. Only temporary shortcut hints // conceal content while retaining its width, so desktop rows do not shift. - const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform); + const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform); let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent"; if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible"; return { @@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({ // row — over an unhovered one the gradient fades to the wrong color. That is also why // touch, which shows the kebab without ever hovering, never gets one. showScrim: showKebab && isHovered, - renderSlot: hasArchiveAction || hasTrailing, + renderSlot: allowRowActions || hasTrailing, // The slot only holds width for something that permanently sits in it. Trailing content // does; the kebab only does on touch, where there is no hover for it to appear on and so // no scrim to let it overlay the title. Everywhere else the width goes back to the title // and the kebab fades in over its tail. - reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform), + reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform), }; } @@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", justifyContent: "center", }, + selectionCheckbox: { + width: bySizing({ touch: 18, pointer: 15 }), + height: bySizing({ touch: 18, pointer: 15 }), + borderRadius: theme.borderRadius.sm, + borderWidth: 1.5, + borderColor: theme.colors.borderAccent, + alignItems: "center", + justifyContent: "center", + }, + selectionCheckboxChecked: { + width: bySizing({ touch: 18, pointer: 15 }), + height: bySizing({ touch: 18, pointer: 15 }), + borderRadius: theme.borderRadius.sm, + borderWidth: 1.5, + borderColor: theme.colors.accent, + backgroundColor: theme.colors.accent, + alignItems: "center", + justifyContent: "center", + }, statusDotOverlay: { position: "absolute", right: 0, diff --git a/packages/app/src/components/toast-host.tsx b/packages/app/src/components/toast-host.tsx index a5ec252e55..1ddcb871c7 100644 --- a/packages/app/src/components/toast-host.tsx +++ b/packages/app/src/components/toast-host.tsx @@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { SPACING, type Theme } from "@/styles/theme"; +import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry"; import { useTranslation } from "react-i18next"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isWeb } from "@/constants/platform"; @@ -28,10 +29,16 @@ import { } from "@/constants/layout"; export type ToastVariant = "default" | "info" | "success" | "warning" | "error"; +/** + * `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a + * concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell. + */ +export type ToastLayout = "default" | "action"; export interface ToastShowOptions { icon?: ReactNode; variant?: ToastVariant; + layout?: ToastLayout; durationMs?: number | null; nativeAndroid?: boolean; testID?: string; @@ -45,6 +52,7 @@ export interface ToastState { nativeMessage: string | null; icon?: ReactNode; variant: ToastVariant; + layout?: ToastLayout; durationMs: number | null; testID?: string; onDismiss?: () => void; @@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480; /** How long a toast takes to fade in or out. */ export const TOAST_FADE_MS = 140; const SIDEBAR_TOAST_INSET = SPACING[2]; +const ACTION_TOAST_INSET = SPACING[1.5]; +const ACTION_TOAST_RADIUS = mapLayout( + CONTROL_HEIGHTS.sm, + (height) => height / 2 + ACTION_TOAST_INSET, +); const toastEntering = FadeIn.duration(TOAST_FADE_MS); const toastExiting = FadeOut.duration(TOAST_FADE_MS); const ThemedCheckCircle = withUnistyles(CheckCircle2); @@ -136,6 +149,7 @@ export function useToastHost(): { nativeMessage, icon: options?.icon, variant, + layout: options?.layout, durationMs, testID: options?.testID, onDismiss: options?.onDismiss, @@ -163,11 +177,14 @@ export function useToastHost(): { export function ToastViewport({ toast, + persistentToast = null, onDismiss, placement = "app-shell", onBottomCoverageChange, }: { toast: ToastState | null; + /** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */ + persistentToast?: ToastState | null; /** Called with the ID of the toast that timed out. */ onDismiss: (id: number) => void; placement?: ToastViewportPlacement; @@ -232,7 +249,10 @@ export function ToastViewport({ const handleSidebarLayout = useCallback( (event: LayoutChangeEvent) => { - onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET); + const height = event.nativeEvent.layout.height; + if (height > 0) { + onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET); + } }, [onBottomCoverageChange], ); @@ -243,28 +263,41 @@ export function ToastViewport({ const topOffset = placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance; + if (placement === "sidebar") { + return ( + + + + + ); + } + // Keep the bottom anchor and its contents together while the native exit retains the view. const content = toast ? ( - + {content} : content; } +function SidebarToastSlot({ + toast, + onPointerEnter, + onPointerLeave, +}: { + toast: ToastState | null; + onPointerEnter: () => void; + onPointerLeave: () => void; +}) { + if (!toast) return null; + return ( + + + + + + ); +} + function ToastCard({ toast, onPointerEnter, @@ -310,6 +372,7 @@ function ToastCard({ onPointerLeave={onPointerLeave} style={[ styles.toast, + toast.layout === "action" ? styles.toastAction : null, toast.variant === "info" ? styles.toastInfo : null, toast.variant === "warning" ? styles.toastWarning : null, toast.variant === "error" ? styles.toastError : null, @@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({ bottom: SIDEBAR_TOAST_INSET, zIndex: OVERLAY_Z.toast, alignItems: "center", + gap: SIDEBAR_TOAST_INSET, }, surface: { alignSelf: "center", maxWidth: "100%" }, }); @@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({ paddingHorizontal: theme.spacing[3], ...theme.shadow.md, }, + toastAction: { + borderRadius: ACTION_TOAST_RADIUS, + paddingVertical: theme.spacing[1.5], + paddingLeft: theme.spacing[3.5], + paddingRight: theme.spacing[1.5], + }, toastInfo: { borderColor: theme.colors.palette.blue[300], }, diff --git a/packages/app/src/git/worktree-archive-warning.ts b/packages/app/src/git/worktree-archive-warning.ts index 3935eef3cd..1e05f06630 100644 --- a/packages/app/src/git/worktree-archive-warning.ts +++ b/packages/app/src/git/worktree-archive-warning.ts @@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive( destructive: true, }); } + +export async function confirmRiskyBulkWorktreeArchive( + input: { + totalCount: number; + riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[]; + }, + labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS, +): Promise { + const lines: string[] = []; + let singleRisky: WorktreeArchiveConfirmationInput | null = null; + for (const workspace of input.riskyWorkspaces) { + const reasons = buildWorktreeArchiveRiskReasons(workspace, labels); + if (reasons.length === 0) continue; + singleRisky = workspace; + lines.push( + i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", { + workspaceName: workspace.workspaceName, + reason: reasons.join(", "), + }), + ); + } + if (lines.length === 0) { + return true; + } + if (input.totalCount === 1 && singleRisky) { + return await confirmRiskyWorktreeArchive(singleRisky, labels); + } + + return await confirmDialog({ + title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", { + count: input.totalCount, + }), + message: lines.join("\n"), + confirmLabel: labels.confirm, + cancelLabel: labels.cancel, + destructive: true, + }); +} diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 0acd7bbdfb..469998a3d0 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -960,6 +960,8 @@ export const ar: TranslationResources = { }, archiveWarning: { title: 'الأرشيف "{{workspaceName}}"؟', + bulkTitle: "أرشفة {{count}} مساحات عمل؟", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "أرشيف", cancel: "يلغي", uncommittedChanges: "تغييرات غير ملتزم بها", @@ -1369,6 +1371,7 @@ export const ar: TranslationResources = { rename: "إعادة تسمية مساحة العمل", pin: "تثبيت في الأعلى", unpin: "إلغاء التثبيت", + select: "تحديد", archive: "أرشيف", archiveWorkspace: "أرشفة مساحة العمل", hideFromSidebar: "إخفاء من الشريط الجانبي", @@ -1387,6 +1390,10 @@ export const ar: TranslationResources = { submit: "إعادة تسمية", invalidBranchName: "اسم الفرع غير صالح", }, + selection: { + count: "تم تحديد {{count}}", + exit: "إنهاء التحديد", + }, toasts: { workspacePathUnavailable: "مسار Workspace غير متوفر", pathCopied: "تم نسخ المسار", @@ -1394,7 +1401,9 @@ export const ar: TranslationResources = { hostDisconnected: "Host غير متصل", hideFailed: "فشل في إخفاء مساحة العمل", archiveFailed: "فشل في أرشفة مساحة العمل", + archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل", archived: "تمت أرشفة مساحة العمل", + archivedCount: "تمت أرشفة {{count}} مساحات عمل", undoArchive: "تراجع", undoArchiveFailed: "تعذّر التراجع عن الأرشفة", }, diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index a9b5f7ffcc..05c9122ac9 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -971,6 +971,8 @@ export const en = { }, archiveWarning: { title: 'Archive "{{workspaceName}}"?', + bulkTitle: "Archive {{count}} workspaces?", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "Archive", cancel: "Cancel", uncommittedChanges: "Uncommitted changes", @@ -1380,6 +1382,7 @@ export const en = { rename: "Rename workspace", pin: "Pin to top", unpin: "Unpin", + select: "Select", archive: "Archive", archiveWorkspace: "Archive workspace", hideFromSidebar: "Hide from sidebar", @@ -1398,6 +1401,10 @@ export const en = { submit: "Rename", invalidBranchName: "Invalid branch name", }, + selection: { + count: "{{count}} selected", + exit: "Exit selection", + }, toasts: { workspacePathUnavailable: "Workspace path not available", pathCopied: "Path copied", @@ -1405,7 +1412,9 @@ export const en = { hostDisconnected: "Host is not connected", hideFailed: "Failed to hide workspace", archiveFailed: "Failed to archive workspace", + archiveMultipleFailed: "Failed to archive {{count}} workspaces", archived: "Workspace archived", + archivedCount: "{{count}} workspaces archived", undoArchive: "Undo", undoArchiveFailed: "Couldn't undo the archive", }, diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 903bf9b193..ab01b09bcd 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -994,6 +994,8 @@ export const es: TranslationResources = { }, archiveWarning: { title: '¿Archivo "{{workspaceName}}"?', + bulkTitle: "¿Archivar {{count}} espacios de trabajo?", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "Archivo", cancel: "Cancelar", uncommittedChanges: "Cambios no confirmados", @@ -1406,6 +1408,7 @@ export const es: TranslationResources = { rename: "Cambiar nombre del espacio de trabajo", pin: "Anclar arriba", unpin: "Desanclar", + select: "Seleccionar", archive: "Archivo", archiveWorkspace: "Archivar espacio de trabajo", hideFromSidebar: "Ocultar de la barra lateral", @@ -1424,6 +1427,10 @@ export const es: TranslationResources = { submit: "Rebautizar", invalidBranchName: "Nombre de sucursal no válido", }, + selection: { + count: "{{count}} seleccionados", + exit: "Salir de la selección", + }, toasts: { workspacePathUnavailable: "RutaWorkspaceno disponible", pathCopied: "Ruta copiada", @@ -1431,7 +1438,9 @@ export const es: TranslationResources = { hostDisconnected: "Hostno está conectado", hideFailed: "No se pudo ocultar el espacio de trabajo", archiveFailed: "No se pudo archivar el espacio de trabajo", + archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo", archived: "Espacio de trabajo archivado", + archivedCount: "{{count}} espacios de trabajo archivados", undoArchive: "Deshacer", undoArchiveFailed: "No se pudo deshacer el archivado", }, diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 09f2cb71b4..87c1c5bd8f 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -986,6 +986,8 @@ export const fr: TranslationResources = { }, archiveWarning: { title: "Archiver « {{workspaceName}} » ?", + bulkTitle: "Archiver {{count}} espaces de travail ?", + bulkWorkspaceReason: "{{workspaceName}} : {{reason}}", confirm: "Archiver", cancel: "Annuler", uncommittedChanges: "Modifications non commitées", @@ -1399,6 +1401,7 @@ export const fr: TranslationResources = { rename: "Renommer l’espace de travail", pin: "Épingler en haut", unpin: "Désépingler", + select: "Sélectionner", archive: "Archiver", archiveWorkspace: "Archiver l’espace de travail", hideFromSidebar: "Masquer de la barre latérale", @@ -1417,6 +1420,10 @@ export const fr: TranslationResources = { submit: "Renommer", invalidBranchName: "Nom de branche invalide", }, + selection: { + count: "{{count}} sélectionnés", + exit: "Quitter la sélection", + }, toasts: { workspacePathUnavailable: "Chemin de l’espace de travail indisponible", pathCopied: "Chemin copié", @@ -1424,7 +1431,9 @@ export const fr: TranslationResources = { hostDisconnected: "L’hôte n’est pas connecté", hideFailed: "Impossible de masquer l’espace de travail", archiveFailed: "Impossible d’archiver l’espace de travail", + archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail", archived: "Espace de travail archivé", + archivedCount: "{{count}} espaces de travail archivés", undoArchive: "Annuler", undoArchiveFailed: "Impossible d’annuler l’archivage", }, diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 0b9b8f1bc4..b81439ff0d 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -974,6 +974,8 @@ export const ja: TranslationResources = { }, archiveWarning: { title: '"{{workspaceName}}"をアーカイブしますか?', + bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?", + bulkWorkspaceReason: "{{workspaceName}}:{{reason}}", confirm: "アーカイブ", cancel: "キャンセル", uncommittedChanges: "未コミットの変更", @@ -1384,6 +1386,7 @@ export const ja: TranslationResources = { rename: "ワークスペースの名前を変更", pin: "上部に固定", unpin: "固定解除", + select: "選択", archive: "アーカイブ", archiveWorkspace: "ワークスペースをアーカイブ", hideFromSidebar: "サイドバーから非表示", @@ -1402,6 +1405,10 @@ export const ja: TranslationResources = { submit: "名前を変更", invalidBranchName: "無効なブランチ名", }, + selection: { + count: "{{count}}件選択中", + exit: "選択を終了", + }, toasts: { workspacePathUnavailable: "ワークスペースパスが利用できません", pathCopied: "パスをコピーしました", @@ -1409,7 +1416,9 @@ export const ja: TranslationResources = { hostDisconnected: "ホストが接続されていません", hideFailed: "ワークスペースの非表示に失敗しました", archiveFailed: "ワークスペースのアーカイブに失敗しました", + archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました", archived: "ワークスペースをアーカイブしました", + archivedCount: "{{count}}件のワークスペースをアーカイブしました", undoArchive: "元に戻す", undoArchiveFailed: "アーカイブを元に戻せませんでした", }, diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 176ba8c5e1..dac331bd24 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -967,6 +967,8 @@ export const ko: TranslationResources = { }, archiveWarning: { title: '"{{workspaceName}}"를 보관하시겠습니까?', + bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "보관", cancel: "취소", uncommittedChanges: "커밋되지 않은 변경 사항", @@ -1376,6 +1378,7 @@ export const ko: TranslationResources = { rename: "워크스페이스 이름 변경", pin: "상단에 고정", unpin: "고정 해제", + select: "선택", archive: "보관", archiveWorkspace: "워크스페이스 보관", hideFromSidebar: "사이드바에서 숨기기", @@ -1394,6 +1397,10 @@ export const ko: TranslationResources = { submit: "이름 변경", invalidBranchName: "잘못된 브랜치 이름", }, + selection: { + count: "{{count}}개 선택됨", + exit: "선택 종료", + }, toasts: { workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다", pathCopied: "경로가 복사되었습니다", @@ -1401,7 +1408,9 @@ export const ko: TranslationResources = { hostDisconnected: "호스트가 연결되어 있지 않습니다", hideFailed: "워크스페이스를 숨기지 못했습니다", archiveFailed: "워크스페이스를 보관하지 못했습니다.", + archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다", archived: "워크스페이스를 보관했습니다", + archivedCount: "워크스페이스 {{count}}개를 보관했습니다", undoArchive: "실행 취소", undoArchiveFailed: "보관을 취소하지 못했습니다", }, diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 23862bd4df..9957f44dc9 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -984,6 +984,8 @@ export const ptBR: TranslationResources = { }, archiveWarning: { title: 'Arquivar "{{workspaceName}}"?', + bulkTitle: "Arquivar {{count}} workspaces?", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "Arquivar", cancel: "Cancelar", uncommittedChanges: "Alterações sem commit", @@ -1396,6 +1398,7 @@ export const ptBR: TranslationResources = { rename: "Renomear workspace", pin: "Fixar no topo", unpin: "Desafixar", + select: "Selecionar", archive: "Arquivar", archiveWorkspace: "Arquivar workspace", hideFromSidebar: "Ocultar da barra lateral", @@ -1414,6 +1417,10 @@ export const ptBR: TranslationResources = { submit: "Renomear", invalidBranchName: "Nome de branch inválido", }, + selection: { + count: "{{count}} selecionados", + exit: "Sair da seleção", + }, toasts: { workspacePathUnavailable: "Caminho do workspace indisponível", pathCopied: "Caminho copiado", @@ -1421,7 +1428,9 @@ export const ptBR: TranslationResources = { hostDisconnected: "Host não está conectado", hideFailed: "Falha ao ocultar workspace", archiveFailed: "Falha ao arquivar workspace", + archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces", archived: "Workspace arquivado", + archivedCount: "{{count}} workspaces arquivados", undoArchive: "Desfazer", undoArchiveFailed: "Não foi possível desfazer o arquivamento", }, diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 0dd150c59c..f4bdb2e015 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -979,6 +979,8 @@ export const ru: TranslationResources = { }, archiveWarning: { title: "Архивировать «{{workspaceName}}»?", + bulkTitle: "Архивировать рабочие пространства ({{count}})?", + bulkWorkspaceReason: "{{workspaceName}}: {{reason}}", confirm: "Архивировать", cancel: "Отмена", uncommittedChanges: "Незафиксированные изменения", @@ -1389,6 +1391,7 @@ export const ru: TranslationResources = { rename: "Переименовать рабочее пространство", pin: "Закрепить вверху", unpin: "Открепить", + select: "Выбрать", archive: "Архивировать", archiveWorkspace: "Архивировать рабочее пространство", hideFromSidebar: "Скрыть на боковой панели", @@ -1407,6 +1410,10 @@ export const ru: TranslationResources = { submit: "Переименовать", invalidBranchName: "Недопустимое имя ветки", }, + selection: { + count: "Выбрано: {{count}}", + exit: "Выйти из выбора", + }, toasts: { workspacePathUnavailable: "Путь к рабочему пространству недоступен", pathCopied: "Путь скопирован", @@ -1414,7 +1421,9 @@ export const ru: TranslationResources = { hostDisconnected: "Хост не подключён", hideFailed: "Не удалось скрыть рабочее пространство", archiveFailed: "Не удалось архивировать рабочее пространство", + archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})", archived: "Рабочее пространство архивировано", + archivedCount: "Архивировано рабочих пространств: {{count}}", undoArchive: "Отменить", undoArchiveFailed: "Не удалось отменить архивацию", }, diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 2a3aa4ccf5..e6d39c0dc4 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -952,6 +952,8 @@ export const zhCN: TranslationResources = { }, archiveWarning: { title: "归档「{{workspaceName}}」?", + bulkTitle: "归档 {{count}} 个工作区?", + bulkWorkspaceReason: "{{workspaceName}}:{{reason}}", confirm: "归档", cancel: "取消", uncommittedChanges: "未 commit 的变更", @@ -1359,6 +1361,7 @@ export const zhCN: TranslationResources = { rename: "重命名 workspace", pin: "置顶", unpin: "取消置顶", + select: "选择", archive: "归档", archiveWorkspace: "归档工作区", hideFromSidebar: "从侧边栏隐藏", @@ -1376,6 +1379,10 @@ export const zhCN: TranslationResources = { submit: "重命名", invalidBranchName: "无效的分支名称", }, + selection: { + count: "已选 {{count}} 项", + exit: "退出选择", + }, toasts: { workspacePathUnavailable: "Workspace 路径不可用", pathCopied: "路径已复制", @@ -1383,7 +1390,9 @@ export const zhCN: TranslationResources = { hostDisconnected: "Host 未连接", hideFailed: "隐藏 workspace 失败", archiveFailed: "归档工作区失败", + archiveMultipleFailed: "归档 {{count}} 个工作区失败", archived: "工作区已归档", + archivedCount: "已归档 {{count}} 个工作区", undoArchive: "撤销", undoArchiveFailed: "无法撤销归档", }, diff --git a/packages/app/src/keyboard/index.ts b/packages/app/src/keyboard/index.ts index 316e339e5d..5c75e2c1bc 100644 --- a/packages/app/src/keyboard/index.ts +++ b/packages/app/src/keyboard/index.ts @@ -14,3 +14,4 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware"; export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions"; export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser"; export { useHardwareKeyboardPresent } from "./availability"; +export { isShiftKeyDown } from "./internal/shift-modifier"; diff --git a/packages/app/src/keyboard/internal/shift-modifier.ts b/packages/app/src/keyboard/internal/shift-modifier.ts new file mode 100644 index 0000000000..028a5666e6 --- /dev/null +++ b/packages/app/src/keyboard/internal/shift-modifier.ts @@ -0,0 +1,51 @@ +export interface ShiftModifierKeyEvent { + key: string; + code?: string; + shiftKey: boolean; +} + +export interface ShiftModifierTracker { + isDown(): boolean; + handleKeyDown(event: ShiftModifierKeyEvent): void; + handleKeyUp(event: ShiftModifierKeyEvent): void; + reset(): void; +} + +/** + * Tracks whether a physical Shift key is currently held across DOM and native + * hardware keyboard streams so touch/pointer press handlers that omit + * `shiftKey` (native GestureResponderEvent, touch-synthesized clicks) can still + * observe Shift+tap and Shift+click. + */ +export function createShiftModifierTracker(): ShiftModifierTracker { + const pressedCodes = new Set(); + return { + isDown: () => pressedCodes.size > 0, + handleKeyDown(event) { + if (event.key === "Shift") { + pressedCodes.add(event.code || "Shift"); + } else if (!event.shiftKey && pressedCodes.size > 0) { + pressedCodes.clear(); + } + }, + handleKeyUp(event) { + if (event.key === "Shift") { + pressedCodes.delete(event.code || "Shift"); + if (!event.shiftKey) { + pressedCodes.clear(); + } + } else if (!event.shiftKey && pressedCodes.size > 0) { + pressedCodes.clear(); + } + }, + reset() { + pressedCodes.clear(); + }, + }; +} + +export const shiftModifier = createShiftModifierTracker(); + +export function isShiftKeyDown(): boolean { + return shiftModifier.isDown(); +} diff --git a/packages/app/src/keyboard/internal/sources/index.ts b/packages/app/src/keyboard/internal/sources/index.ts index 570251a083..6202dcf618 100644 --- a/packages/app/src/keyboard/internal/sources/index.ts +++ b/packages/app/src/keyboard/internal/sources/index.ts @@ -1,3 +1,4 @@ +import { AppState } from "react-native"; import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract"; import { setHardwareKeyboardClaimedShortcuts, @@ -7,6 +8,14 @@ import { import { createHardwareKeyboardSource } from "./native"; const hardwareKeyboard = createHardwareKeyboardSource({ subscribe: subscribeHardwareKeyboard, + subscribeBlur: (onBlur) => { + const subscription = AppState.addEventListener("change", (nextState) => { + if (nextState !== "active") { + onBlur(); + } + }); + return () => subscription.remove(); + }, setOverlayKeys: setHardwareKeyboardOverlayKeys, setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts, }); diff --git a/packages/app/src/keyboard/internal/sources/native.ts b/packages/app/src/keyboard/internal/sources/native.ts index 9d76abe0a6..c011843494 100644 --- a/packages/app/src/keyboard/internal/sources/native.ts +++ b/packages/app/src/keyboard/internal/sources/native.ts @@ -9,6 +9,7 @@ import { import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeySource { subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void; + subscribeBlur?(handler: () => void): () => void; setOverlayKeys(keys: readonly string[]): void; setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; } @@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) { nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), ); }); + const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {}); return () => { + unsubscribeBlur(); unsubscribeHardware(); unsubscribeFocus(); unsubscribeCommandCenter(); diff --git a/packages/app/src/keyboard/native-shortcuts.test.ts b/packages/app/src/keyboard/native-shortcuts.test.ts index d4c4edc24f..b5f67f639a 100644 --- a/packages/app/src/keyboard/native-shortcuts.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.test.ts @@ -269,4 +269,80 @@ describe("hardware source adapter", () => { expect(claimed).toEqual([]); releaseFinal(); }); + + it("forwards native blur events and unsubscribes on detach", async () => { + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); + const blurListeners = new Set<() => void>(); + let blurCalls = 0; + const detach = createHardwareKeyboardSource({ + subscribe: () => () => {}, + subscribeBlur(listener) { + blurListeners.add(listener); + return () => { + blurListeners.delete(listener); + }; + }, + setOverlayKeys() {}, + setClaimedShortcuts() {}, + }).attach({ + keyDown() {}, + keyUp() {}, + blur() { + blurCalls += 1; + }, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }); + for (const listener of blurListeners) listener(); + expect(blurCalls).toBe(1); + detach(); + expect(blurListeners.size).toBe(0); + }); +}); + +describe("shift modifier tracking", () => { + it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => { + const { createShiftModifierTracker } = await import("./internal/shift-modifier"); + const tracker = createShiftModifierTracker(); + expect(tracker.isDown()).toBe(false); + + tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true }); + expect(tracker.isDown()).toBe(true); + + tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true }); + tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true }); + expect(tracker.isDown()).toBe(true); + + tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false }); + expect(tracker.isDown()).toBe(false); + + // Self-heals if a Shift key-up was swallowed by the OS. + tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true }); + expect(tracker.isDown()).toBe(true); + tracker.handleKeyDown({ key: "a", code: "KeyA", shiftKey: false }); + expect(tracker.isDown()).toBe(false); + + // Clears on blur / backgrounding. + tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true }); + expect(tracker.isDown()).toBe(true); + tracker.reset(); + expect(tracker.isDown()).toBe(false); + }); + + it("exposes live hardware Shift state through isShiftKeyDown", async () => { + const { shiftModifier } = await import("./internal/shift-modifier"); + const { isShiftKeyDown } = await import("./index"); + try { + shiftModifier.reset(); + expect(isShiftKeyDown()).toBe(false); + + shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true }); + expect(isShiftKeyDown()).toBe(true); + + shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false }); + expect(isShiftKeyDown()).toBe(false); + } finally { + shiftModifier.reset(); + } + }); }); diff --git a/packages/app/src/keyboard/use-shortcuts.ts b/packages/app/src/keyboard/use-shortcuts.ts index 700bfb7dc0..de827722ef 100644 --- a/packages/app/src/keyboard/use-shortcuts.ts +++ b/packages/app/src/keyboard/use-shortcuts.ts @@ -1,6 +1,7 @@ import { usesDesktopBindings } from "./internal/conventions"; import { createKeyboardPipeline } from "./internal/pipeline"; import { overlays } from "./internal/overlays"; +import { shiftModifier } from "./internal/shift-modifier"; import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources"; import type { KeyboardSourceInput } from "./internal/sources/contract"; import type { KeyboardInputEvent } from "./internal/overlays"; @@ -249,19 +250,30 @@ export function useKeyboardShortcuts({ [getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged], ); + const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => { + shiftModifier.handleKeyDown(input.event); + return pipeline.keyDown(input); + }); + const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => { + shiftModifier.handleKeyUp(event); const key = event.key ?? ""; if (key === badgeModifierKey) { setBadgeModifierDown(false); } }); + const handleBlur = useStableEvent(() => { + shiftModifier.reset(); + resetModifiers(); + }); + useEffect(() => { if (!enabled) return; const detach = attachKeyboardSources({ - keyDown: pipeline.keyDown, + keyDown: handleKeyDown, keyUp: handleKeyUp, - blur: resetModifiers, + blur: handleBlur, commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen, subscribeCommandCenter: (listener) => useKeyboardShortcutsStore.subscribe((state, previous) => { @@ -270,7 +282,8 @@ export function useKeyboardShortcuts({ }); return () => { detach(); + shiftModifier.reset(); pipeline.dispose(); }; - }, [enabled, pipeline, handleKeyUp, resetModifiers]); + }, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]); } diff --git a/packages/app/src/sidebar-selection/index.ts b/packages/app/src/sidebar-selection/index.ts new file mode 100644 index 0000000000..9113f36a72 --- /dev/null +++ b/packages/app/src/sidebar-selection/index.ts @@ -0,0 +1,8 @@ +export { isShiftPressEvent } from "./internal/selection-state"; +export { + registerSidebarVisibleWorkspaceKeysReader, + useIsSidebarSelectionMode, + useIsWorkspaceBulkSelected, + useSidebarSelectionStore, +} from "./internal/selection-store"; +export { SidebarSelectionHost } from "./internal/sidebar-selection-host"; diff --git a/packages/app/src/sidebar-selection/internal/archive-selected.test.ts b/packages/app/src/sidebar-selection/internal/archive-selected.test.ts new file mode 100644 index 0000000000..23c9b1a9d9 --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/archive-selected.test.ts @@ -0,0 +1,280 @@ +import { describe, expect, it, vi } from "vitest"; +import type { ToastApi } from "@/components/toast-host"; +import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"; +import { + archiveSelectedWorkspaces, + type BulkArchiveClient, + type BulkArchiveWorkspacesDeps, +} from "./archive-selected"; + +function makeEntry( + overrides: Partial & { workspaceId: string }, +): SidebarWorkspaceEntry { + return { + workspaceKey: `srv:${overrides.workspaceId}`, + serverId: "srv", + projectViewKey: "prj-view", + projectName: "Repo", + projectRootPath: "/repo", + workspaceDirectory: `/repo/${overrides.workspaceId}`, + workspaceDirectoryLabel: overrides.workspaceId, + projectKind: "git", + workspaceKind: "local_checkout", + name: overrides.workspaceId, + title: null, + currentBranch: overrides.workspaceId, + statusBucket: "done", + statusEnteredAt: null, + archivingAt: null, + diffStat: null, + prHint: null, + pinnedAt: null, + background: false, + labels: [], + scripts: [], + hasRunningScripts: false, + archiveHasUncommittedChanges: null, + archiveUnpushedCommitCount: null, + ...overrides, + }; +} + +function createFakeToast(): { toast: ToastApi; errors: string[] } { + const errors: string[] = []; + return { + errors, + toast: { + show: () => () => {}, + copied: () => {}, + error: (message) => errors.push(message), + }, + }; +} + +function createFakeClient(): BulkArchiveClient { + return { + archiveWorkspace: async () => ({ error: null }), + undoWorkspaceArchive: async () => {}, + getCheckoutStatus: async () => + ({ + isGit: true, + isDirty: false, + aheadOfOrigin: 0, + }) as Awaited>, + }; +} + +describe("archiveSelectedWorkspaces", () => { + it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => { + const order: string[] = []; + const client = createFakeClient(); + const { toast, errors } = createFakeToast(); + const confirmRiskyBulkArchive = vi.fn(async () => true); + const deps: BulkArchiveWorkspacesDeps = { + getClient: () => client, + supportsUndo: () => true, + readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }), + confirmRiskyBulkArchive, + archiveWithUndo: async (input) => { + order.push( + `archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`, + ); + return { failures: [], showPartialFailure: () => false }; + }, + archiveWithoutUndo: async () => "archived", + hasActiveUndo: () => false, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: (workspace) => { + order.push(`redirect:${workspace.workspaceId}`); + }, + }; + + const ok = await archiveSelectedWorkspaces({ + workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })], + toast, + onArchiveStarted: () => order.push("exit-selection"), + deps, + }); + + expect(ok).toBe(true); + expect(errors).toEqual([]); + expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]); + expect(confirmRiskyBulkArchive).not.toHaveBeenCalled(); + }); + + it("keeps select mode open when the user cancels a risky worktree confirmation", async () => { + const client = createFakeClient(); + const { toast, errors } = createFakeToast(); + const onArchiveStarted = vi.fn(); + const archiveWithUndo = vi.fn(async () => ({ + failures: [], + showPartialFailure: () => false, + })); + const confirmRiskyBulkArchive = vi.fn(async () => false); + + const ok = await archiveSelectedWorkspaces({ + workspaces: [ + makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }), + makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }), + ], + toast, + onArchiveStarted, + deps: { + getClient: () => client, + supportsUndo: () => true, + readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }), + confirmRiskyBulkArchive, + archiveWithUndo, + archiveWithoutUndo: async () => "archived", + hasActiveUndo: () => false, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: vi.fn(), + }, + }); + + expect(ok).toBe(false); + expect(errors).toEqual([]); + expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({ + totalCount: 2, + riskyWorkspaces: [ + { + workspaceName: "feat-wip", + diffStat: null, + isDirty: true, + aheadOfOrigin: 1, + }, + ], + }); + expect(onArchiveStarted).not.toHaveBeenCalled(); + expect(archiveWithUndo).not.toHaveBeenCalled(); + }); + + it("shows a disconnect error and aborts before archiving when any host is offline", async () => { + const { toast, errors } = createFakeToast(); + const onArchiveStarted = vi.fn(); + + const ok = await archiveSelectedWorkspaces({ + workspaces: [makeEntry({ workspaceId: "w1" })], + toast, + onArchiveStarted, + deps: { + getClient: () => null, + supportsUndo: () => true, + readWorktreeRisk: vi.fn(), + confirmRiskyBulkArchive: vi.fn(), + archiveWithUndo: vi.fn(), + archiveWithoutUndo: vi.fn(), + hasActiveUndo: () => false, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: vi.fn(), + }, + }); + + expect(ok).toBe(false); + expect(errors).toEqual(["Host is not connected"]); + expect(onArchiveStarted).not.toHaveBeenCalled(); + }); + + it("reports multi-workspace failures when more than one archive fails", async () => { + const client = createFakeClient(); + const { toast, errors } = createFakeToast(); + + const ok = await archiveSelectedWorkspaces({ + workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })], + toast, + onArchiveStarted: vi.fn(), + deps: { + getClient: () => client, + supportsUndo: () => true, + readWorktreeRisk: vi.fn(), + confirmRiskyBulkArchive: vi.fn(), + archiveWithUndo: async () => ({ + failures: [ + { workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") }, + { workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") }, + ], + showPartialFailure: () => false, + }), + archiveWithoutUndo: vi.fn(), + hasActiveUndo: () => false, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: vi.fn(), + }, + }); + + expect(ok).toBe(false); + expect(errors).toEqual(["Failed to archive 2 workspaces"]); + }); + + it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => { + const client = createFakeClient(); + const { toast, errors } = createFakeToast(); + const partialErrors: string[] = []; + + const ok = await archiveSelectedWorkspaces({ + workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })], + toast, + onArchiveStarted: vi.fn(), + deps: { + getClient: () => client, + supportsUndo: () => true, + readWorktreeRisk: vi.fn(), + confirmRiskyBulkArchive: vi.fn(), + archiveWithUndo: async () => ({ + failures: [ + { workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") }, + ], + showPartialFailure: (message) => { + partialErrors.push(message); + return true; + }, + }), + archiveWithoutUndo: vi.fn(), + hasActiveUndo: () => false, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: vi.fn(), + }, + }); + + expect(ok).toBe(false); + expect(partialErrors).toEqual(["Host offline"]); + expect(errors).toEqual([]); + }); + + it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => { + const client = createFakeClient(); + const sidebar = createFakeToast(); + const app = createFakeToast(); + + const ok = await archiveSelectedWorkspaces({ + workspaces: [makeEntry({ workspaceId: "w1" })], + toast: sidebar.toast, + fallbackErrorToast: app.toast, + onArchiveStarted: vi.fn(), + deps: { + getClient: () => client, + supportsUndo: () => true, + readWorktreeRisk: vi.fn(), + confirmRiskyBulkArchive: vi.fn(), + archiveWithUndo: async () => ({ + failures: [ + { + workspace: { serverId: "srv", workspaceId: "w1" }, + error: new Error("Host timed out"), + }, + ], + // This batch's own undo window was closed when a newer batch superseded it. + showPartialFailure: () => false, + }), + archiveWithoutUndo: vi.fn(), + hasActiveUndo: () => true, + purgeWorkspaceState: vi.fn(), + redirectActiveWorkspace: vi.fn(), + }, + }); + + expect(ok).toBe(false); + expect(sidebar.errors).toEqual([]); + expect(app.errors).toEqual(["Host timed out"]); + }); +}); diff --git a/packages/app/src/sidebar-selection/internal/archive-selected.ts b/packages/app/src/sidebar-selection/internal/archive-selected.ts new file mode 100644 index 0000000000..ede57574c1 --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/archive-selected.ts @@ -0,0 +1,197 @@ +import type { ToastApi } from "@/components/toast-host"; +import type { CheckoutStatusClient } from "@/git/checkout-status-cache"; +import { + confirmRiskyBulkWorktreeArchive, + readWorktreeArchiveRisk, + type WorktreeArchiveConfirmationInput, +} from "@/git/worktree-archive-warning"; +import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"; +import { i18n } from "@/i18n/i18next"; +import { getHostRuntimeStore } from "@/runtime/host-runtime"; +import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store"; +import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; +import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect"; +import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; +import { + archiveWorkspacesWithUndo, + hasUndoableWorkspaceArchive, + supportsWorkspaceArchiveUndo, + type UndoableWorkspaceArchiveClient, +} from "@/workspace/archive-undo"; +import { + archiveWorkspaceOptimistically, + type WorkspaceArchiveTarget, +} from "@/workspace/workspace-archive"; + +export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {} + +export interface BulkArchiveWorkspacesDeps { + getClient: (serverId: string) => BulkArchiveClient | null; + supportsUndo: (serverId: string) => boolean; + readWorktreeRisk: typeof readWorktreeArchiveRisk; + confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive; + archiveWithUndo: typeof archiveWorkspacesWithUndo; + archiveWithoutUndo: typeof archiveWorkspaceOptimistically; + hasActiveUndo: () => boolean; + purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void; + redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void; +} + +function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void { + const workspaceKey = buildWorkspaceTabPersistenceKey(workspace); + if (workspaceKey) { + useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey); + } +} + +export function createDefaultBulkArchiveDeps( + getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null, +): BulkArchiveWorkspacesDeps { + return { + getClient: (serverId) => getHostRuntimeStore().getClient(serverId), + supportsUndo: supportsWorkspaceArchiveUndo, + readWorktreeRisk: readWorktreeArchiveRisk, + confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive, + archiveWithUndo: archiveWorkspacesWithUndo, + archiveWithoutUndo: archiveWorkspaceOptimistically, + hasActiveUndo: hasUndoableWorkspaceArchive, + purgeWorkspaceState: defaultPurgeWorkspaceState, + redirectActiveWorkspace: (workspace) => { + redirectIfArchivingActiveWorkspace({ + serverId: workspace.serverId, + workspaceId: workspace.workspaceId, + activeWorkspaceSelection: getActiveWorkspaceSelection(), + }); + }, + }; +} + +function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string { + if (failures.length > 1) { + return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length }); + } + const error = failures[0]?.error; + return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"); +} + +interface ResolvedWorkspaceTarget { + entry: SidebarWorkspaceEntry; + client: BulkArchiveClient; +} + +export async function archiveSelectedWorkspaces(input: { + workspaces: readonly SidebarWorkspaceEntry[]; + toast: ToastApi; + fallbackErrorToast?: ToastApi; + onArchiveStarted: () => void; + deps: BulkArchiveWorkspacesDeps; +}): Promise { + const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input; + if (workspaces.length === 0) return false; + + const resolved: ResolvedWorkspaceTarget[] = []; + for (const entry of workspaces) { + const client = deps.getClient(entry.serverId); + if (!client) { + toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected")); + return false; + } + resolved.push({ entry, client }); + } + + const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = []; + const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree"); + if (worktrees.length > 0) { + try { + const risks = await Promise.all( + worktrees.map(async ({ entry, client }) => { + const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory); + return { + workspaceName: entry.name, + diffStat: entry.diffStat, + isDirty: risk.isDirty, + aheadOfOrigin: risk.aheadOfOrigin, + } satisfies WorktreeArchiveConfirmationInput; + }), + ); + riskyWorkspaces.push(...risks); + } catch (error) { + toast.error( + error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"), + ); + return false; + } + } + + if (riskyWorkspaces.length > 0) { + const confirmed = await deps.confirmRiskyBulkArchive({ + totalCount: resolved.length, + riskyWorkspaces, + }); + if (!confirmed) { + return false; + } + } + + // Redirect before optimistic removal hides the active workspace from the session store. + for (const { entry } of resolved) { + deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId }); + } + + onArchiveStarted(); + + const undoable: ResolvedWorkspaceTarget[] = []; + const legacy: ResolvedWorkspaceTarget[] = []; + for (const item of resolved) { + if (deps.supportsUndo(item.entry.serverId)) { + undoable.push(item); + } else { + legacy.push(item); + } + } + + const failures: Array<{ error: unknown }> = []; + let showPartialFailure: (message: string) => boolean = () => false; + + await Promise.all([ + undoable.length > 0 + ? (async () => { + const result = await deps.archiveWithUndo({ + entries: undoable.map(({ entry, client }) => { + const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId }; + return { + client, + workspace, + onArchiveCommitted: () => deps.purgeWorkspaceState(workspace), + }; + }), + toast, + }); + failures.push(...result.failures); + showPartialFailure = result.showPartialFailure; + })() + : Promise.resolve(), + // COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06. + ...legacy.map(async ({ entry, client }) => { + const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId }; + try { + await deps.archiveWithoutUndo({ client, workspace }); + deps.purgeWorkspaceState(workspace); + } catch (error) { + failures.push({ error }); + } + }), + ]); + + if (failures.length > 0) { + const errorMessage = formatArchiveFailureMessage(failures); + if (!showPartialFailure(errorMessage)) { + // If a newer batch now owns the sidebar Undo toast, surface this older failure on the + // app-level toast instead of displacing the active Undo window and purging its layouts. + const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast; + errorToast.error(errorMessage); + } + } + + return failures.length === 0; +} diff --git a/packages/app/src/sidebar-selection/internal/selection-state.test.ts b/packages/app/src/sidebar-selection/internal/selection-state.test.ts new file mode 100644 index 0000000000..dfecb57af1 --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/selection-state.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { + enterWorkspaceSelection, + exitWorkspaceSelection, + INITIAL_WORKSPACE_SELECTION_STATE, + isShiftPressEvent, + reconcileWorkspaceSelection, + selectWorkspaceRange, + toggleWorkspaceSelection, +} from "./selection-state"; + +describe("sidebar workspace selection state", () => { + it("enters selection with the clicked workspace as anchor", () => { + const state = enterWorkspaceSelection("ws-2"); + expect({ + active: state.active, + selected: [...state.selectedKeys], + anchorKey: state.anchorKey, + }).toEqual({ + active: true, + selected: ["ws-2"], + anchorKey: "ws-2", + }); + }); + + it("toggles workspaces on plain click without needing Shift", () => { + let state = enterWorkspaceSelection("ws-1"); + state = toggleWorkspaceSelection(state, "ws-3"); + expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]); + expect(state.anchorKey).toBe("ws-3"); + + state = toggleWorkspaceSelection(state, "ws-1"); + expect([...state.selectedKeys]).toEqual(["ws-3"]); + expect(state.anchorKey).toBe("ws-1"); + + state = toggleWorkspaceSelection(state, "ws-3"); + expect(state.active).toBe(true); + expect([...state.selectedKeys]).toEqual([]); + }); + + it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => { + const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"]; + let state = enterWorkspaceSelection("ws-1"); + state = toggleWorkspaceSelection(state, "ws-3"); + + state = selectWorkspaceRange(state, "ws-5", visible); + expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]); + expect(state.anchorKey).toBe("ws-3"); + + const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible); + expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]); + }); + + it("falls back to adding the target when the anchor is no longer in the visible list", () => { + const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [ + "ws-1", + "ws-2", + ]); + expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]); + expect(state.anchorKey).toBe("ws-2"); + }); + + it("reconciles removed workspaces and clears a missing anchor", () => { + let state = enterWorkspaceSelection("ws-1"); + state = toggleWorkspaceSelection(state, "ws-2"); + const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"])); + expect({ + active: reconciled.active, + selected: [...reconciled.selectedKeys], + anchorKey: reconciled.anchorKey, + }).toEqual({ + active: true, + selected: ["ws-1"], + anchorKey: null, + }); + }); + + it("resets completely on exit", () => { + expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE); + }); + + it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => { + expect(isShiftPressEvent({ shiftKey: true })).toBe(true); + expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true); + expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false); + expect(isShiftPressEvent(null)).toBe(false); + + // Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state. + const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } }; + expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false); + expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true); + }); +}); diff --git a/packages/app/src/sidebar-selection/internal/selection-state.ts b/packages/app/src/sidebar-selection/internal/selection-state.ts new file mode 100644 index 0000000000..a77311adaa --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/selection-state.ts @@ -0,0 +1,129 @@ +import { isShiftKeyDown } from "@/keyboard"; + +export interface WorkspaceSelectionState { + active: boolean; + selectedKeys: ReadonlySet; + anchorKey: string | null; +} + +const EMPTY_KEYS: ReadonlySet = new Set(); + +export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = { + active: false, + selectedKeys: EMPTY_KEYS, + anchorKey: null, +}; + +export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState { + return { + active: true, + selectedKeys: new Set([workspaceKey]), + anchorKey: workspaceKey, + }; +} + +export function toggleWorkspaceSelection( + state: WorkspaceSelectionState, + workspaceKey: string, +): WorkspaceSelectionState { + if (!state.active) { + return enterWorkspaceSelection(workspaceKey); + } + const next = new Set(state.selectedKeys); + if (!next.delete(workspaceKey)) { + next.add(workspaceKey); + } + return { + active: true, + selectedKeys: next, + anchorKey: workspaceKey, + }; +} + +export function selectWorkspaceRange( + state: WorkspaceSelectionState, + targetKey: string, + orderedVisibleKeys: readonly string[], +): WorkspaceSelectionState { + if (!state.active) { + return enterWorkspaceSelection(targetKey); + } + if (!state.anchorKey) { + const next = new Set(state.selectedKeys); + next.add(targetKey); + return { active: true, selectedKeys: next, anchorKey: targetKey }; + } + + const anchorIndex = orderedVisibleKeys.indexOf(state.anchorKey); + const targetIndex = orderedVisibleKeys.indexOf(targetKey); + if (anchorIndex < 0 || targetIndex < 0) { + const next = new Set(state.selectedKeys); + next.add(targetKey); + return { active: true, selectedKeys: next, anchorKey: targetKey }; + } + + const start = Math.min(anchorIndex, targetIndex); + const end = Math.max(anchorIndex, targetIndex); + const next = new Set(state.selectedKeys); + for (let index = start; index <= end; index += 1) { + const key = orderedVisibleKeys[index]; + if (key !== undefined) { + next.add(key); + } + } + return { + active: true, + selectedKeys: next, + anchorKey: state.anchorKey, + }; +} + +export function reconcileWorkspaceSelection( + state: WorkspaceSelectionState, + availableKeys: ReadonlySet, +): WorkspaceSelectionState { + if (!state.active) return state; + + let changed = false; + const next = new Set(); + for (const key of state.selectedKeys) { + if (availableKeys.has(key)) { + next.add(key); + } else { + changed = true; + } + } + + const nextAnchor = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null; + if (!changed && nextAnchor === state.anchorKey) { + return state; + } + + return { + active: true, + selectedKeys: changed ? next : state.selectedKeys, + anchorKey: nextAnchor, + }; +} + +export function exitWorkspaceSelection(): WorkspaceSelectionState { + return INITIAL_WORKSPACE_SELECTION_STATE; +} + +export function isShiftPressEvent( + event: unknown, + isHardwareShiftDown: () => boolean = isShiftKeyDown, +): boolean { + if (typeof event === "object" && event !== null) { + if (Reflect.get(event, "shiftKey") === true) return true; + const nativeEvent = Reflect.get(event, "nativeEvent"); + if ( + typeof nativeEvent === "object" && + nativeEvent !== null && + Reflect.get(nativeEvent, "shiftKey") === true + ) { + return true; + } + } + return isHardwareShiftDown(); +} diff --git a/packages/app/src/sidebar-selection/internal/selection-store.ts b/packages/app/src/sidebar-selection/internal/selection-store.ts new file mode 100644 index 0000000000..399440adcd --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/selection-store.ts @@ -0,0 +1,82 @@ +import { create } from "zustand"; +import { + enterWorkspaceSelection, + exitWorkspaceSelection, + INITIAL_WORKSPACE_SELECTION_STATE, + reconcileWorkspaceSelection, + selectWorkspaceRange, + toggleWorkspaceSelection, + type WorkspaceSelectionState, +} from "./selection-state"; + +type VisibleKeysReader = () => readonly string[]; + +let visibleKeysReader: VisibleKeysReader = () => []; + +/** + * Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click + * range selection walks only rows on screen without causing re-renders when the order changes. + */ +export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void { + visibleKeysReader = reader; + return () => { + if (visibleKeysReader === reader) { + visibleKeysReader = () => []; + } + }; +} + +interface SidebarSelectionStoreState extends WorkspaceSelectionState { + isArchiving: boolean; + enter: (workspaceKey: string) => void; + pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void; + reconcile: (availableKeys: ReadonlySet) => void; + setArchiving: (archiving: boolean) => void; + exit: () => void; +} + +export const useSidebarSelectionStore = create((set) => ({ + ...INITIAL_WORKSPACE_SELECTION_STATE, + isArchiving: false, + enter: (workspaceKey) => + set(() => ({ + ...enterWorkspaceSelection(workspaceKey), + isArchiving: false, + })), + pressWorkspace: (workspaceKey, { shiftKey }) => + set((state) => { + if (state.isArchiving) return state; + const next = shiftKey + ? selectWorkspaceRange(state, workspaceKey, visibleKeysReader()) + : toggleWorkspaceSelection(state, workspaceKey); + return next === state ? state : { ...next }; + }), + reconcile: (availableKeys) => + set((state) => { + const next = reconcileWorkspaceSelection(state, availableKeys); + return next === state ? state : { ...next }; + }), + setArchiving: (isArchiving) => set({ isArchiving }), + exit: () => + set((state) => + state.active || state.isArchiving + ? { ...exitWorkspaceSelection(), isArchiving: false } + : state, + ), +})); + +export function useIsSidebarSelectionMode(): boolean { + return useSidebarSelectionStore((state) => state.active); +} + +export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean { + return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey)); +} + +export function useSidebarSelectionCount(): number { + return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0)); +} + +export function useSidebarSelectionArchiving(): boolean { + return useSidebarSelectionStore((state) => state.isArchiving); +} diff --git a/packages/app/src/sidebar-selection/internal/sidebar-selection-host.browser.test.tsx b/packages/app/src/sidebar-selection/internal/sidebar-selection-host.browser.test.tsx new file mode 100644 index 0000000000..4046a4118a --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/sidebar-selection-host.browser.test.tsx @@ -0,0 +1,355 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import React, { act, useCallback } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { I18nextProvider } from "react-i18next"; +import { Text } from "react-native"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { afterEach, describe, expect, it } from "vitest"; +import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region"; +import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu"; +import { ToastProvider, useToast } from "@/contexts/toast-context"; +import type { ToastApi } from "@/components/toast-host"; +import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"; +import { i18n } from "@/i18n/i18next"; +import { dispatchTopOverlayKeyDown } from "@/keyboard"; +import { + KeyboardActionDispatcherProvider, + useKeyboardActionDispatcher, +} from "@/keyboard/keyboard-action-dispatcher-context"; +import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; +import { + isShiftPressEvent, + registerSidebarVisibleWorkspaceKeysReader, + SidebarSelectionHost, + useIsSidebarSelectionMode, + useIsWorkspaceBulkSelected, + useSidebarSelectionStore, +} from "@/sidebar-selection"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +let root: Root | null = null; +let container: HTMLDivElement | null = null; +let releaseVisibleKeys: (() => void) | null = null; + +function makeEntry(id: string): SidebarWorkspaceEntry { + return { + workspaceKey: `srv:${id}`, + workspaceId: id, + serverId: "srv", + projectViewKey: "prj-view", + projectName: "Repo", + projectRootPath: "/repo", + workspaceDirectory: `/repo/${id}`, + workspaceDirectoryLabel: id, + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + title: null, + currentBranch: id, + statusBucket: "done", + statusEnteredAt: null, + archivingAt: null, + diffStat: null, + prHint: null, + pinnedAt: null, + background: false, + labels: [], + scripts: [], + hasRunningScripts: false, + archiveHasUncommittedChanges: null, + archiveUnpushedCommitCount: null, + }; +} + +let capturedDispatcher: ReturnType | null = null; +let capturedSidebarToast: ToastApi | null = null; +let fallbackArchiveCount = 0; + +function FallbackArchiveProbe() { + capturedDispatcher = useKeyboardActionDispatcher(); + useKeyboardActionHandler({ + handlerId: "test-global-workspace-archive-fallback", + actions: ["workspace.archive"], + enabled: true, + priority: 0, + handle: () => { + fallbackArchiveCount += 1; + return true; + }, + }); + return null; +} + +function SidebarToastProbe() { + capturedSidebarToast = useToast(); + return null; +} + +const noop = () => {}; + +function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) { + const isSelectionMode = useIsSidebarSelectionMode(); + const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey); + const handlePress = useCallback( + (event: unknown) => { + const shiftKey = isShiftPressEvent(event); + if (isSelectionMode || shiftKey) { + useSidebarSelectionStore.getState().pressWorkspace(entry.workspaceKey, { shiftKey }); + } + }, + [entry.workspaceKey, isSelectionMode], + ); + return ( + + {entry.name} + + ); +} + +function mountHost(entries: readonly SidebarWorkspaceEntry[]) { + const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry])); + releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() => + entries.map((entry) => entry.workspaceKey), + ); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render( + + + + + + + + + {entries.map((entry) => ( + + ))} + + + + + + + , + ); + }); +} + +afterEach(() => { + capturedDispatcher = null; + capturedSidebarToast = null; + fallbackArchiveCount = 0; + act(() => { + useSidebarSelectionStore.getState().exit(); + }); + releaseVisibleKeys?.(); + releaseVisibleKeys = null; + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +describe("SidebarSelectionHost", () => { + it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => { + mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]); + expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull(); + + // Enter select mode via Shift+click on "a", then plain-click "c" without Shift. + act(() => { + useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true }); + }); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "1 selected", + ); + + act(() => { + useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false }); + }); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "2 selected", + ); + + // Clicking the Exit button leaves select mode and fades the persistent toast out. + const exitButton = document.querySelector( + '[data-testid="workspace-selection-exit"]', + ); + expect(exitButton).not.toBeNull(); + act(() => { + exitButton?.click(); + }); + expect(useSidebarSelectionStore.getState().active).toBe(false); + await expect + .poll(() => document.querySelector('[data-testid="workspace-selection-toast"]')) + .toBeNull(); + + // Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape. + act(() => { + useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true }); + useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: true }); + }); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "3 selected", + ); + + let prevented = false; + act(() => { + const handled = dispatchTopOverlayKeyDown({ + key: "Escape", + code: "Escape", + altKey: false, + ctrlKey: false, + metaKey: false, + shiftKey: false, + repeat: false, + preventDefault: () => { + prevented = true; + }, + stopPropagation: () => {}, + }); + expect(handled).toBe(true); + }); + expect(prevented).toBe(true); + expect(useSidebarSelectionStore.getState().active).toBe(false); + await expect + .poll(() => document.querySelector('[data-testid="workspace-selection-toast"]')) + .toBeNull(); + }); + + it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => { + mountHost([makeEntry("a"), makeEntry("b")]); + + // Outside select mode, the global fallback receives workspace.archive. + act(() => { + expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe( + true, + ); + }); + expect(fallbackArchiveCount).toBe(1); + + // Enter select mode then deselect the only row -> 0 selected. + act(() => { + useSidebarSelectionStore.getState().enter("srv:a"); + useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false }); + }); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "0 selected", + ); + + // The archive shortcut must be absorbed by select mode rather than archiving the open workspace. + act(() => { + expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe( + true, + ); + }); + expect(fallbackArchiveCount).toBe(1); + + // Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned). + act(() => { + useSidebarSelectionStore.getState().enter("srv:a"); + useSidebarSelectionStore.getState().setArchiving(true); + }); + act(() => { + expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe( + true, + ); + expect( + dispatchTopOverlayKeyDown({ + key: "Escape", + code: "Escape", + altKey: false, + ctrlKey: false, + metaKey: false, + shiftKey: false, + repeat: false, + preventDefault: () => {}, + stopPropagation: () => {}, + }), + ).toBe(true); + }); + expect(fallbackArchiveCount).toBe(1); + expect(useSidebarSelectionStore.getState().active).toBe(true); + }); + + it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => { + mountHost([makeEntry("a"), makeEntry("b")]); + + let dismissUndo: (() => void) | undefined; + act(() => { + dismissUndo = capturedSidebarToast?.show("Workspace archived", { + durationMs: 6000, + testID: "workspace-archived-toast", + }); + }); + expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull(); + + act(() => { + useSidebarSelectionStore.getState().enter("srv:a"); + }); + + // Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible. + expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull(); + expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull(); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "1 selected", + ); + expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull(); + expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull(); + + act(() => { + dismissUndo?.(); + }); + }); + + it("toggles focused workspace checkboxes when pressing Space in select mode", () => { + mountHost([makeEntry("a"), makeEntry("b")]); + + act(() => { + useSidebarSelectionStore.getState().enter("srv:a"); + }); + + const rowB = document.querySelector('[data-testid="sidebar-workspace-row-srv:b"]'); + expect(rowB?.getAttribute("role")).toBe("checkbox"); + expect(rowB?.getAttribute("aria-checked")).toBe("false"); + + act(() => { + rowB?.focus(); + rowB?.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }), + ); + rowB?.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }), + ); + }); + expect(rowB?.getAttribute("aria-checked")).toBe("true"); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "2 selected", + ); + + act(() => { + rowB?.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }), + ); + }); + expect(rowB?.getAttribute("aria-checked")).toBe("false"); + expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe( + "1 selected", + ); + }); +}); diff --git a/packages/app/src/sidebar-selection/internal/sidebar-selection-host.tsx b/packages/app/src/sidebar-selection/internal/sidebar-selection-host.tsx new file mode 100644 index 0000000000..2d62e86fc8 --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/sidebar-selection-host.tsx @@ -0,0 +1,157 @@ +import { useCallback, useEffect, useMemo, useRef } from "react"; +import { + useSidebarAppToast, + useSidebarPersistentToast, +} from "@/components/sidebar/sidebar-toast-region"; +import type { ToastState } from "@/components/toast-host"; +import { useToast } from "@/contexts/toast-context"; +import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; +import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"; +import { useOverlayRegistration } from "@/keyboard"; +import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher"; +import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store"; +import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected"; +import { + useIsSidebarSelectionMode, + useSidebarSelectionArchiving, + useSidebarSelectionCount, + useSidebarSelectionStore, +} from "./selection-store"; +import { WorkspaceSelectionToast } from "./workspace-selection-toast"; + +const SELECTION_TOAST_ID = -1; +const ESCAPE_OVERLAY_KEYS = ["Escape"] as const; +const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"]; + +/** + * Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and + * the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`. + */ +export function SidebarSelectionHost({ + active, + workspaceEntriesByKey, +}: { + active: boolean; + workspaceEntriesByKey: ReadonlyMap; +}): null { + const toast = useToast(); + const appToast = useSidebarAppToast(); + const activeWorkspaceSelection = useActiveWorkspaceSelection(); + const selectionMode = useIsSidebarSelectionMode(); + const selectedCount = useSidebarSelectionCount(); + const isArchiving = useSidebarSelectionArchiving(); + + const entriesRef = useRef(workspaceEntriesByKey); + entriesRef.current = workspaceEntriesByKey; + const activeSelectionRef = useRef(activeWorkspaceSelection); + activeSelectionRef.current = activeWorkspaceSelection; + const archiveAttemptRef = useRef(0); + + useEffect(() => { + if (!selectionMode) return; + useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys())); + }, [selectionMode, workspaceEntriesByKey]); + + useEffect(() => { + if (active) return; + const state = useSidebarSelectionStore.getState(); + if (state.active && !state.isArchiving) { + state.exit(); + } + }, [active]); + + const handleExit = useCallback(() => { + const state = useSidebarSelectionStore.getState(); + if (state.isArchiving) return; + state.exit(); + }, []); + + const handleArchiveSelected = useCallback(() => { + const store = useSidebarSelectionStore.getState(); + if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return; + + const entries: SidebarWorkspaceEntry[] = []; + for (const key of store.selectedKeys) { + const entry = entriesRef.current.get(key); + if (entry && entry.archivingAt === null) { + entries.push(entry); + } + } + if (entries.length === 0) { + store.exit(); + return; + } + + const attemptId = archiveAttemptRef.current + 1; + archiveAttemptRef.current = attemptId; + store.setArchiving(true); + void archiveSelectedWorkspaces({ + workspaces: entries, + toast, + fallbackErrorToast: appToast, + onArchiveStarted: () => { + useSidebarSelectionStore.getState().exit(); + }, + deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current), + }).finally(() => { + if (archiveAttemptRef.current !== attemptId) return; + const current = useSidebarSelectionStore.getState(); + if (current.isArchiving) { + current.setArchiving(false); + } + }); + }, [appToast, toast]); + + useOverlayRegistration({ + keys: ESCAPE_OVERLAY_KEYS, + // Keep Escape owned while select mode is active (including during worktree checks) so it + // never falls through to interrupt a running agent in the open workspace; any higher-layer + // confirmation dialog still receives Escape first. + active: selectionMode && active, + layer: 0, + manageFocus: false, + onKeyDown: (event) => { + if (event.key !== "Escape") return false; + event.preventDefault(); + handleExit(); + return true; + }, + }); + + useKeyboardActionHandler({ + handlerId: "sidebar-selection-archive", + actions: WORKSPACE_ARCHIVE_ACTIONS, + // Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it + // at 0 selected or during a worktree check never falls through to archive the open workspace. + enabled: selectionMode && active, + priority: 10, + handle: () => { + handleArchiveSelected(); + return true; + }, + }); + + const persistentToast = useMemo(() => { + if (!selectionMode || !active) return null; + return { + id: SELECTION_TOAST_ID, + content: ( + + ), + nativeMessage: null, + variant: "default", + layout: "action", + durationMs: null, + testID: "workspace-selection-toast", + }; + }, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]); + + useSidebarPersistentToast(persistentToast); + + return null; +} diff --git a/packages/app/src/sidebar-selection/internal/workspace-selection-toast.tsx b/packages/app/src/sidebar-selection/internal/workspace-selection-toast.tsx new file mode 100644 index 0000000000..e9a8a534a1 --- /dev/null +++ b/packages/app/src/sidebar-selection/internal/workspace-selection-toast.tsx @@ -0,0 +1,83 @@ +import { X } from "lucide-react-native"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Button } from "@/components/ui/button"; +import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry"; +import { DensityIcon } from "@/components/ui/density-icon"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; +import type { ShortcutKey } from "@/utils/format-shortcut"; + +const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]]; + +export function WorkspaceSelectionToast({ + selectedCount, + isArchiving, + onArchive, + onExit, +}: { + selectedCount: number; + isArchiving: boolean; + onArchive: () => void; + onExit: () => void; +}) { + const { t } = useTranslation(); + const exitLabel = t("sidebar.workspace.selection.exit"); + + return ( + + + {t("sidebar.workspace.selection.count", { count: selectedCount })} + + + + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + row: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "center", + gap: theme.spacing[3], + }, + message: { + flexShrink: 1, + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + fontWeight: theme.fontWeight.normal, + }, + actions: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1], + }, + // Matches the Archive button's sm pill height so the circular hover fill sits concentrically + // in the action toast's trailing corner. + exitButton: { + width: CONTROL_HEIGHTS.sm, + height: CONTROL_HEIGHTS.sm, + }, +})); diff --git a/packages/app/src/workspace/archive-undo/index.ts b/packages/app/src/workspace/archive-undo/index.ts index c6107367aa..5bd37a0827 100644 --- a/packages/app/src/workspace/archive-undo/index.ts +++ b/packages/app/src/workspace/archive-undo/index.ts @@ -1,7 +1,12 @@ export { archiveWorkspaceWithUndo, + archiveWorkspacesWithUndo, + hasUndoableWorkspaceArchive, undoLatestWorkspaceArchive, type UndoableWorkspaceArchiveClient, + type UndoableWorkspaceArchiveEntryInput, + type WorkspaceArchiveBatchFailure, + type WorkspaceArchiveBatchResult, } from "./internal/undo-window"; export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host"; export { supportsWorkspaceArchiveUndo } from "./internal/capability"; diff --git a/packages/app/src/workspace/archive-undo/internal/undo-window.test.ts b/packages/app/src/workspace/archive-undo/internal/undo-window.test.ts index efa9a539ac..e0664488c4 100644 --- a/packages/app/src/workspace/archive-undo/internal/undo-window.test.ts +++ b/packages/app/src/workspace/archive-undo/internal/undo-window.test.ts @@ -8,6 +8,7 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor import { seedSessionHosts } from "@/test/seed-session"; import { archiveWorkspaceWithUndo, + archiveWorkspacesWithUndo, undoLatestWorkspaceArchive, type UndoableWorkspaceArchiveClient, } from "@/workspace/archive-undo"; @@ -82,6 +83,9 @@ function createToastHost() { get shownTestID() { return shown?.options?.testID ?? null; }, + get shownVariant() { + return shown?.options?.variant ?? null; + }, timeOut: () => shown?.dismiss(), }; } @@ -299,3 +303,166 @@ describe("archiveWorkspaceWithUndo", () => { }).toEqual({ toast: null, undone: false, row: workspace("a") }); }); }); + +describe("archiveWorkspacesWithUndo", () => { + it("hides every workspace in the batch and undoes all of them together", async () => { + const host = createClient(); + const toast = createToastHost(); + const committed: string[] = []; + + const batch = archiveWorkspacesWithUndo({ + entries: [ + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "a" }, + onArchiveCommitted: () => committed.push("a"), + }, + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "b" }, + onArchiveCommitted: () => committed.push("b"), + }, + ], + toast: toast.api, + }); + + expect(storedWorkspace("a")).toBeUndefined(); + expect(storedWorkspace("b")).toBeUndefined(); + expect(toast.shownTestID).toBe("workspace-archived-toast"); + + expect(undoLatestWorkspaceArchive()).toBe(true); + expect({ + a: storedWorkspace("a"), + b: storedWorkspace("b"), + undoA: host.undoRequested("a"), + undoB: host.undoRequested("b"), + toast: toast.shownTestID, + }).toEqual({ + a: workspace("a"), + b: workspace("b"), + undoA: true, + undoB: true, + toast: null, + }); + + host.finishArchive("a", { canceled: true }); + host.finishArchive("b", { canceled: true }); + await expect(batch.then((result) => result.failures)).resolves.toEqual([]); + host.finishUndo("a"); + host.finishUndo("b"); + expect(committed).toEqual([]); + }); + + it("commits every workspace in the batch when the toast times out", async () => { + const host = createClient(); + const toast = createToastHost(); + const committed: string[] = []; + + const batch = archiveWorkspacesWithUndo({ + entries: [ + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "a" }, + onArchiveCommitted: () => committed.push("a"), + }, + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "b" }, + onArchiveCommitted: () => committed.push("b"), + }, + ], + toast: toast.api, + }); + + host.finishArchive("a"); + host.finishArchive("b"); + await expect(batch.then((result) => result.failures)).resolves.toEqual([]); + expect(committed).toEqual([]); + + toast.timeOut(); + expect(committed).toEqual(["a", "b"]); + }); + + it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => { + const host = createClient(); + const toast = createToastHost(); + const committed: string[] = []; + + const batch = archiveWorkspacesWithUndo({ + entries: [ + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "a" }, + onArchiveCommitted: () => committed.push("a"), + }, + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "b" }, + onArchiveCommitted: () => committed.push("b"), + }, + ], + toast: toast.api, + }); + + host.finishArchive("a"); + host.finishArchive("b", { error: "busy" }); + const { failures, showPartialFailure } = await batch; + + expect(failures).toHaveLength(1); + expect(failures[0]?.workspace.workspaceId).toBe("b"); + expect(storedWorkspace("a")).toBeUndefined(); + expect(storedWorkspace("b")).toEqual(workspace("b")); + + // Updating the toast with the partial-failure error must not dismiss Undo or commit "a". + expect(showPartialFailure("busy")).toBe(true); + expect({ + toast: toast.shownTestID, + variant: toast.shownVariant, + committed, + }).toEqual({ + toast: "workspace-archived-toast", + variant: "error", + committed: [], + }); + + expect(undoLatestWorkspaceArchive()).toBe(true); + expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({ + undoA: true, + undoB: false, + }); + expect(committed).toEqual([]); + }); + + it("commits surviving workspaces once a partial-failure undo toast times out", async () => { + const host = createClient(); + const toast = createToastHost(); + const committed: string[] = []; + + const batch = archiveWorkspacesWithUndo({ + entries: [ + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "a" }, + onArchiveCommitted: () => committed.push("a"), + }, + { + client: host.client, + workspace: { serverId: SERVER_ID, workspaceId: "b" }, + onArchiveCommitted: () => committed.push("b"), + }, + ], + toast: toast.api, + }); + + host.finishArchive("a"); + host.finishArchive("b", { error: "busy" }); + const { showPartialFailure } = await batch; + + expect(showPartialFailure("busy")).toBe(true); + expect(committed).toEqual([]); + + toast.timeOut(); + expect(committed).toEqual(["a"]); + expect(undoLatestWorkspaceArchive()).toBe(false); + }); +}); diff --git a/packages/app/src/workspace/archive-undo/internal/undo-window.tsx b/packages/app/src/workspace/archive-undo/internal/undo-window.tsx index 5dc968124e..38dff06b90 100644 --- a/packages/app/src/workspace/archive-undo/internal/undo-window.tsx +++ b/packages/app/src/workspace/archive-undo/internal/undo-window.tsx @@ -17,18 +17,28 @@ export interface UndoableWorkspaceArchiveClient { undoWorkspaceArchive: (workspaceId: string) => Promise; } -interface UndoWindowInput { +export interface UndoableWorkspaceArchiveEntryInput { client: UndoableWorkspaceArchiveClient; workspace: WorkspaceArchiveTarget; - toast: ToastApi; - hidden: WorkspaceDescriptor | null; onArchiveCommitted: () => void; } +interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput { + hidden: WorkspaceDescriptor | null; + archived: boolean; + failed: boolean; + committed: boolean; +} + +interface UndoWindowInput { + entries: UndoWindowEntry[]; + toast: ToastApi; +} + let latest: UndoWindow | null = null; /** - * One archive's chance to be undone. It opens when the row hides and closes when its toast + * One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast * leaves the screen (timeout, replaced by another toast, or undo). * * - `open`: undo is offered. @@ -37,40 +47,78 @@ let latest: UndoWindow | null = null; */ class UndoWindow { phase: "open" | "closed" | "undone" = "open"; - private archived = false; - private readonly dismissToast: DismissToast; + private dismissToast: DismissToast = () => {}; + private toastToken: object | null = null; constructor(private readonly input: UndoWindowInput) { - this.dismissToast = input.toast.show(, { - durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS, - testID: "workspace-archived-toast", - onDismiss: this.close, - }); + this.showToast({ variant: "default" }); } - /** The host finished the archive. It commits now if undo is no longer offered. */ - archiveFinished(): void { - this.archived = true; - if (this.phase === "closed") this.commit(); + private showToast(options: { message?: string; variant: "default" | "error" }): void { + const token = {}; + this.toastToken = token; + const remainingCount = this.input.entries.filter((entry) => !entry.failed).length; + this.dismissToast = this.input.toast.show( + , + { + variant: options.variant, + layout: "action", + durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS, + testID: "workspace-archived-toast", + onDismiss: () => { + // Replacing our own toast in place (for example to surface a partial failure) must not + // close the undo window or purge surviving workspaces. + if (this.toastToken !== token) return; + this.close(); + }, + }, + ); } - /** The archive failed on the host, so there is nothing left to undo. */ - archiveFailed(): void { - this.close(); - this.dismissToast(); + /** + * Surfaces a partial-failure message on the active undo toast without dismissing Undo for the + * workspaces that did archive. Returns false once the window is closed, undone, or superseded. + */ + showPartialFailure(message: string): boolean { + if (this.phase !== "open" || latest !== this) return false; + this.showToast({ message, variant: "error" }); + return true; + } + + /** The host finished archiving this entry. It commits now if undo is no longer offered. */ + entryFinished(entry: UndoWindowEntry): void { + entry.archived = true; + if (this.phase === "closed") this.commitEntry(entry); + } + + /** The archive failed on the host. Dismisses the toast once every entry has failed. */ + entryFailed(entry: UndoWindowEntry): void { + entry.failed = true; + if (this.input.entries.every((item) => item.failed)) { + this.close(); + this.dismissToast(); + } } readonly close = (): void => { if (this.phase !== "open") return; this.phase = "closed"; this.release(); - if (this.archived) this.commit(); + for (const entry of this.input.entries) { + if (entry.archived) this.commitEntry(entry); + } }; /** Commits unless the workspace is back by now, for example restored from another client. */ - private commit(): void { - if (isWorkspaceListed(this.input.workspace)) return; - this.input.onArchiveCommitted(); + private commitEntry(entry: UndoWindowEntry): void { + if (entry.committed || entry.failed) return; + if (isWorkspaceListed(entry.workspace)) return; + entry.committed = true; + entry.onArchiveCommitted(); } readonly undo = (): boolean => { @@ -78,10 +126,19 @@ class UndoWindow { this.phase = "undone"; this.release(); this.dismissToast(); - void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => { - console.warn("[workspace-archive-undo] undo failed", error); - this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed")); - }); + const undoable = this.input.entries.filter((entry) => !entry.failed); + void (async () => { + const results = await Promise.allSettled( + undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)), + ); + const failed = results.filter( + (result): result is PromiseRejectedResult => result.status === "rejected", + ); + if (failed.length > 0) { + console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason); + this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed")); + } + })(); return true; }; @@ -90,6 +147,75 @@ class UndoWindow { } } +export interface WorkspaceArchiveBatchFailure { + workspace: WorkspaceArchiveTarget; + error: unknown; +} + +export interface WorkspaceArchiveBatchResult { + failures: WorkspaceArchiveBatchFailure[]; + /** + * Updates this batch's live undo toast to show a partial-failure error while keeping Undo active + * for the workspaces that succeeded. Returns false if the undo window is no longer open. + */ + showPartialFailure: (message: string) => boolean; +} + +/** + * Archives one or more workspaces together and offers one undo until the toast goes away. + * + * `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no + * longer be undone, and only if the workspace is still gone then. Returns failures for any + * workspace whose archive failed while not undone; those rows are already restored. + */ +export async function archiveWorkspacesWithUndo(input: { + entries: readonly UndoableWorkspaceArchiveEntryInput[]; + toast: ToastApi; +}): Promise { + if (input.entries.length === 0) { + return { failures: [], showPartialFailure: () => false }; + } + + const started = input.entries.map((entry) => { + const archive = beginOptimisticWorkspaceArchive(entry); + const windowEntry: UndoWindowEntry = { + ...entry, + hidden: archive.hidden, + archived: false, + failed: false, + committed: false, + }; + return { windowEntry, done: archive.done }; + }); + + const window = new UndoWindow({ + entries: started.map((item) => item.windowEntry), + toast: input.toast, + }); + latest = window; + + const failures: WorkspaceArchiveBatchFailure[] = []; + await Promise.all( + started.map(async ({ windowEntry, done }) => { + let outcome: Awaited; + try { + outcome = await done; + } catch (error) { + if (window.phase === "undone") return; + window.entryFailed(windowEntry); + failures.push({ workspace: windowEntry.workspace, error }); + return; + } + if (outcome === "archived") window.entryFinished(windowEntry); + }), + ); + + return { + failures, + showPartialFailure: (message) => window.showPartialFailure(message), + }; +} + /** * Archives a workspace and offers to undo it until the toast goes away. * @@ -104,19 +230,19 @@ export async function archiveWorkspaceWithUndo(input: { toast: ToastApi; onArchiveCommitted: () => void; }): Promise { - const archive = beginOptimisticWorkspaceArchive(input); - const window = new UndoWindow({ ...input, hidden: archive.hidden }); - latest = window; - - let outcome: Awaited; - try { - outcome = await archive.done; - } catch (error) { - if (window.phase === "undone") return; - window.archiveFailed(); - throw error; + const { failures } = await archiveWorkspacesWithUndo({ + entries: [ + { + client: input.client, + workspace: input.workspace, + onArchiveCommitted: input.onArchiveCommitted, + }, + ], + toast: input.toast, + }); + if (failures[0]) { + throw failures[0].error; } - if (outcome === "archived") window.archiveFinished(); } /** Undoes the most recent archive while its toast is up. Returns false when there is none. */ diff --git a/packages/app/src/workspace/archive-undo/internal/workspace-archived-toast.tsx b/packages/app/src/workspace/archive-undo/internal/workspace-archived-toast.tsx index 4cca52fd48..cdd0e9f743 100644 --- a/packages/app/src/workspace/archive-undo/internal/workspace-archived-toast.tsx +++ b/packages/app/src/workspace/archive-undo/internal/workspace-archived-toast.tsx @@ -6,17 +6,30 @@ import { Button } from "@/components/ui/button"; import { Shortcut } from "@/components/ui/shortcut"; import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; -export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) { +export function WorkspaceArchivedToast({ + count = 1, + message: customMessage, + onUndo, +}: { + count?: number; + message?: string; + onUndo: () => void; +}) { const { t } = useTranslation(); const undoKeys = useShortcutKeys("undo-archive-workspace"); const undoShortcut = useMemo( () => (undoKeys ? : null), [undoKeys], ); + const message = + customMessage ?? + (count === 1 + ? t("sidebar.workspace.toasts.archived") + : t("sidebar.workspace.toasts.archivedCount", { count })); return ( - {t("sidebar.workspace.toasts.archived")} + {message}