mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3777cc754b | ||
|
|
7708e1f084 | ||
|
|
ba45634eee |
@@ -36,6 +36,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
|
||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Drag to reorder
|
||||
|
||||
A list the user can reorder renders through `DraggableList` from `@/components/draggable-list`. Each row puts a `DraggableListHandle` where its grip is drawn. The Usage cards (`packages/app/src/usage/list.tsx`, `packages/app/src/usage/card.tsx`) and the agent profile roster (`packages/app/src/agent-profiles/settings/`) are the reference.
|
||||
|
||||
| Platform | How a drag starts |
|
||||
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Web | dnd-kit pointer drag. With `useDragHandle`, only the handle starts it, and the handle reorders by keyboard. Without it, the whole row starts it. |
|
||||
| Native | Hold the handle for 180 ms without moving more than 4 px. The list then owns the touch until the finger lifts. |
|
||||
|
||||
## The scroll view must host the drag
|
||||
|
||||
On native, the hold calls `drag()`, which calls `useContentDrag().setActive(true)` from `@/components/ui/content-drag` on the nearest scroll view. That scroll view stops scrolling until the drag ends. If no scroll view up the tree hosts content drags, `setActive` does nothing. The page scroll then takes the touch as soon as the finger moves past the touch slop, before the list's own pan activates. The row never moves, and the page scrolls instead.
|
||||
|
||||
These scroll views host content drags:
|
||||
|
||||
- `ScrollView` from `@/components/ui/scroll-view`, inside and outside a sheet.
|
||||
- `PageLayout`, for a settings page or any other full page.
|
||||
|
||||
If you put a reorderable list in another scroll view, such as a third-party keyboard-aware one, wrap it with `withContentDrag` from `@/components/ui/content-drag`. `packages/app/src/components/page-layout/index.tsx` shows the pattern. A plain `ScrollView` from `react-native` breaks the drag.
|
||||
|
||||
Inside a sheet, the `ScrollView` also registers the drag gesture with the sheet, so the sheet's pan-to-close waits for it.
|
||||
|
||||
## Where the grip goes
|
||||
|
||||
The grip hangs in the row's leading padding, absolutely positioned over the full row height. The row's content keeps the same left rail as rows that cannot be reordered, and the grip does not take a column. On a pointer device the grip shows on hover, focus, or while dragging. On touch and compact layouts it always shows, because there is no hover.
|
||||
|
||||
## Test with a page that scrolls
|
||||
|
||||
A list that fits on the screen does not show the bug, because the page has nothing to scroll. Test on a phone with enough rows that the page scrolls. Then check both directions:
|
||||
|
||||
1. Hold the grip and drag a row past two others. The new order is saved.
|
||||
2. Swipe quickly on a row body. The page scrolls and the order stays the same.
|
||||
|
||||
On an Android emulator, `adb shell input swipe` does not hold still long enough to arm the drag. Send `input motionevent DOWN`, wait 500 ms, then send `MOVE` events and `UP`.
|
||||
@@ -465,7 +465,7 @@ in a tab. An overlay opened from that content and calling `useSafeAreaInsets()`
|
||||
gets that 0 and draws over the navigation bar.
|
||||
|
||||
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
|
||||
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
|
||||
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
|
||||
- An RN `Modal` passes the call site's context straight through, so wrap its content in
|
||||
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
|
||||
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
@@ -153,3 +153,25 @@ On iPad, replacing the field a second time appends text. For this Settings journ
|
||||
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
|
||||
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
|
||||
runs end to end without these adjustments.
|
||||
|
||||
## Sheet footer keyboard safe-area clearance
|
||||
|
||||
`footer-keyboard.android.sh` records the **Add project** sheet on an Android device or emulator
|
||||
across repeated keyboard open/dismiss transitions, then runs `assert-sheet-footer-keyboard.mjs`
|
||||
over every recorded frame. Configure three-button navigation, `show_ime_with_hard_keyboard=1`, and
|
||||
a visible soft keyboard (such as Gboard) on the test device before running so the script does not
|
||||
mutate device settings. The assertion checks both settled positions against the navigation bar
|
||||
height and fails if any frame drops the **Open project** button into the navigation bar or
|
||||
overshoots above its open-keyboard position.
|
||||
|
||||
```sh
|
||||
ANDROID_SERIAL=emulator-5554 \
|
||||
packages/app/e2e/mobile/modal-sheet/footer-keyboard.android.sh
|
||||
```
|
||||
|
||||
You can also validate an existing screen recording directly (optionally passing pixel tolerance and
|
||||
navigation bar height in pixels):
|
||||
|
||||
```sh
|
||||
node packages/app/e2e/mobile/modal-sheet/assert-sheet-footer-keyboard.mjs /path/to/recording.mp4 4 96
|
||||
```
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import process from "node:process";
|
||||
|
||||
const [, , videoPath, toleranceArg = "4", navBarHeightArg = "0"] = process.argv;
|
||||
|
||||
if (!videoPath) {
|
||||
throw new Error(
|
||||
"Usage: node assert-sheet-footer-keyboard.mjs <screenrecord.mp4> [pixel-tolerance] [nav-bar-height-px]",
|
||||
);
|
||||
}
|
||||
|
||||
const tolerance = Number(toleranceArg);
|
||||
if (!Number.isFinite(tolerance) || tolerance < 0) {
|
||||
throw new Error(`Invalid pixel tolerance: ${toleranceArg}`);
|
||||
}
|
||||
|
||||
const navBarHeight = Number(navBarHeightArg);
|
||||
if (!Number.isFinite(navBarHeight) || navBarHeight < 0) {
|
||||
throw new Error(`Invalid navigation bar height: ${navBarHeightArg}`);
|
||||
}
|
||||
|
||||
function probeDimensions(filePath) {
|
||||
const output = execFileSync(
|
||||
"ffprobe",
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height",
|
||||
"-of",
|
||||
"csv=s=x:p=0",
|
||||
filePath,
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
).trim();
|
||||
const [width, height] = output.split("x").map(Number);
|
||||
if (!width || !height) {
|
||||
throw new Error(`Unable to read video dimensions for ${filePath}: ${output}`);
|
||||
}
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function measureButtonBottomPerFrame(filePath, width, height) {
|
||||
const centerX = Math.floor(width / 2);
|
||||
// Decode only the 1px vertical centerline so full-rate recordings fit comfortably in memory.
|
||||
const result = spawnSync(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
"-i",
|
||||
filePath,
|
||||
"-vf",
|
||||
`format=rgb24,crop=1:${height}:${centerX}:0`,
|
||||
"-vsync",
|
||||
"0",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pix_fmt",
|
||||
"rgb24",
|
||||
"-",
|
||||
],
|
||||
{ maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`ffmpeg failed (${result.status}): ${result.stderr?.toString("utf8") ?? ""}`);
|
||||
}
|
||||
|
||||
const buffer = result.stdout;
|
||||
const frameSize = height * 3;
|
||||
const frameCount = Math.floor(buffer.length / frameSize);
|
||||
// Restrict vertical scan below the search field so its green focus ring is excluded.
|
||||
const scanTop = Math.floor(height * 0.42);
|
||||
const bottoms = [];
|
||||
|
||||
for (let frame = 0; frame < frameCount; frame += 1) {
|
||||
const frameOffset = frame * frameSize;
|
||||
let maxY = null;
|
||||
for (let y = scanTop; y < height; y += 1) {
|
||||
const offset = frameOffset + y * 3;
|
||||
const r = buffer[offset];
|
||||
const g = buffer[offset + 1];
|
||||
const b = buffer[offset + 2];
|
||||
// Matches the green primary "Open project" button (both enabled and disabled states).
|
||||
if (g > 50 && g > r + 15 && g > b + 10) {
|
||||
maxY = y;
|
||||
}
|
||||
}
|
||||
bottoms.push(maxY);
|
||||
}
|
||||
return bottoms;
|
||||
}
|
||||
|
||||
function findSettledValue(values, minRunLength) {
|
||||
let runValue = null;
|
||||
let runLength = 0;
|
||||
for (const value of values) {
|
||||
if (value !== null && runValue !== null && Math.abs(value - runValue) <= 2) {
|
||||
runLength += 1;
|
||||
if (runLength >= minRunLength) return runValue;
|
||||
} else {
|
||||
runValue = value;
|
||||
runLength = value === null ? 0 : 1;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const { width, height } = probeDimensions(videoPath);
|
||||
const bottoms = measureButtonBottomPerFrame(videoPath, width, height);
|
||||
const visibleFrames = bottoms
|
||||
.map((bottom, frame) => ({ frame, bottom }))
|
||||
.filter((entry) => entry.bottom !== null);
|
||||
|
||||
if (visibleFrames.length < 10) {
|
||||
throw new Error(
|
||||
`Expected at least 10 frames with the Open project footer button visible, found ${visibleFrames.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Identify settled resting (keyboard closed, lower on screen) and open (keyboard shown, higher on
|
||||
// screen) positions by finding stable runs separated by at least 200px of keyboard height.
|
||||
const minBottom = Math.min(...visibleFrames.map((entry) => entry.bottom));
|
||||
const maxBottom = Math.max(...visibleFrames.map((entry) => entry.bottom));
|
||||
const midpoint = (minBottom + maxBottom) / 2;
|
||||
|
||||
const closedSettled = findSettledValue(
|
||||
bottoms.map((y) => (y !== null && y > midpoint ? y : null)),
|
||||
15,
|
||||
);
|
||||
const openSettled = findSettledValue(
|
||||
bottoms.map((y) => (y !== null && y < midpoint ? y : null)),
|
||||
15,
|
||||
);
|
||||
|
||||
if (closedSettled === null || openSettled === null || closedSettled - openSettled < 200) {
|
||||
throw new Error(
|
||||
`Recording did not capture settled keyboard-closed (${closedSettled}) and keyboard-open (${openSettled}) states`,
|
||||
);
|
||||
}
|
||||
|
||||
const maxAllowedBottom =
|
||||
navBarHeight > 0
|
||||
? Math.min(closedSettled + tolerance, height - navBarHeight)
|
||||
: closedSettled + tolerance;
|
||||
const belowNavViolations = visibleFrames.filter((entry) => entry.bottom > maxAllowedBottom);
|
||||
const overshootViolations = visibleFrames.filter((entry) => entry.bottom < openSettled - tolerance);
|
||||
|
||||
if (belowNavViolations.length > 0 || overshootViolations.length > 0) {
|
||||
const summary = [
|
||||
`Sheet footer keyboard transition jank detected in ${videoPath}:`,
|
||||
` settled closed bottom=${closedSettled}px (gap=${height - closedSettled}px), settled open bottom=${openSettled}px (gap=${height - openSettled}px), maxAllowedBottom=${maxAllowedBottom}px`,
|
||||
];
|
||||
if (belowNavViolations.length > 0) {
|
||||
const worst = Math.max(...belowNavViolations.map((entry) => entry.bottom));
|
||||
summary.push(
|
||||
` dropped below safe-area clearance on ${belowNavViolations.length} frames (first=f${belowNavViolations[0].frame}, last=f${belowNavViolations.at(-1).frame}, worst bottom=${worst}px, excess=+${worst - maxAllowedBottom}px)`,
|
||||
);
|
||||
}
|
||||
if (overshootViolations.length > 0) {
|
||||
const worst = Math.min(...overshootViolations.map((entry) => entry.bottom));
|
||||
summary.push(
|
||||
` overshot above open keyboard position on ${overshootViolations.length} frames (first=f${overshootViolations[0].frame}, worst bottom=${worst}px, overshoot=-${openSettled - worst}px)`,
|
||||
);
|
||||
}
|
||||
throw new Error(summary.join("\n"));
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
`Sheet footer stayed within bounds across ${bottoms.length} frames (${visibleFrames.length} visible): closed=${closedSettled}px, open=${openSettled}px, maxAllowed=${maxAllowedBottom}px, 0 nav-bar overlap frames, 0 overshoot frames\n`,
|
||||
);
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Verifies that the Add project bottom sheet footer never flashes behind the Android system
|
||||
# navigation bar on keyboard dismiss or overshoots upward on keyboard open.
|
||||
#
|
||||
# Prerequisites (configured on the test device before running):
|
||||
# - Three-button navigation bar enabled (for example:
|
||||
# `adb shell cmd overlay enable com.android.internal.systemui.navbar.threebutton`).
|
||||
# - Software keyboard enabled when a hardware keyboard is attached (`show_ime_with_hard_keyboard=1`)
|
||||
# and a visible soft keyboard (such as Gboard) selected as the active IME.
|
||||
# - The Add project sheet already open with a connected host so the Open project footer button is
|
||||
# visible.
|
||||
# - `ffmpeg` and `ffprobe` on PATH.
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
SERIAL="${ANDROID_SERIAL:-$(adb devices | awk '/\tdevice$/ {print $1; exit}')}"
|
||||
OUT_DIR="${SHEET_FOOTER_QA_DIR:-/tmp/paseo-sheet-footer-qa}"
|
||||
VIDEO_PATH="$OUT_DIR/sheet-footer-keyboard.mp4"
|
||||
|
||||
if [ -z "$SERIAL" ]; then
|
||||
echo "No Android device attached. Set ANDROID_SERIAL or start an emulator." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$OUT_DIR"
|
||||
|
||||
# Derive tap coordinates and 3-button navigation bar height (48dp) from the active display metrics.
|
||||
SIZE_LINE="$(adb -s "$SERIAL" shell wm size | tail -n 1 | tr -d '\r')"
|
||||
DIMENSIONS="${SIZE_LINE##* }"
|
||||
WIDTH="${DIMENSIONS%x*}"
|
||||
HEIGHT="${DIMENSIONS#*x}"
|
||||
DENSITY_LINE="$(adb -s "$SERIAL" shell wm density | tail -n 1 | tr -d '\r')"
|
||||
DENSITY="${DENSITY_LINE##* }"
|
||||
NAV_BAR_PX="${SHEET_FOOTER_NAV_BAR_PX:-$((48 * DENSITY / 160))}"
|
||||
SEARCH_X=$((WIDTH / 2))
|
||||
SEARCH_Y=$((HEIGHT * 34 / 100))
|
||||
|
||||
adb -s "$SERIAL" shell rm -f /sdcard/sheet-footer-keyboard.mp4
|
||||
adb -s "$SERIAL" shell screenrecord --time-limit 9 --bit-rate 8000000 /sdcard/sheet-footer-keyboard.mp4 &
|
||||
REC_PID=$!
|
||||
|
||||
sleep 0.8
|
||||
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
|
||||
sleep 1.8
|
||||
adb -s "$SERIAL" shell input keyevent 4
|
||||
sleep 1.8
|
||||
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
|
||||
sleep 1.8
|
||||
adb -s "$SERIAL" shell input keyevent 4
|
||||
wait "$REC_PID" || true
|
||||
|
||||
adb -s "$SERIAL" pull /sdcard/sheet-footer-keyboard.mp4 "$VIDEO_PATH" >/dev/null
|
||||
node "$SCRIPT_DIR/assert-sheet-footer-keyboard.mjs" "$VIDEO_PATH" 4 "$NAV_BAR_PX"
|
||||
@@ -17,7 +17,12 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { DraggableListHandle } from "@/components/draggable-list";
|
||||
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
|
||||
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import {
|
||||
bySizing,
|
||||
ICON_BUTTON_SIZES,
|
||||
mapLayout,
|
||||
TOUCH_TARGET,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -41,11 +46,16 @@ import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
|
||||
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
|
||||
export const ROSTER_COL_PROFILE_WIDTH = 184;
|
||||
export const ROSTER_COL_RUNTIME_WIDTH = 248;
|
||||
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
|
||||
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
|
||||
|
||||
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
|
||||
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
|
||||
const KEBAB_GLYPH_SIZE = ICON_SIZE.sm;
|
||||
// The kebab's hitbox is larger than its glyph; it overhangs the row so the glyph sits on the
|
||||
// card's trailing rail and the hitbox does not make the row taller.
|
||||
const KEBAB_HITBOX_OVERHANG = bySizing({
|
||||
touch: (ICON_BUTTON_SIZES.small.touch - KEBAB_GLYPH_SIZE) / 2,
|
||||
pointer: (ICON_BUTTON_SIZES.small.pointer - KEBAB_GLYPH_SIZE) / 2,
|
||||
});
|
||||
|
||||
const ThemedGripVertical = withUnistyles(GripVertical);
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
@@ -130,7 +140,7 @@ function AgentProfileRowMenu({
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
testID={`agent-profile-menu-${profileId}`}
|
||||
>
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
<DropdownMenuItem
|
||||
@@ -231,16 +241,9 @@ function AgentProfileRowContent({
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<View style={styles.stackedSpecLine}>
|
||||
<AgentProfileGlyph
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.stackedNotesText}
|
||||
@@ -372,8 +375,8 @@ export function AgentProfileRow({
|
||||
[dragging, isFirst, isHovered, menuProps.open, selected],
|
||||
);
|
||||
|
||||
const gripVisibilityStyle = useMemo(
|
||||
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
const gripStyle = useMemo(
|
||||
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
|
||||
[showRowAffordances],
|
||||
);
|
||||
const kebabVisibilityStyle = useMemo(
|
||||
@@ -399,22 +402,6 @@ export function AgentProfileRow({
|
||||
|
||||
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
|
||||
|
||||
{reorderable ? (
|
||||
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<DraggableListHandle
|
||||
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||
name: profile.name,
|
||||
})}
|
||||
style={styles.gripHandle}
|
||||
testID={`agent-profile-drag-${profile.id}`}
|
||||
>
|
||||
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||
</DraggableListHandle>
|
||||
</View>
|
||||
) : (
|
||||
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
|
||||
)}
|
||||
|
||||
<AgentProfileRowContent
|
||||
serverId={serverId}
|
||||
profile={profile}
|
||||
@@ -425,7 +412,8 @@ export function AgentProfileRow({
|
||||
isStacked={isStacked}
|
||||
/>
|
||||
|
||||
<View style={styles.trailing}>
|
||||
{/* A stacked row opens on tap like the wide one; the kebab alone ends it, on the trailing rail. */}
|
||||
<View style={isStacked ? styles.trailingStacked : styles.trailing}>
|
||||
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<AgentProfileRowMenu
|
||||
profileId={profile.id}
|
||||
@@ -442,13 +430,27 @@ export function AgentProfileRow({
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
</View>
|
||||
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevronRight
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
</View>
|
||||
{isStacked ? null : (
|
||||
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevronRight
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{reorderable ? (
|
||||
<DraggableListHandle
|
||||
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||
name: profile.name,
|
||||
})}
|
||||
style={gripStyle}
|
||||
testID={`agent-profile-drag-${profile.id}`}
|
||||
>
|
||||
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||
</DraggableListHandle>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -460,8 +462,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
minHeight: ROW_MIN_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
rowHovered: {
|
||||
@@ -491,19 +492,15 @@ const styles = StyleSheet.create((theme) => ({
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
gripSlot: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripSpacerCompact: {
|
||||
width: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripHandle: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
height: GRIP_HANDLE_HEIGHT,
|
||||
// The grip hangs in the row's leading padding, as on a Usage card, so the icon tile sits on the
|
||||
// card's rail with or without it and revealing it on hover moves nothing. It takes the padding's
|
||||
// full height so a finger finds it.
|
||||
grip: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
@@ -585,12 +582,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
stackedSpecLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
stackedSpecText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
@@ -609,6 +600,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
trailingStacked: {
|
||||
flexShrink: 0,
|
||||
marginRight: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
|
||||
marginVertical: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
|
||||
},
|
||||
kebabSlot: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
|
||||
@@ -44,7 +44,6 @@ import {
|
||||
AgentProfileRow,
|
||||
ROSTER_COL_PROFILE_WIDTH,
|
||||
ROSTER_COL_RUNTIME_WIDTH,
|
||||
ROSTER_GRIP_WIDTH,
|
||||
ROSTER_TRAILING_WIDTH,
|
||||
} from "./agent-profile-row";
|
||||
|
||||
@@ -90,7 +89,6 @@ function RosterTableHeader(): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.tableHeader}>
|
||||
<View style={styles.tableHeaderGripSpacer} />
|
||||
<View style={styles.tableHeaderColumns}>
|
||||
<Text style={[styles.tableHeaderText, styles.colProfileHeader]} numberOfLines={1}>
|
||||
{t("settings.host.agentProfiles.columns.profile")}
|
||||
@@ -1030,16 +1028,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
tableHeaderGripSpacer: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
flexShrink: 0,
|
||||
},
|
||||
tableHeaderColumns: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
|
||||
|
||||
describe("getCompactSheetSafeAreaPadding", () => {
|
||||
it("assigns safe clearance to the footer independently of decorative padding", () => {
|
||||
expect(
|
||||
getCompactSheetSafeAreaPadding({
|
||||
isCompact: true,
|
||||
isKeyboardVisible: false,
|
||||
hasFooter: true,
|
||||
safeAreaBottom: 34,
|
||||
}),
|
||||
).toEqual({ footerPaddingBottom: 34 });
|
||||
});
|
||||
|
||||
it("assigns safe clearance to the body only without a footer", () => {
|
||||
expect(
|
||||
getCompactSheetSafeAreaPadding({
|
||||
isCompact: true,
|
||||
isKeyboardVisible: false,
|
||||
hasFooter: false,
|
||||
safeAreaBottom: 34,
|
||||
}),
|
||||
).toEqual({ contentPaddingBottom: 34 });
|
||||
});
|
||||
|
||||
it("does not add a safe-area band above the compact keyboard", () => {
|
||||
expect(
|
||||
getCompactSheetSafeAreaPadding({
|
||||
isCompact: true,
|
||||
isKeyboardVisible: true,
|
||||
hasFooter: false,
|
||||
safeAreaBottom: 34,
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("does not inset desktop sheets", () => {
|
||||
expect(
|
||||
getCompactSheetSafeAreaPadding({
|
||||
isCompact: false,
|
||||
isKeyboardVisible: false,
|
||||
hasFooter: false,
|
||||
safeAreaBottom: 34,
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
export interface CompactSheetSafeAreaPaddingInput {
|
||||
isCompact: boolean;
|
||||
isKeyboardVisible: boolean;
|
||||
hasFooter: boolean;
|
||||
safeAreaBottom: number;
|
||||
}
|
||||
|
||||
export interface CompactSheetSafeAreaPadding {
|
||||
contentPaddingBottom?: number;
|
||||
footerPaddingBottom?: number;
|
||||
}
|
||||
|
||||
export function getCompactSheetSafeAreaPadding({
|
||||
isCompact,
|
||||
isKeyboardVisible,
|
||||
hasFooter,
|
||||
safeAreaBottom,
|
||||
}: CompactSheetSafeAreaPaddingInput): CompactSheetSafeAreaPadding {
|
||||
if (!isCompact || isKeyboardVisible || safeAreaBottom <= 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (hasFooter) {
|
||||
return { footerPaddingBottom: safeAreaBottom };
|
||||
}
|
||||
|
||||
return { contentPaddingBottom: safeAreaBottom };
|
||||
}
|
||||
@@ -20,12 +20,11 @@ import {
|
||||
IsolatedBottomSheetModal,
|
||||
SheetVisibleFrame,
|
||||
type ContextBridge,
|
||||
useBottomSheetSafeAreaPaddingStyle,
|
||||
useIsolatedBottomSheetVisibility,
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
|
||||
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
|
||||
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
|
||||
@@ -610,8 +609,9 @@ export interface SheetKeyboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
|
||||
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
|
||||
* The compact sheet's body. It renders on the far side of the sheet's portal so `SheetVisibleFrame`
|
||||
* and `useBottomSheetSafeAreaPaddingStyle` read the screen's bottom inset, not the one left where
|
||||
* the sheet was opened: inside a sheet tab, none is.
|
||||
*/
|
||||
function CompactSheetBody({
|
||||
header,
|
||||
@@ -619,7 +619,6 @@ function CompactSheetBody({
|
||||
onClose,
|
||||
testID,
|
||||
footer,
|
||||
isKeyboardVisible,
|
||||
scrollable,
|
||||
bodyStyle,
|
||||
contentStyle,
|
||||
@@ -630,32 +629,18 @@ function CompactSheetBody({
|
||||
onClose: () => void;
|
||||
testID?: string;
|
||||
footer: ReactNode;
|
||||
isKeyboardVisible: boolean;
|
||||
scrollable: boolean;
|
||||
bodyStyle?: StyleProp<ViewStyle>;
|
||||
contentStyle?: StyleProp<ViewStyle>;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
|
||||
isCompact: true,
|
||||
isKeyboardVisible,
|
||||
hasFooter: Boolean(footer),
|
||||
safeAreaBottom: insets.bottom,
|
||||
});
|
||||
// Safe-area clearance is a separate layer: it must not replace the caller's
|
||||
// padding (including an explicit zero), and the footer owns it when present.
|
||||
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
|
||||
const footerClearanceStyle = useMemo(
|
||||
() => ({ paddingBottom: footerPaddingBottom }),
|
||||
[footerPaddingBottom],
|
||||
);
|
||||
const footerView = useMemo(
|
||||
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
|
||||
[footer, footerClearanceStyle],
|
||||
);
|
||||
// Safe-area clearance is owned on the UI thread in lockstep with `SheetVisibleFrame`'s keyboard
|
||||
// height: `SheetVisibleFrame` pads the frame whenever a footer or non-scrollable body is shown,
|
||||
// while a scrollable body without a footer pads its scroll content so items scroll behind the
|
||||
// system bar and still clear it at rest.
|
||||
const bodyClearanceStyle = useBottomSheetSafeAreaPaddingStyle(scrollable && !footer);
|
||||
return (
|
||||
<SheetVisibleFrame footer={footerView}>
|
||||
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
|
||||
{header ? (
|
||||
<SheetHeaderView
|
||||
header={header}
|
||||
@@ -672,12 +657,12 @@ function CompactSheetBody({
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<View style={[styles.contentGrow, bodyClearanceStyle]}>
|
||||
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
|
||||
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
|
||||
</View>
|
||||
</Animated.View>
|
||||
</ScrollView>
|
||||
) : (
|
||||
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
|
||||
<View style={styles.compactStaticContent}>
|
||||
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
|
||||
{children}
|
||||
</SheetContent>
|
||||
@@ -710,7 +695,6 @@ export function AdaptiveModalSheet({
|
||||
}: AdaptiveModalSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const isKeyboardVisible = useKeyboardVisibility(visible);
|
||||
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
|
||||
const isSheet = isMobile || !isWeb;
|
||||
// The sheet registers itself; the desktop dialog does not use it.
|
||||
@@ -828,7 +812,6 @@ export function AdaptiveModalSheet({
|
||||
onClose={onClose}
|
||||
testID={testID}
|
||||
footer={footerView}
|
||||
isKeyboardVisible={isKeyboardVisible}
|
||||
scrollable={scrollable}
|
||||
bodyStyle={bodyStyle}
|
||||
contentStyle={contentStyle}
|
||||
|
||||
@@ -15,7 +15,7 @@ import DraggableFlatList, {
|
||||
} from "react-native-draggable-flatlist";
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { useContentDrag } from "@/components/ui/scroll-view";
|
||||
import { useContentDrag } from "@/components/ui/content-drag";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
|
||||
@@ -8,10 +8,15 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { BackHeader } from "@/components/headers/back-header";
|
||||
import { MenuHeader } from "@/components/headers/menu-header";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { withContentDrag } from "@/components/ui/content-drag";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
|
||||
|
||||
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
|
||||
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
|
||||
const PageScrollView =
|
||||
Platform.OS === "android"
|
||||
? withContentDrag(KeyboardAwareScrollView)
|
||||
: withContentDrag(ScrollView);
|
||||
|
||||
interface PageLayoutProps {
|
||||
title?: string;
|
||||
|
||||
@@ -66,12 +66,16 @@ function heightOf(testID: string): number {
|
||||
return element(testID).getBoundingClientRect().height;
|
||||
}
|
||||
|
||||
function titleFontSize(rowTestID: string, label: string): number {
|
||||
const title = [...element(rowTestID).querySelectorAll("div")].find(
|
||||
(node) => node.textContent === label && node.children.length === 0,
|
||||
function textNode(rowTestID: string, text: string): HTMLElement {
|
||||
const found = [...element(rowTestID).querySelectorAll("div")].find(
|
||||
(node) => node.textContent === text && node.children.length === 0,
|
||||
);
|
||||
if (!title) throw new Error(`No title ${label}`);
|
||||
return Number.parseFloat(getComputedStyle(title).fontSize);
|
||||
if (!found) throw new Error(`No text ${text}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
function titleFontSize(rowTestID: string, label: string): number {
|
||||
return Number.parseFloat(getComputedStyle(textNode(rowTestID, label)).fontSize);
|
||||
}
|
||||
|
||||
describe("settings row density", () => {
|
||||
@@ -100,4 +104,52 @@ describe("settings row density", () => {
|
||||
titleFontSize("card-row", "Card row"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a row with a long summary one line tall on a phone-width card", () => {
|
||||
container = document.createElement("div");
|
||||
// A 393pt phone less the sheet's side padding.
|
||||
container.style.width = "360px";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root?.render(
|
||||
<SettingsCard>
|
||||
<SettingsRow label="Text only" testID="text-row" />
|
||||
<SettingsCollapsibleRow
|
||||
label="Customize settings"
|
||||
summary="Auto mode · Medium · 2 features · Add a note for when to use it"
|
||||
testID="long-summary"
|
||||
>
|
||||
<SettingsRow label="Nested" />
|
||||
</SettingsCollapsibleRow>
|
||||
</SettingsCard>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(heightOf("long-summary-toggle")).toBe(heightOf("text-row"));
|
||||
});
|
||||
|
||||
it("keeps a short summary beside the chevron on a wide card", () => {
|
||||
container = document.createElement("div");
|
||||
container.style.width = "680px";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root?.render(
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label="Speech to text"
|
||||
summary="Local"
|
||||
onPress={openNothing}
|
||||
testID="short-summary"
|
||||
/>
|
||||
</SettingsCard>,
|
||||
),
|
||||
);
|
||||
|
||||
const row = element("short-summary").getBoundingClientRect();
|
||||
const summary = textNode("short-summary", "Local").getBoundingClientRect();
|
||||
// The summary's margin, the chevron and the row's padding: about 40px.
|
||||
expect(row.right - summary.right).toBeLessThan(48);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -88,9 +88,13 @@ export function SettingsRowHeader({
|
||||
const hovered = pointerOver && !disabled;
|
||||
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
|
||||
const chevronStyle = useMemo(
|
||||
() => [styles.chevron, expanded && styles.chevronExpanded],
|
||||
() => [styles.chevron, expanded && styles.chevronExpanded, styles.passThrough],
|
||||
[expanded],
|
||||
);
|
||||
// A hint can be a sentence, so a hinted row gives the room to the label column and caps the
|
||||
// summary. A label alone keeps its one-line width and the summary truncates in what is left.
|
||||
const hinted = Boolean(hint || hintStatus);
|
||||
const contentStyle = hinted ? settingsStyles.rowContent : styles.labelContent;
|
||||
return (
|
||||
<View
|
||||
style={rowStyle}
|
||||
@@ -113,7 +117,7 @@ export function SettingsRowHeader({
|
||||
{leading}
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[settingsStyles.rowContent, styles.passThrough]}>
|
||||
<View style={[contentStyle, styles.passThrough]}>
|
||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
{labelAccessory}
|
||||
@@ -128,28 +132,15 @@ export function SettingsRowHeader({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
{external ? (
|
||||
// Drawn the same as a section header's docs link, so the two read as one thing.
|
||||
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
|
||||
) : (
|
||||
<>
|
||||
{summary ? (
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
) : null}
|
||||
{disabled ? null : (
|
||||
<View style={chevronStyle}>
|
||||
<ThemedChevron
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
|
||||
{external || disabled ? null : (
|
||||
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevron
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -160,6 +151,32 @@ const HIDDEN_FROM_ASSISTIVE_TECH = {
|
||||
"aria-hidden": true,
|
||||
} as const;
|
||||
|
||||
/** The summary before the chevron, or the external link label in its place. */
|
||||
function RowTrailing({
|
||||
hinted,
|
||||
external,
|
||||
hovered,
|
||||
summary,
|
||||
}: {
|
||||
hinted: boolean;
|
||||
external: boolean;
|
||||
hovered: boolean;
|
||||
summary: string | undefined;
|
||||
}) {
|
||||
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
|
||||
return (
|
||||
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
|
||||
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
|
||||
{!external && summary ? (
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
|
||||
* does not move when its value arrives or its work starts. A long error is cut to the line; the
|
||||
@@ -222,10 +239,30 @@ const styles = StyleSheet.create((theme) => ({
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
trailing: {
|
||||
// The label keeps its one-line width and takes the free space; the summary truncates in what is
|
||||
// left. Any shrink, even a fraction of a pixel, would wrap the label, so it does not shrink. The
|
||||
// cap lets a long label wrap before it pushes the chevron off the row. Past the cap, the auto
|
||||
// margin takes the rest of the row, so the control, summary and chevron stay together at the end.
|
||||
labelContent: {
|
||||
flexGrow: 1,
|
||||
flexShrink: 0,
|
||||
maxWidth: "75%",
|
||||
paddingRight: theme.spacing[3],
|
||||
marginRight: "auto",
|
||||
},
|
||||
labelTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
// A hinted row's column grows from zero width, so an unbounded summary would squeeze it to
|
||||
// nothing and wrap the label one glyph per line. The summary keeps at most half the row.
|
||||
hintedTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
maxWidth: "50%",
|
||||
},
|
||||
hintLine: {
|
||||
flexDirection: "row",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
} from "react-native";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
@@ -1140,31 +1139,22 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
|
||||
* one left where the combobox was opened: inside a sheet tab, none is.
|
||||
* Rendered on the far side of the sheet's portal so `SheetVisibleFrame` clears the screen's
|
||||
* bottom inset in lockstep with the keyboard, not the inset left where the combobox was opened.
|
||||
*/
|
||||
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
|
||||
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
||||
const frameStyle = useMemo(
|
||||
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
|
||||
[footer, safeAreaBottom],
|
||||
);
|
||||
const footerStyle = useMemo(
|
||||
() => [styles.footer, { paddingBottom: safeAreaBottom }],
|
||||
[safeAreaBottom],
|
||||
);
|
||||
const footerView = useMemo(
|
||||
() =>
|
||||
footer ? (
|
||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
||||
<View style={styles.footer} dataSet={FOOTER_DATASET}>
|
||||
{footer}
|
||||
</View>
|
||||
) : undefined,
|
||||
[footer, footerStyle],
|
||||
[footer],
|
||||
);
|
||||
return (
|
||||
<SheetVisibleFrame footer={footerView}>
|
||||
<View style={frameStyle}>{children}</View>
|
||||
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
|
||||
<View style={styles.mobileSheetFrame}>{children}</View>
|
||||
</SheetVisibleFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import React, { act, Children, useCallback, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useContentDrag, withContentDrag } from "./content-drag";
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
interface FakeScrollProps {
|
||||
scrollEnabled?: boolean;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** Stands in for a scroll view: it reports the props a native scroll view would act on. */
|
||||
function FakeScroll({ scrollEnabled, children }: FakeScrollProps) {
|
||||
return (
|
||||
<div
|
||||
data-testid="scroll"
|
||||
data-scroll-enabled={String(scrollEnabled)}
|
||||
data-child-count={Children.toArray(children).length}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const DragHostScroll = withContentDrag<FakeScrollProps, unknown>(FakeScroll);
|
||||
|
||||
/** A row that holds a drag the way a draggable list does: active from press until release. */
|
||||
function DragRow() {
|
||||
const { setActive } = useContentDrag();
|
||||
const arm = useCallback(() => setActive(true), [setActive]);
|
||||
const release = useCallback(() => setActive(false), [setActive]);
|
||||
return (
|
||||
<>
|
||||
<button type="button" data-testid="arm" onClick={arm} />
|
||||
<button type="button" data-testid="release" onClick={release} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function mount(node: React.ReactElement) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(node));
|
||||
}
|
||||
|
||||
function scroll(): HTMLElement {
|
||||
const found = document.querySelector('[data-testid="scroll"]');
|
||||
if (!(found instanceof HTMLElement)) throw new Error("No scroll view rendered");
|
||||
return found;
|
||||
}
|
||||
|
||||
function press(testID: string) {
|
||||
const button = document.querySelector(`[data-testid="${testID}"]`);
|
||||
if (!(button instanceof HTMLElement)) throw new Error(`No ${testID}`);
|
||||
act(() => button.click());
|
||||
}
|
||||
|
||||
describe("withContentDrag", () => {
|
||||
it("stops the scroll while a child drag holds the touch, and resumes after", () => {
|
||||
mount(
|
||||
<DragHostScroll>
|
||||
<DragRow />
|
||||
</DragHostScroll>,
|
||||
);
|
||||
|
||||
expect(scroll().dataset.scrollEnabled).toBe("true");
|
||||
press("arm");
|
||||
expect(scroll().dataset.scrollEnabled).toBe("false");
|
||||
press("release");
|
||||
expect(scroll().dataset.scrollEnabled).toBe("true");
|
||||
});
|
||||
|
||||
it("keeps a scroll view the caller disabled disabled after the drag", () => {
|
||||
mount(
|
||||
<DragHostScroll scrollEnabled={false}>
|
||||
<DragRow />
|
||||
</DragHostScroll>,
|
||||
);
|
||||
|
||||
press("arm");
|
||||
press("release");
|
||||
expect(scroll().dataset.scrollEnabled).toBe("false");
|
||||
});
|
||||
|
||||
it("passes the children through as given, so sticky header indices still count them", () => {
|
||||
mount(
|
||||
<DragHostScroll>
|
||||
<div>Intro</div>
|
||||
<div>Section header</div>
|
||||
<DragRow />
|
||||
</DragHostScroll>,
|
||||
);
|
||||
|
||||
expect(scroll().dataset.childCount).toBe("3");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type ComponentType,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { AttachSheetContentDrag } from "./bottom-sheet-scope";
|
||||
|
||||
/**
|
||||
* What a child that drags inside a scroll view needs to keep the touch: `setActive(true)` stops
|
||||
* the scroll until the drag ends, so the scroll view cannot take the finger once the drag has
|
||||
* armed. Inside a sheet the child also registers its drag gesture through `attach` so the sheet's
|
||||
* pan waits for it; outside a sheet there is no `attach`. Outside any scroll view that hosts
|
||||
* content drags, `setActive` does nothing.
|
||||
*/
|
||||
export interface ContentDrag {
|
||||
attach: AttachSheetContentDrag | undefined;
|
||||
setActive: (active: boolean) => void;
|
||||
}
|
||||
|
||||
const ContentDragContext = createContext<ContentDrag | null>(null);
|
||||
|
||||
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
|
||||
|
||||
export function useContentDrag(): ContentDrag {
|
||||
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
|
||||
}
|
||||
|
||||
function useNoAttach(): AttachSheetContentDrag | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a scroll view host content drags: it stops scrolling while a child drag is active. Without
|
||||
* it, a vertical drag in a row of a scrolling page is taken by the page scroll once the finger
|
||||
* moves past the touch slop, before the row's drag gesture can activate. A sheet's scroll view
|
||||
* passes `useAttach` so its children can also register their gesture with the sheet.
|
||||
*
|
||||
* The context wraps the scroll view rather than its content, so the scroll view receives its
|
||||
* children as given: `stickyHeaderIndices` counts them.
|
||||
*/
|
||||
export function withContentDrag<P extends { scrollEnabled?: boolean }, T>(
|
||||
Scroll: ComponentType<P & { ref?: Ref<T> }>,
|
||||
useAttach: () => AttachSheetContentDrag | undefined = useNoAttach,
|
||||
) {
|
||||
return forwardRef<T, P>(function ContentDragScrollView(props, ref) {
|
||||
const attach = useAttach();
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
|
||||
// Overriding one prop of `P` keeps it a `P`; TypeScript cannot prove that for a generic.
|
||||
const scrollProps = {
|
||||
...props,
|
||||
scrollEnabled: !dragging && props.scrollEnabled !== false,
|
||||
} as P;
|
||||
return (
|
||||
<ContentDragContext.Provider value={contentDrag}>
|
||||
<Scroll {...scrollProps} ref={ref} />
|
||||
</ContentDragContext.Provider>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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) => {
|
||||
|
||||
@@ -212,6 +212,6 @@ export function useIsolatedBottomSheetVisibility({
|
||||
};
|
||||
}
|
||||
|
||||
export { SheetVisibleFrame } from "./visible-frame";
|
||||
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
|
||||
export { systemBackPress } from "./back-press";
|
||||
export { SheetHostScope } from "./host-scope";
|
||||
|
||||
+118
-1
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
||||
import {
|
||||
getBottomSheetSafeAreaPaddingBottom,
|
||||
getBottomSheetVisibleContentHeight,
|
||||
} from "./visible-frame-layout";
|
||||
|
||||
describe("getBottomSheetVisibleContentHeight", () => {
|
||||
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
|
||||
@@ -13,6 +16,120 @@ describe("getBottomSheetVisibleContentHeight", () => {
|
||||
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
|
||||
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
|
||||
});
|
||||
|
||||
it("ignores non-positive keyboard heights", () => {
|
||||
const layout = {
|
||||
containerHeight: 874,
|
||||
contentPosition: 88,
|
||||
handleHeight: 24,
|
||||
keyboardHeight: -10,
|
||||
isKeyboardVisible: true,
|
||||
};
|
||||
|
||||
expect(getBottomSheetVisibleContentHeight(layout)).toBe(762);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBottomSheetSafeAreaPaddingBottom", () => {
|
||||
it("keeps full safe-area clearance while the keyboard is hidden, even with retained keyboard height", () => {
|
||||
expect(
|
||||
getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: 344,
|
||||
isKeyboardVisible: false,
|
||||
safeAreaBottom: 48,
|
||||
}),
|
||||
).toBe(48);
|
||||
});
|
||||
|
||||
it("keeps full safe-area clearance during Gorhom's first-open frame before heightWithinContainer is populated", () => {
|
||||
expect(
|
||||
getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: 0,
|
||||
isKeyboardVisible: true,
|
||||
safeAreaBottom: 48,
|
||||
}),
|
||||
).toBe(48);
|
||||
});
|
||||
|
||||
it("drops safe-area clearance to 0 when the keyboard height covers the bottom safe area", () => {
|
||||
expect(
|
||||
getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: 344,
|
||||
isKeyboardVisible: true,
|
||||
safeAreaBottom: 48,
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves remaining safe-area clearance when keyboard height is smaller than the bottom inset", () => {
|
||||
expect(
|
||||
getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: 20,
|
||||
isKeyboardVisible: true,
|
||||
safeAreaBottom: 48,
|
||||
}),
|
||||
).toBe(28);
|
||||
});
|
||||
|
||||
it("returns 0 when there is no bottom safe-area inset", () => {
|
||||
expect(
|
||||
getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: 0,
|
||||
isKeyboardVisible: false,
|
||||
safeAreaBottom: 0,
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("holds the invariant that visible frame height + paddingBottom never places the footer inside the bottom safe area across keyboard open/close transitions", () => {
|
||||
const containerHeight = 1608;
|
||||
const contentPosition = 161;
|
||||
const handleHeight = 48;
|
||||
const safeAreaBottom = 96;
|
||||
const restingContentBottom = containerHeight - safeAreaBottom;
|
||||
|
||||
// Sequence matching real Android/iOS Gorhom keyboard transitions:
|
||||
// 1. Resting closed
|
||||
// 2. First open intermediate state (status=SHOWN before heightWithinContainer updates)
|
||||
// 3. Open settled (heightWithinContainer = 598)
|
||||
// 4. Close (status=HIDDEN while heightWithinContainer retains 598)
|
||||
// 5. Partial accessory bar (heightWithinContainer = 40 < safeAreaBottom)
|
||||
const transitions = [
|
||||
{ isKeyboardVisible: false, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
|
||||
{ isKeyboardVisible: true, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
|
||||
{
|
||||
isKeyboardVisible: true,
|
||||
keyboardHeight: 598,
|
||||
expectedContentBottom: containerHeight - 598,
|
||||
},
|
||||
{
|
||||
isKeyboardVisible: false,
|
||||
keyboardHeight: 598,
|
||||
expectedContentBottom: restingContentBottom,
|
||||
},
|
||||
{ isKeyboardVisible: true, keyboardHeight: 40, expectedContentBottom: restingContentBottom },
|
||||
];
|
||||
|
||||
for (const step of transitions) {
|
||||
const height = getBottomSheetVisibleContentHeight({
|
||||
containerHeight,
|
||||
contentPosition,
|
||||
handleHeight,
|
||||
keyboardHeight: step.keyboardHeight,
|
||||
isKeyboardVisible: step.isKeyboardVisible,
|
||||
});
|
||||
const paddingBottom = getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: step.keyboardHeight,
|
||||
isKeyboardVisible: step.isKeyboardVisible,
|
||||
safeAreaBottom,
|
||||
});
|
||||
// Inside a border-box frame at `contentPosition + handleHeight`, the bottom of the footer
|
||||
// sits at `contentPosition + handleHeight + height - paddingBottom`.
|
||||
const footerBottomY = contentPosition + handleHeight + height - paddingBottom;
|
||||
expect(footerBottomY).toBe(step.expectedContentBottom);
|
||||
expect(footerBottomY).toBeLessThanOrEqual(restingContentBottom);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface BottomSheetVisibleContentHeightInput {
|
||||
export interface BottomSheetVisibleContentHeightInput {
|
||||
containerHeight: number;
|
||||
contentPosition: number;
|
||||
lowestDetentPosition?: number;
|
||||
@@ -7,6 +7,28 @@ interface BottomSheetVisibleContentHeightInput {
|
||||
isKeyboardVisible: boolean;
|
||||
}
|
||||
|
||||
export interface BottomSheetSafeAreaPaddingInput {
|
||||
keyboardHeight: number;
|
||||
isKeyboardVisible: boolean;
|
||||
safeAreaBottom: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective keyboard height inside the sheet container.
|
||||
*
|
||||
* Gorhom retains `heightWithinContainer` after the keyboard hides, and on first show `status`
|
||||
* flips to `SHOWN` before its reaction writes `heightWithinContainer`. Treating both states as 0
|
||||
* keeps frame height and safe-area clearance in lockstep.
|
||||
*/
|
||||
export function getBottomSheetEffectiveKeyboardHeight(
|
||||
keyboardHeight: number,
|
||||
isKeyboardVisible: boolean,
|
||||
): number {
|
||||
"worklet";
|
||||
if (!isKeyboardVisible || keyboardHeight <= 0) return 0;
|
||||
return keyboardHeight;
|
||||
}
|
||||
|
||||
export function getBottomSheetVisibleContentHeight({
|
||||
containerHeight,
|
||||
contentPosition,
|
||||
@@ -18,8 +40,29 @@ export function getBottomSheetVisibleContentHeight({
|
||||
"worklet";
|
||||
if (containerHeight < 0 || handleHeight < 0) return 0;
|
||||
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
|
||||
return Math.max(
|
||||
0,
|
||||
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
|
||||
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
|
||||
keyboardHeight,
|
||||
isKeyboardVisible,
|
||||
);
|
||||
return Math.max(0, containerHeight - position - handleHeight - effectiveKeyboardHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bottom safe-area clearance derived from the same keyboard inset subtracted from
|
||||
* `SheetVisibleFrame`'s height so both update in one UI-thread commit.
|
||||
*
|
||||
* Invariant: `effectiveKeyboardHeight + paddingBottom >= safeAreaBottom`.
|
||||
*/
|
||||
export function getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight,
|
||||
isKeyboardVisible,
|
||||
safeAreaBottom,
|
||||
}: BottomSheetSafeAreaPaddingInput): number {
|
||||
"worklet";
|
||||
if (safeAreaBottom <= 0) return 0;
|
||||
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
|
||||
keyboardHeight,
|
||||
isKeyboardVisible,
|
||||
);
|
||||
return Math.max(0, safeAreaBottom - effectiveKeyboardHeight);
|
||||
}
|
||||
|
||||
@@ -2,21 +2,63 @@ import type { ReactNode } from "react";
|
||||
import { View, StyleSheet } from "react-native";
|
||||
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
|
||||
import Animated, { useAnimatedStyle } from "react-native-reanimated";
|
||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import {
|
||||
getBottomSheetSafeAreaPaddingBottom,
|
||||
getBottomSheetVisibleContentHeight,
|
||||
} from "./visible-frame-layout";
|
||||
|
||||
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
|
||||
/**
|
||||
* UI-thread bottom safe-area padding synchronized with Gorhom's keyboard state.
|
||||
* Use this for scrollable sheet bodies without a footer so content scrolls behind the system
|
||||
* navigation bar while still clearing it at rest and dropping the padding in lockstep with
|
||||
* `SheetVisibleFrame` when the keyboard opens or closes.
|
||||
*/
|
||||
export function useBottomSheetSafeAreaPaddingStyle(enabled = true) {
|
||||
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
||||
const { animatedKeyboardState } = useBottomSheetInternal();
|
||||
return useAnimatedStyle(() => {
|
||||
const keyboard = animatedKeyboardState.get();
|
||||
return {
|
||||
paddingBottom: enabled
|
||||
? getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
||||
safeAreaBottom,
|
||||
})
|
||||
: 0,
|
||||
};
|
||||
}, [animatedKeyboardState, enabled, safeAreaBottom]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap,
|
||||
* and frame height + bottom safe-area clearance update together in one UI-thread commit so the
|
||||
* footer never flashes behind the system navigation bar on keyboard show/hide.
|
||||
*/
|
||||
export function SheetVisibleFrame({
|
||||
children,
|
||||
footer,
|
||||
safeAreaInset = "footer",
|
||||
}: {
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
/**
|
||||
* Where bottom safe-area clearance is applied:
|
||||
* - `"footer"` (default): pads the frame whenever `footer` is present.
|
||||
* - `"frame"`: always pads the frame, with or without a footer.
|
||||
* - `"none"`: caller owns safe-area clearance.
|
||||
*/
|
||||
safeAreaInset?: "footer" | "frame" | "none";
|
||||
}) {
|
||||
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
||||
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
|
||||
useBottomSheetInternal();
|
||||
const padFrame = safeAreaInset === "frame" || (safeAreaInset === "footer" && Boolean(footer));
|
||||
const visibleStyle = useAnimatedStyle(() => {
|
||||
const { containerHeight, handleHeight } = animatedLayoutState.get();
|
||||
const keyboard = animatedKeyboardState.get();
|
||||
const isKeyboardVisible = keyboard.status === KEYBOARD_STATUS.SHOWN;
|
||||
return {
|
||||
height: getBottomSheetVisibleContentHeight({
|
||||
containerHeight,
|
||||
@@ -24,10 +66,24 @@ export function SheetVisibleFrame({
|
||||
contentPosition: animatedPosition.get(),
|
||||
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
||||
isKeyboardVisible,
|
||||
}),
|
||||
paddingBottom: padFrame
|
||||
? getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible,
|
||||
safeAreaBottom,
|
||||
})
|
||||
: 0,
|
||||
};
|
||||
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
|
||||
}, [
|
||||
animatedDetentsState,
|
||||
animatedKeyboardState,
|
||||
animatedLayoutState,
|
||||
animatedPosition,
|
||||
padFrame,
|
||||
safeAreaBottom,
|
||||
]);
|
||||
return (
|
||||
<Animated.View style={[styles.frame, visibleStyle]}>
|
||||
<View style={styles.body}>{children}</View>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
|
||||
import { forwardRef, type Ref } from "react";
|
||||
import {
|
||||
ScrollView as NativeScrollView,
|
||||
FlatList as NativeFlatList,
|
||||
@@ -12,15 +12,13 @@ import {
|
||||
type NativeViewGestureHandlerProps,
|
||||
} from "react-native-gesture-handler";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
useAttachSheetContentDrag,
|
||||
useIsInsideBottomSheet,
|
||||
type AttachSheetContentDrag,
|
||||
} from "./bottom-sheet-scope";
|
||||
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
|
||||
import { withContentDrag } from "./content-drag";
|
||||
|
||||
// Both libraries forward to the RN FlatList instance. Their published ref types
|
||||
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
|
||||
// disagree about getScrollResponder (Gorhom) and include the component function
|
||||
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
|
||||
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
|
||||
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
|
||||
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
||||
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
|
||||
@@ -30,7 +28,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
||||
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
function ScrollView(props, ref) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
|
||||
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
|
||||
if (props.horizontal) {
|
||||
return isNative ? (
|
||||
<GestureScrollView {...props} ref={ref} disallowInterruption />
|
||||
@@ -42,42 +40,11 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* What a child that drags inside a sheet needs to keep the touch: it registers its drag gesture
|
||||
* through `attach` so the sheet's pan waits for it, and `setActive(true)` stops the sheet's
|
||||
* scroll until the drag ends. Outside a sheet scroll there is no `attach` and `setActive` does
|
||||
* nothing.
|
||||
*/
|
||||
export interface ContentDrag {
|
||||
attach: AttachSheetContentDrag | undefined;
|
||||
setActive: (active: boolean) => void;
|
||||
}
|
||||
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
|
||||
|
||||
const ContentDragContext = createContext<ContentDrag | null>(null);
|
||||
|
||||
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
|
||||
|
||||
export function useContentDrag(): ContentDrag {
|
||||
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
|
||||
}
|
||||
|
||||
const SheetScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
function SheetScrollView(props, ref) {
|
||||
const attach = useAttachSheetContentDrag();
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
|
||||
return (
|
||||
<BottomSheetScrollView
|
||||
{...props}
|
||||
scrollEnabled={!dragging && props.scrollEnabled !== false}
|
||||
ref={ref}
|
||||
>
|
||||
<ContentDragContext.Provider value={contentDrag}>
|
||||
{props.children}
|
||||
</ContentDragContext.Provider>
|
||||
</BottomSheetScrollView>
|
||||
);
|
||||
},
|
||||
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
|
||||
SheetScroll,
|
||||
useAttachSheetContentDrag,
|
||||
);
|
||||
|
||||
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
|
||||
|
||||
const subscribe = (onStoreChange: () => void) => {
|
||||
const subscriptions = (["keyboardWillShow", "keyboardDidHide"] as const).map((event) =>
|
||||
KeyboardEvents.addListener(event, onStoreChange),
|
||||
);
|
||||
return () => {
|
||||
for (const subscription of subscriptions) {
|
||||
subscription.remove();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export function useKeyboardVisibility(enabled = true): boolean {
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => (enabled ? KeyboardController.isVisible() : false),
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export function useKeyboardVisibility(_enabled = true): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -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