mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Select sidebar workspaces with Cmd/Ctrl+click and Finder-style Shift ranges (#10821)
* feat(app): select sidebar workspaces with Cmd/Ctrl+click and Finder-style Shift ranges Cmd+click on macOS/iOS (Ctrl+click on Windows, Linux and Android) now enters select mode on the clicked row and toggles rows without opening them, matching Shift+click entry. The first modifier click selects only the clicked row and never includes the open workspace, so starting a bulk archive from another row cannot mark the workspace you are reading. Shift+click now rebuilds the range from the anchor on every click instead of only adding to it, so a closer Shift+click shrinks the range and crossing the anchor flips it. Rows picked before the current Shift run are kept, and a Cmd/Ctrl or plain click moves the anchor and commits the range. The primary modifier follows the shortcut layer's `mod` (Meta on mac, Control elsewhere) because Ctrl+click on macOS is the secondary click. The held-key tracker now follows Cmd and Ctrl as well as Shift, since native responder events from a hardware keyboard carry no modifier flags. Both sidebar lists share one press hook instead of duplicating the routing. * fix(app): select on the first tap after a scroll or long press in the sidebar A scroll, swipe, drag, or long-press menu on a workspace row sets the row's long-press flag, and only the drag interaction's press-in clears it. Modifier taps and select-mode taps skip that press-in, so the stale flag swallowed the next Shift/Cmd/Ctrl tap on native hardware keyboards, and the next plain tap in select mode. Those presses never arm the long-press gesture, so the selection press hook now clears the flag when it takes the press-in. * fix(app): keep web context-menu rows clickable after a held press On web, ContextMenuTrigger always handed react-native-web an onLongPress, even though the web menu opens on right-click and the handler did nothing there. With any onLongPress set, react-native-web marks a press held past the long-press delay as a long press and cancels the click that ends it. Only the next responder grant clears that mark, and react-native-web grants none to Ctrl or Alt mousedowns. So a slow click on a sidebar row did not open it, and on Windows/Linux the next Ctrl+click on that row was dropped too. On web the trigger now passes only the caller's onLongPress. * fix(app): stop selecting presses from reading the row's long-press flag The selection press path cleared and honored the row's long-press flag, but only the drag interaction's press-in resets that flag. A Ctrl+click on web gets no press-in, so a flag left by an earlier touch swipe or scroll on the row swallowed it. Selecting presses never arm the long-press gesture, and a native long press already cancels the press, so the selection path no longer reads the flag at all. Navigation keeps its own guard.
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
|
||||
// Cmd on macOS, Ctrl on Windows and Linux: the platform primary modifier the app binds as `mod`.
|
||||
const MOD = "ControlOrMeta";
|
||||
|
||||
type SeededProject = Awaited<ReturnType<typeof seedWorkspace>>;
|
||||
|
||||
async function seedProjectWithWorkspaces(count: number) {
|
||||
const project = await seedWorkspace({ repoPrefix: "sidebar-selection-" });
|
||||
const workspaceIds = [project.workspaceId];
|
||||
for (let index = 1; index < count; index += 1) {
|
||||
const created = await project.client.createWorkspace({
|
||||
source: { kind: "directory", path: project.repoPath, projectId: project.projectId },
|
||||
title: `Selection workspace ${index}`,
|
||||
});
|
||||
if (!created.workspace) throw new Error(created.error ?? "Failed to seed a workspace");
|
||||
workspaceIds.push(created.workspace.id);
|
||||
}
|
||||
return { project, workspaceIds };
|
||||
}
|
||||
|
||||
/** The seeded rows, in the order the sidebar shows them. */
|
||||
async function rowsInSidebarOrder(page: Page, workspaceIds: readonly string[]) {
|
||||
const testIds = workspaceIds.map((id) => `sidebar-workspace-row-${getServerId()}:${id}`);
|
||||
const rows = page.locator(testIds.map((testId) => `[data-testid="${testId}"]`).join(", "));
|
||||
await expect(rows).toHaveCount(workspaceIds.length);
|
||||
const ordered = await rows.evaluateAll((elements) =>
|
||||
elements.map((element) => element.getAttribute("data-testid") ?? ""),
|
||||
);
|
||||
return ordered.map((testId) => page.getByTestId(testId));
|
||||
}
|
||||
|
||||
async function expectChecked(rows: readonly Locator[], checked: readonly boolean[]) {
|
||||
for (const [index, row] of rows.entries()) {
|
||||
await expect(row).toHaveAttribute("aria-checked", String(checked[index]));
|
||||
}
|
||||
}
|
||||
|
||||
async function expectSelectedCount(page: Page, count: number) {
|
||||
await expect(page.getByTestId("workspace-selection-count")).toHaveText(`${count} selected`);
|
||||
}
|
||||
|
||||
async function exitSelection(page: Page) {
|
||||
await page.getByTestId("workspace-selection-exit").click();
|
||||
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
|
||||
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
|
||||
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
|
||||
*/
|
||||
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
|
||||
const [first, second, third, fourth] = rows;
|
||||
await first.click();
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
const openWorkspaceUrl = page.url();
|
||||
|
||||
await third.click({ modifiers: [MOD] });
|
||||
await expectSelectedCount(page, 1);
|
||||
await expectChecked(rows, [false, false, true, false]);
|
||||
|
||||
await fourth.click({ modifiers: [MOD] });
|
||||
await expectChecked(rows, [false, false, true, true]);
|
||||
await third.click({ modifiers: [MOD] });
|
||||
await expectChecked(rows, [false, false, false, true]);
|
||||
|
||||
await second.click();
|
||||
await expectChecked(rows, [false, true, false, true]);
|
||||
expect(page.url()).toBe(openWorkspaceUrl);
|
||||
await exitSelection(page);
|
||||
|
||||
await second.click({ modifiers: ["Shift"] });
|
||||
await expectSelectedCount(page, 1);
|
||||
await expectChecked(rows, [false, true, false, false]);
|
||||
|
||||
await fourth.click({ modifiers: ["Shift"] });
|
||||
await expectChecked(rows, [false, true, true, true]);
|
||||
await third.click({ modifiers: ["Shift"] });
|
||||
await expectChecked(rows, [false, true, true, false]);
|
||||
await first.click({ modifiers: ["Shift"] });
|
||||
await expectChecked(rows, [true, true, false, false]);
|
||||
|
||||
await fourth.click({ modifiers: [MOD] });
|
||||
await third.click({ modifiers: ["Shift"] });
|
||||
await expectChecked(rows, [true, true, true, true]);
|
||||
expect(page.url()).toBe(openWorkspaceUrl);
|
||||
await exitSelection(page);
|
||||
}
|
||||
|
||||
test.describe("sidebar workspace selection clicks", () => {
|
||||
let seeded: { project: SeededProject; workspaceIds: string[] } | null = null;
|
||||
|
||||
test.afterEach(async () => {
|
||||
await seeded?.project.cleanup();
|
||||
seeded = null;
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
|
||||
page,
|
||||
}) => {
|
||||
seeded = await seedProjectWithWorkspaces(4);
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
|
||||
seeded = await seedProjectWithWorkspaces(4);
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
|
||||
});
|
||||
});
|
||||
@@ -106,11 +106,11 @@ import {
|
||||
selectSidebarGroupVisibility,
|
||||
} from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
useWorkspaceSelectionPress,
|
||||
} from "@/sidebar-selection";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
@@ -1117,35 +1117,11 @@ function WorkspaceRowInner({
|
||||
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 { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
|
||||
workspaceKey: workspace.workspaceKey,
|
||||
onNavigate: handleNavigatePress,
|
||||
onPressIn: interaction.handlePressIn,
|
||||
});
|
||||
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View, Text, ScrollView, type GestureResponderEvent } from "react-native";
|
||||
import { View, Text, ScrollView } 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";
|
||||
@@ -74,11 +74,11 @@ import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle
|
||||
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
useWorkspaceSelectionPress,
|
||||
} from "@/sidebar-selection";
|
||||
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
|
||||
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
|
||||
@@ -936,35 +936,11 @@ function StatusWorkspaceRowInnerContent({
|
||||
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],
|
||||
);
|
||||
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
|
||||
workspaceKey: workspace.workspaceKey,
|
||||
onNavigate: handleNavigatePress,
|
||||
onPressIn: startDragPress,
|
||||
});
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
|
||||
@@ -150,17 +150,17 @@ export function ContextMenuTrigger({
|
||||
);
|
||||
|
||||
const propsOnLongPress = props.onLongPress;
|
||||
const handleLongPress = useCallback(
|
||||
const handleNativeLongPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
if (isWeb) {
|
||||
propsOnLongPress?.(event);
|
||||
return;
|
||||
}
|
||||
openAtEvent(event);
|
||||
propsOnLongPress?.(event);
|
||||
},
|
||||
[propsOnLongPress, openAtEvent],
|
||||
);
|
||||
// The web menu opens on right-click, not long press. Any onLongPress makes react-native-web cancel
|
||||
// the click that ends a held press, and only a later press-in clears that, which Ctrl+click never
|
||||
// gets. So on web, pass the caller's onLongPress through and nothing else.
|
||||
const handleLongPress = isWeb ? propsOnLongPress : handleNativeLongPress;
|
||||
|
||||
const handleContextMenu = useCallback(
|
||||
(event: unknown) => {
|
||||
|
||||
@@ -14,4 +14,5 @@ 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";
|
||||
export { readPressModifiers } from "./internal/press-modifiers";
|
||||
export type { PressModifiers } from "./internal/press-modifiers";
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
|
||||
export type HeldModifierKey = "Shift" | "Meta" | "Control";
|
||||
|
||||
export interface HeldModifierKeyEvent {
|
||||
key: string;
|
||||
code?: string;
|
||||
shiftKey: boolean;
|
||||
metaKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
}
|
||||
|
||||
export interface HeldModifierTracker {
|
||||
isDown(key: HeldModifierKey): boolean;
|
||||
handleKeyDown(event: HeldModifierKeyEvent): void;
|
||||
handleKeyUp(event: HeldModifierKeyEvent): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
const MODIFIER_FLAGS = {
|
||||
Shift: "shiftKey",
|
||||
Meta: "metaKey",
|
||||
Control: "ctrlKey",
|
||||
} as const satisfies Record<HeldModifierKey, keyof HeldModifierKeyEvent>;
|
||||
|
||||
const MODIFIER_KEYS = Object.keys(MODIFIER_FLAGS) as HeldModifierKey[];
|
||||
|
||||
/**
|
||||
* Tracks which physical modifier keys are held across DOM and native hardware keyboard streams so
|
||||
* press handlers that omit modifier flags (native GestureResponderEvent, touch-synthesized clicks)
|
||||
* can still observe Shift+tap or Cmd+tap from a hardware keyboard.
|
||||
*/
|
||||
export function createHeldModifierTracker(): HeldModifierTracker {
|
||||
const pressedCodes: Record<HeldModifierKey, Set<string>> = {
|
||||
Shift: new Set(),
|
||||
Meta: new Set(),
|
||||
Control: new Set(),
|
||||
};
|
||||
// A key reported without a modifier's flag means that modifier's key-up was swallowed.
|
||||
const clearReleased = (event: HeldModifierKeyEvent) => {
|
||||
for (const modifier of MODIFIER_KEYS) {
|
||||
if (event.key !== modifier && !event[MODIFIER_FLAGS[modifier]]) {
|
||||
pressedCodes[modifier].clear();
|
||||
}
|
||||
}
|
||||
};
|
||||
return {
|
||||
isDown: (key) => pressedCodes[key].size > 0,
|
||||
handleKeyDown(event) {
|
||||
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
|
||||
if (modifier) {
|
||||
pressedCodes[modifier].add(event.code || modifier);
|
||||
}
|
||||
clearReleased(event);
|
||||
},
|
||||
handleKeyUp(event) {
|
||||
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
|
||||
if (modifier) {
|
||||
pressedCodes[modifier].delete(event.code || modifier);
|
||||
if (!event[MODIFIER_FLAGS[modifier]]) {
|
||||
pressedCodes[modifier].clear();
|
||||
}
|
||||
}
|
||||
clearReleased(event);
|
||||
},
|
||||
reset() {
|
||||
for (const modifier of MODIFIER_KEYS) {
|
||||
pressedCodes[modifier].clear();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const heldModifiers = createHeldModifierTracker();
|
||||
|
||||
/**
|
||||
* Modifiers that accompanied a pointer press. `mod` is the platform primary modifier the shortcut
|
||||
* layer binds as `mod`: Cmd on macOS/iOS/iPadOS, Ctrl on Windows, Linux and Android. Ctrl on macOS
|
||||
* is the secondary click, so it never counts as `mod` there.
|
||||
*/
|
||||
export interface PressModifiers {
|
||||
shift: boolean;
|
||||
mod: boolean;
|
||||
}
|
||||
|
||||
interface PressModifierContext {
|
||||
isMac: boolean;
|
||||
held: Pick<HeldModifierTracker, "isDown">;
|
||||
}
|
||||
|
||||
export function readPressModifiers(
|
||||
event: unknown,
|
||||
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
|
||||
): PressModifiers {
|
||||
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
|
||||
return {
|
||||
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
|
||||
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
|
||||
};
|
||||
}
|
||||
|
||||
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
|
||||
if (typeof event !== "object" || event === null) return false;
|
||||
if (Reflect.get(event, flag) === true) return true;
|
||||
const nativeEvent = Reflect.get(event, "nativeEvent");
|
||||
return (
|
||||
typeof nativeEvent === "object" &&
|
||||
nativeEvent !== null &&
|
||||
Reflect.get(nativeEvent, flag) === true
|
||||
);
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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<string>();
|
||||
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();
|
||||
}
|
||||
@@ -300,49 +300,111 @@ describe("hardware source adapter", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shift modifier tracking", () => {
|
||||
function modifierKey(
|
||||
key: string,
|
||||
code: string,
|
||||
flags: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {},
|
||||
) {
|
||||
return { key, code, shiftKey: false, metaKey: false, ctrlKey: false, ...flags };
|
||||
}
|
||||
|
||||
describe("held 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);
|
||||
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
|
||||
const tracker = createHeldModifierTracker();
|
||||
expect(tracker.isDown("Shift")).toBe(false);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
expect(tracker.isDown("Shift")).toBe(true);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true });
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.handleKeyDown(modifierKey("Shift", "ShiftRight", { shiftKey: true }));
|
||||
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
expect(tracker.isDown("Shift")).toBe(true);
|
||||
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false });
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
tracker.handleKeyUp(modifierKey("Shift", "ShiftRight"));
|
||||
expect(tracker.isDown("Shift")).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);
|
||||
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
expect(tracker.isDown("Shift")).toBe(true);
|
||||
tracker.handleKeyDown(modifierKey("a", "KeyA"));
|
||||
expect(tracker.isDown("Shift")).toBe(false);
|
||||
|
||||
// Clears on blur / backgrounding.
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
expect(tracker.isDown("Shift")).toBe(true);
|
||||
tracker.reset();
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
expect(tracker.isDown("Shift")).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);
|
||||
it("tracks Cmd and Ctrl holds independently of Shift", async () => {
|
||||
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
|
||||
const tracker = createHeldModifierTracker();
|
||||
|
||||
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(isShiftKeyDown()).toBe(true);
|
||||
tracker.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
|
||||
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { metaKey: true, shiftKey: true }));
|
||||
expect([tracker.isDown("Meta"), tracker.isDown("Shift"), tracker.isDown("Control")]).toEqual([
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
]);
|
||||
|
||||
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
|
||||
expect(isShiftKeyDown()).toBe(false);
|
||||
} finally {
|
||||
shiftModifier.reset();
|
||||
}
|
||||
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { metaKey: true }));
|
||||
expect([tracker.isDown("Meta"), tracker.isDown("Shift")]).toEqual([true, false]);
|
||||
|
||||
// A key reported without the Meta flag means its key-up was swallowed.
|
||||
tracker.handleKeyDown(modifierKey("a", "KeyA"));
|
||||
expect(tracker.isDown("Meta")).toBe(false);
|
||||
|
||||
tracker.handleKeyDown(modifierKey("Control", "ControlRight", { ctrlKey: true }));
|
||||
expect(tracker.isDown("Control")).toBe(true);
|
||||
tracker.handleKeyUp(modifierKey("Control", "ControlRight"));
|
||||
expect(tracker.isDown("Control")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("press modifiers", () => {
|
||||
it("reads Shift and the platform primary modifier from a pointer press", async () => {
|
||||
const { createHeldModifierTracker, readPressModifiers } =
|
||||
await import("./internal/press-modifiers");
|
||||
const held = createHeldModifierTracker();
|
||||
const mac = { isMac: true, held };
|
||||
const other = { isMac: false, held };
|
||||
|
||||
expect(readPressModifiers({ shiftKey: true }, mac)).toEqual({ shift: true, mod: false });
|
||||
expect(readPressModifiers({ nativeEvent: { shiftKey: true } }, other)).toEqual({
|
||||
shift: true,
|
||||
mod: false,
|
||||
});
|
||||
expect(readPressModifiers({ metaKey: true }, mac)).toEqual({ shift: false, mod: true });
|
||||
expect(readPressModifiers({ ctrlKey: true }, other)).toEqual({ shift: false, mod: true });
|
||||
// Ctrl+click is the secondary click on macOS, and Windows/Linux have no Cmd.
|
||||
expect(readPressModifiers({ ctrlKey: true }, mac)).toEqual({ shift: false, mod: false });
|
||||
expect(readPressModifiers({ metaKey: true }, other)).toEqual({ shift: false, mod: false });
|
||||
expect(readPressModifiers(null, mac)).toEqual({ shift: false, mod: false });
|
||||
});
|
||||
|
||||
it("falls back to held hardware keys when a native press omits modifiers", async () => {
|
||||
const { createHeldModifierTracker, readPressModifiers } =
|
||||
await import("./internal/press-modifiers");
|
||||
const held = createHeldModifierTracker();
|
||||
const responderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
|
||||
|
||||
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
|
||||
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
|
||||
shift: false,
|
||||
mod: true,
|
||||
});
|
||||
expect(readPressModifiers(responderEvent, { isMac: false, held })).toEqual({
|
||||
shift: false,
|
||||
mod: false,
|
||||
});
|
||||
|
||||
held.reset();
|
||||
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
|
||||
shift: true,
|
||||
mod: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { usesDesktopBindings } from "./internal/conventions";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { overlays } from "./internal/overlays";
|
||||
import { shiftModifier } from "./internal/shift-modifier";
|
||||
import { heldModifiers } from "./internal/press-modifiers";
|
||||
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
|
||||
import type { KeyboardSourceInput } from "./internal/sources/contract";
|
||||
import type { KeyboardInputEvent } from "./internal/overlays";
|
||||
@@ -251,12 +251,12 @@ export function useKeyboardShortcuts({
|
||||
);
|
||||
|
||||
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
|
||||
shiftModifier.handleKeyDown(input.event);
|
||||
heldModifiers.handleKeyDown(input.event);
|
||||
return pipeline.keyDown(input);
|
||||
});
|
||||
|
||||
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
|
||||
shiftModifier.handleKeyUp(event);
|
||||
heldModifiers.handleKeyUp(event);
|
||||
const key = event.key ?? "";
|
||||
if (key === badgeModifierKey) {
|
||||
setBadgeModifierDown(false);
|
||||
@@ -264,7 +264,7 @@ export function useKeyboardShortcuts({
|
||||
});
|
||||
|
||||
const handleBlur = useStableEvent(() => {
|
||||
shiftModifier.reset();
|
||||
heldModifiers.reset();
|
||||
resetModifiers();
|
||||
});
|
||||
|
||||
@@ -282,7 +282,7 @@ export function useKeyboardShortcuts({
|
||||
});
|
||||
return () => {
|
||||
detach();
|
||||
shiftModifier.reset();
|
||||
heldModifiers.reset();
|
||||
pipeline.dispose();
|
||||
};
|
||||
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export { isShiftPressEvent } from "./internal/selection-state";
|
||||
export {
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
@@ -6,3 +5,4 @@ export {
|
||||
useSidebarSelectionStore,
|
||||
} from "./internal/selection-store";
|
||||
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
|
||||
export { useWorkspaceSelectionPress } from "./internal/workspace-selection-press";
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
enterWorkspaceSelection,
|
||||
exitWorkspaceSelection,
|
||||
INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
isShiftPressEvent,
|
||||
reconcileWorkspaceSelection,
|
||||
selectWorkspaceRange,
|
||||
toggleWorkspaceSelection,
|
||||
@@ -51,6 +50,35 @@ describe("sidebar workspace selection state", () => {
|
||||
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
|
||||
});
|
||||
|
||||
it("replaces the previous Shift range so a closer Shift+click shrinks it, like Finder", () => {
|
||||
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
|
||||
state = selectWorkspaceRange(state, "ws-6", visible);
|
||||
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4", "ws-5", "ws-6"]);
|
||||
|
||||
state = selectWorkspaceRange(state, "ws-4", visible);
|
||||
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4"]);
|
||||
|
||||
// Crossing over the anchor flips the range without dropping the earlier pick.
|
||||
state = selectWorkspaceRange(state, "ws-2", visible);
|
||||
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3"]);
|
||||
expect(state.anchorKey).toBe("ws-3");
|
||||
});
|
||||
|
||||
it("commits the Shift range once a toggle moves the anchor", () => {
|
||||
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = selectWorkspaceRange(state, "ws-3", visible);
|
||||
state = toggleWorkspaceSelection(state, "ws-5");
|
||||
|
||||
// The new anchor is ws-5; shrinking its range must keep ws-1..ws-3.
|
||||
state = selectWorkspaceRange(state, "ws-6", visible);
|
||||
state = selectWorkspaceRange(state, "ws-5", visible);
|
||||
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3", "ws-5"]);
|
||||
});
|
||||
|
||||
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",
|
||||
@@ -78,16 +106,4 @@ describe("sidebar workspace selection state", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { isShiftKeyDown } from "@/keyboard";
|
||||
|
||||
export interface WorkspaceSelectionState {
|
||||
active: boolean;
|
||||
selectedKeys: ReadonlySet<string>;
|
||||
anchorKey: string | null;
|
||||
/**
|
||||
* Selection as it stood before the current run of Shift+clicks from `anchorKey`. Each Shift+click
|
||||
* rebuilds the selection from this base, so a closer Shift+click shrinks the range like Finder.
|
||||
* Null until the first Shift+click after the anchor moves.
|
||||
*/
|
||||
rangeBaseKeys: ReadonlySet<string> | null;
|
||||
}
|
||||
|
||||
const EMPTY_KEYS: ReadonlySet<string> = new Set();
|
||||
@@ -12,6 +16,7 @@ export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
|
||||
active: false,
|
||||
selectedKeys: EMPTY_KEYS,
|
||||
anchorKey: null,
|
||||
rangeBaseKeys: null,
|
||||
};
|
||||
|
||||
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
|
||||
@@ -19,6 +24,7 @@ export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectio
|
||||
active: true,
|
||||
selectedKeys: new Set([workspaceKey]),
|
||||
anchorKey: workspaceKey,
|
||||
rangeBaseKeys: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -37,6 +43,7 @@ export function toggleWorkspaceSelection(
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: workspaceKey,
|
||||
rangeBaseKeys: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -48,23 +55,18 @@ export function selectWorkspaceRange(
|
||||
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 anchorIndex = state.anchorKey ? orderedVisibleKeys.indexOf(state.anchorKey) : -1;
|
||||
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 };
|
||||
return { active: true, selectedKeys: next, anchorKey: targetKey, rangeBaseKeys: null };
|
||||
}
|
||||
|
||||
const rangeBaseKeys = state.rangeBaseKeys ?? state.selectedKeys;
|
||||
const start = Math.min(anchorIndex, targetIndex);
|
||||
const end = Math.max(anchorIndex, targetIndex);
|
||||
const next = new Set(state.selectedKeys);
|
||||
const next = new Set(rangeBaseKeys);
|
||||
for (let index = start; index <= end; index += 1) {
|
||||
const key = orderedVisibleKeys[index];
|
||||
if (key !== undefined) {
|
||||
@@ -75,6 +77,7 @@ export function selectWorkspaceRange(
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: state.anchorKey,
|
||||
rangeBaseKeys,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,46 +87,34 @@ export function reconcileWorkspaceSelection(
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) return state;
|
||||
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
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) {
|
||||
const selectedKeys = keepAvailableKeys(state.selectedKeys, availableKeys);
|
||||
const rangeBaseKeys = state.rangeBaseKeys
|
||||
? keepAvailableKeys(state.rangeBaseKeys, availableKeys)
|
||||
: null;
|
||||
const anchorKey = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
|
||||
if (
|
||||
selectedKeys === state.selectedKeys &&
|
||||
rangeBaseKeys === state.rangeBaseKeys &&
|
||||
anchorKey === state.anchorKey
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: changed ? next : state.selectedKeys,
|
||||
anchorKey: nextAnchor,
|
||||
};
|
||||
return { active: true, selectedKeys, anchorKey, rangeBaseKeys };
|
||||
}
|
||||
|
||||
function keepAvailableKeys(
|
||||
keys: ReadonlySet<string>,
|
||||
availableKeys: ReadonlySet<string>,
|
||||
): ReadonlySet<string> {
|
||||
for (const key of keys) {
|
||||
if (!availableKeys.has(key)) {
|
||||
return new Set([...keys].filter((candidate) => availableKeys.has(candidate)));
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -29,7 +29,8 @@ export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysRea
|
||||
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
|
||||
isArchiving: boolean;
|
||||
enter: (workspaceKey: string) => void;
|
||||
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
|
||||
/** Shift+click selects a range from the anchor; any other press toggles the workspace. */
|
||||
pressWorkspace: (workspaceKey: string, options: { range: boolean }) => void;
|
||||
reconcile: (availableKeys: ReadonlySet<string>) => void;
|
||||
setArchiving: (archiving: boolean) => void;
|
||||
exit: () => void;
|
||||
@@ -43,10 +44,10 @@ export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set)
|
||||
...enterWorkspaceSelection(workspaceKey),
|
||||
isArchiving: false,
|
||||
})),
|
||||
pressWorkspace: (workspaceKey, { shiftKey }) =>
|
||||
pressWorkspace: (workspaceKey, { range }) =>
|
||||
set((state) => {
|
||||
if (state.isArchiving) return state;
|
||||
const next = shiftKey
|
||||
const next = range
|
||||
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
|
||||
: toggleWorkspaceSelection(state, workspaceKey);
|
||||
return next === state ? state : { ...next };
|
||||
|
||||
+135
-16
@@ -5,6 +5,7 @@ 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 { userEvent } from "vitest/browser";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { ToastProvider, useToast } from "@/contexts/toast-context";
|
||||
@@ -17,14 +18,16 @@ import {
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
SidebarSelectionHost,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
useWorkspaceSelectionPress,
|
||||
} from "@/sidebar-selection";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
@@ -87,19 +90,23 @@ function SidebarToastProbe() {
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
let navigatedKeys: string[] = [];
|
||||
const rowLongPressRefs = new Map<string, { current: boolean }>();
|
||||
|
||||
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],
|
||||
);
|
||||
const handleNavigate = useCallback(() => {
|
||||
navigatedKeys.push(entry.workspaceKey);
|
||||
}, [entry.workspaceKey]);
|
||||
// The row's gesture state, wired the way sidebar rows wire it.
|
||||
const interaction = useLongPressDragInteraction({ drag: noop, menuController: null });
|
||||
rowLongPressRefs.set(entry.workspaceKey, interaction.didLongPressRef);
|
||||
const { onPress, onPressIn } = useWorkspaceSelectionPress({
|
||||
workspaceKey: entry.workspaceKey,
|
||||
onNavigate: handleNavigate,
|
||||
onPressIn: interaction.handlePressIn,
|
||||
});
|
||||
return (
|
||||
<SidebarWorkspaceContextMenu
|
||||
contextMenuOpen={false}
|
||||
@@ -110,7 +117,8 @@ function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
highlightStyle={undefined}
|
||||
onPress={handlePress}
|
||||
onPress={onPress}
|
||||
onPressIn={onPressIn}
|
||||
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
|
||||
>
|
||||
<Text>{entry.name}</Text>
|
||||
@@ -125,6 +133,8 @@ function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
|
||||
);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
container = document.createElement("div");
|
||||
// Give the sidebar room so the floating selection bar sits below the rows instead of on them.
|
||||
container.style.cssText = "display:flex;flex-direction:column;width:320px;height:640px;";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
@@ -155,6 +165,8 @@ afterEach(() => {
|
||||
capturedDispatcher = null;
|
||||
capturedSidebarToast = null;
|
||||
fallbackArchiveCount = 0;
|
||||
navigatedKeys = [];
|
||||
rowLongPressRefs.clear();
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().exit();
|
||||
});
|
||||
@@ -166,6 +178,113 @@ afterEach(() => {
|
||||
container = null;
|
||||
});
|
||||
|
||||
function row(id: string): HTMLElement {
|
||||
const element = document.querySelector<HTMLElement>(
|
||||
`[data-testid="sidebar-workspace-row-srv:${id}"]`,
|
||||
);
|
||||
if (!element) throw new Error(`Row ${id} is not mounted`);
|
||||
return element;
|
||||
}
|
||||
|
||||
function selectedIds(): string[] {
|
||||
const state = useSidebarSelectionStore.getState();
|
||||
if (!state.active) return [];
|
||||
return [...state.selectedKeys].map((key) => key.replace("srv:", "")).sort();
|
||||
}
|
||||
|
||||
function markGestureCanceled(id: string) {
|
||||
const ref = rowLongPressRefs.get(`srv:${id}`);
|
||||
if (!ref) throw new Error(`Row ${id} is not mounted`);
|
||||
ref.current = true;
|
||||
}
|
||||
|
||||
/** Holds the primary mouse button on a row past the long-press delay, then releases it. */
|
||||
async function slowClick(element: HTMLElement) {
|
||||
const box = element.getBoundingClientRect();
|
||||
const init = {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 0,
|
||||
clientX: box.left + box.width / 2,
|
||||
clientY: box.top + box.height / 2,
|
||||
};
|
||||
element.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: 1 }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 700));
|
||||
element.dispatchEvent(new MouseEvent("mouseup", init));
|
||||
element.dispatchEvent(new MouseEvent("click", init));
|
||||
}
|
||||
|
||||
// Cmd on macOS, Ctrl on Windows and Linux, matching the shortcut layer's `mod`.
|
||||
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
|
||||
|
||||
describe("sidebar workspace row presses", () => {
|
||||
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
|
||||
mountHost(["a", "b", "c", "d"].map(makeEntry));
|
||||
|
||||
await userEvent.click(row("a"));
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
|
||||
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["c"]);
|
||||
|
||||
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
|
||||
await userEvent.click(row("d"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["b", "c", "d"]);
|
||||
|
||||
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["b", "d"]);
|
||||
|
||||
// Plain clicks keep toggling while select mode is on.
|
||||
await userEvent.click(row("a"));
|
||||
expect(selectedIds()).toEqual(["a", "b", "d"]);
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
});
|
||||
|
||||
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
|
||||
mountHost(["a", "b"].map(makeEntry));
|
||||
|
||||
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
|
||||
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
|
||||
markGestureCanceled("a");
|
||||
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["a"]);
|
||||
|
||||
markGestureCanceled("b");
|
||||
await userEvent.click(row("b"));
|
||||
expect(selectedIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
|
||||
mountHost(["a", "b"].map(makeEntry));
|
||||
|
||||
await act(() => slowClick(row("a")));
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
|
||||
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
|
||||
mountHost(["a", "b", "c", "d", "e", "f"].map(makeEntry));
|
||||
|
||||
await userEvent.click(row("b"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["b"]);
|
||||
|
||||
await userEvent.click(row("e"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["b", "c", "d", "e"]);
|
||||
|
||||
await userEvent.click(row("c"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["b", "c"]);
|
||||
|
||||
// Cmd/Ctrl+click moves the anchor; the next Shift range grows from there and keeps b..c.
|
||||
await userEvent.click(row("f"), { modifiers: [MOD_KEY] });
|
||||
await userEvent.click(row("e"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["b", "c", "e", "f"]);
|
||||
expect(navigatedKeys).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
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")]);
|
||||
@@ -173,14 +292,14 @@ describe("SidebarSelectionHost", () => {
|
||||
|
||||
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { range: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"2 selected",
|
||||
@@ -201,8 +320,8 @@ describe("SidebarSelectionHost", () => {
|
||||
|
||||
// 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 });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { range: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"3 selected",
|
||||
@@ -246,7 +365,7 @@ describe("SidebarSelectionHost", () => {
|
||||
// Enter select mode then deselect the only row -> 0 selected.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"0 selected",
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useCallback } from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import { readPressModifiers } from "@/keyboard";
|
||||
import { useSidebarSelectionStore } from "./selection-store";
|
||||
|
||||
interface WorkspaceSelectionPressInput {
|
||||
workspaceKey: string;
|
||||
/** The row's normal press: open the workspace. */
|
||||
onNavigate: () => void;
|
||||
/** The row's normal press-in: start the long-press drag gesture. */
|
||||
onPressIn?: (event: GestureResponderEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
|
||||
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
|
||||
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
|
||||
* mouse users can keep tapping without a modifier.
|
||||
*
|
||||
* Selecting presses never consult the row's long-press flag. They never arm the long-press
|
||||
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
|
||||
* no press-in, so a flag left by an earlier scroll or swipe would swallow the click.
|
||||
*/
|
||||
export function useWorkspaceSelectionPress({
|
||||
workspaceKey,
|
||||
onNavigate,
|
||||
onPressIn,
|
||||
}: WorkspaceSelectionPressInput) {
|
||||
const handlePress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const modifiers = readPressModifiers(event);
|
||||
const store = useSidebarSelectionStore.getState();
|
||||
if (!store.active && !modifiers.shift && !modifiers.mod) {
|
||||
onNavigate();
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
store.pressWorkspace(workspaceKey, { range: modifiers.shift });
|
||||
},
|
||||
[onNavigate, workspaceKey],
|
||||
);
|
||||
|
||||
const handlePressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const modifiers = readPressModifiers(event);
|
||||
if (modifiers.shift || modifiers.mod) {
|
||||
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!useSidebarSelectionStore.getState().active) {
|
||||
onPressIn?.(event);
|
||||
}
|
||||
},
|
||||
[onPressIn],
|
||||
);
|
||||
|
||||
return { onPress: handlePress, onPressIn: handlePressIn };
|
||||
}
|
||||
Reference in New Issue
Block a user