mirror of
https://github.com/expo/explore.git
synced 2026-11-15 13:18:16 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d238b3785 | ||
|
|
39225ea1d0 | ||
|
|
f276247860 | ||
|
|
91c16317dc | ||
|
|
1da81fb511 | ||
|
|
2c8795c896 | ||
|
|
558d396644 | ||
|
|
9a63514fc4 | ||
|
|
c6998a9c0d | ||
|
|
913a366ba2 | ||
|
|
0d7cbc0fa5 | ||
|
|
1057fd658f | ||
|
|
250a6ee182 | ||
|
|
cf890cd8e3 | ||
|
|
f7fa742abd | ||
|
|
c6005add19 | ||
|
|
90fff65588 | ||
|
|
20c99122c1 |
No files matched your search
+69
-1
@@ -4639,7 +4639,7 @@ test.describe("phone layout", () => {
|
||||
await page.goto("/map");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).tap();
|
||||
await page.keyboard.type("c");
|
||||
await expect(page.locator(".search-command-section-label")).toBeVisible();
|
||||
await expect(page.locator(".search-command-section-label").first()).toBeVisible();
|
||||
expect(await offScaleText(page, ".search-command")).toEqual([]);
|
||||
// iOS zooms into any field under 16px.
|
||||
expect(await page.locator(".search-command-input-row input").evaluate((element) => getComputedStyle(element).fontSize))
|
||||
@@ -5267,6 +5267,74 @@ test("/ finds screens on the Screens page: the tree and the grid narrow to the q
|
||||
await expect(page.getByRole("main", { name: "Screens" }).getByRole("searchbox", { name: "Find screens" })).toBeFocused();
|
||||
});
|
||||
|
||||
test("⌘K is a command palette: suggested commands lead, word queries rank commands first and run on Enter, route queries rank screens first", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/map");
|
||||
const mod = process.platform === "darwin" ? "Meta" : "Control";
|
||||
await page.keyboard.press(`${mod}+KeyK`);
|
||||
const palette = page.getByRole("dialog", { name: "Search Explore" });
|
||||
await expect(palette).toBeVisible();
|
||||
const box = palette.getByRole("combobox", { name: "Search screens and commands" });
|
||||
await expect(box).toBeFocused();
|
||||
|
||||
// The empty palette suggests what to do next on this canvas, not the screen inventory.
|
||||
const suggested = palette.getByRole("group", { name: "Suggested" });
|
||||
await expect(suggested.getByRole("option").filter({ hasText: "Next changed screen" })).toBeVisible();
|
||||
expect(await palette.getByRole("option").count()).toBeLessThanOrEqual(7);
|
||||
|
||||
// A word query ranks commands first; each prints the key that also runs it.
|
||||
await box.fill("dark");
|
||||
await expect(palette.getByRole("option").first()).toContainText("Theme: Dark");
|
||||
await box.fill("fit");
|
||||
const fit = palette.getByRole("option").filter({ hasText: "Fit the canvas" });
|
||||
await expect(fit).toBeVisible();
|
||||
await expect(fit.locator("kbd")).toBeVisible();
|
||||
|
||||
// Enter runs the command.
|
||||
await box.fill("dark");
|
||||
await box.press("Enter");
|
||||
await expect(palette).toHaveCount(0);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
|
||||
|
||||
// A route-shaped query ranks screens first, with the commands after them.
|
||||
await page.keyboard.press(`${mod}+KeyK`);
|
||||
await box.fill("/");
|
||||
await expect(palette.getByRole("option").first().locator("code")).toBeVisible();
|
||||
await expect(palette.getByRole("group", { name: "Screens" })).toBeVisible();
|
||||
|
||||
// A navigation command.
|
||||
await box.fill("screens");
|
||||
await expect(palette.getByRole("option").first()).toHaveText(/^Screens/);
|
||||
await box.press("Enter");
|
||||
await expect(page.getByRole("main", { name: "Screens" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("⌘K steps through its results in the order it shows them, and a command that opens a menu keeps it open", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/map");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).click();
|
||||
const palette = page.getByRole("dialog", { name: "Search Explore" });
|
||||
const box = palette.getByRole("combobox", { name: "Search screens and commands" });
|
||||
// "c" matches commands and screens alike: ↓ walks the rows top to bottom, across the sections.
|
||||
await box.fill("c");
|
||||
const options = palette.getByRole("option");
|
||||
const count = await options.count();
|
||||
expect(await palette.getByRole("group").count()).toBe(2);
|
||||
for (let step = 0; step < count; step += 1) {
|
||||
await expect(options.nth(step)).toHaveAttribute("aria-selected", "true");
|
||||
await expect(box).toHaveAttribute("aria-activedescendant", (await options.nth(step).getAttribute("id"))!);
|
||||
await box.press("ArrowDown");
|
||||
}
|
||||
await expect(options.first()).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
// The palette hands focus to the menu it opens instead of taking it back.
|
||||
await box.fill("Changed screens menu");
|
||||
await box.press("Enter");
|
||||
await expect(palette).toHaveCount(0);
|
||||
await expect(page.locator(".changes-menu")).toBeVisible();
|
||||
await expect(page.locator(".changes-menu-body")).toBeFocused();
|
||||
});
|
||||
|
||||
test("a / from the Map opens the find once: Screens opened again from the toolbar comes up without it", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/map");
|
||||
|
||||
@@ -65,3 +65,78 @@ test("empty queries and non-positive limits do not return an unbounded inventory
|
||||
assert.deepEqual(search.searchItems(items, "money", 0), []);
|
||||
assert.deepEqual(search.suggestedSearchItems(items, {}, 0), []);
|
||||
});
|
||||
|
||||
test("the palette ranks commands first for a word and screens first for a route, matching command keywords", () => {
|
||||
const items = [
|
||||
{ id: "screen:a", kind: "screen", title: "/settings/dark-mode", keywords: ["/settings/dark-mode"], context: "", order: 0, screenId: "a" },
|
||||
{ id: "command:theme", kind: "command", title: "Theme: Dark", keywords: ["theme", "appearance"], context: "View", order: 1, run() {} },
|
||||
{ id: "command:fit", kind: "command", title: "Fit the canvas", keywords: ["zoom"], context: "Canvas", order: 2, run() {} },
|
||||
];
|
||||
assert.deepEqual(search.searchItems(items, "dark").map((item) => item.id), ["command:theme", "screen:a"]);
|
||||
assert.deepEqual(search.searchItems(items, "/settings").map((item) => item.id), ["screen:a"]);
|
||||
const open = { id: "command:open", kind: "command", title: "Open /settings/dark-mode in Compare", keywords: [], context: "Changes", order: 3, run() {} };
|
||||
assert.deepEqual(search.searchItems([...items, open], "settings/dark").map((item) => item.id), ["screen:a", "command:open"]);
|
||||
assert.deepEqual(search.searchItems(items, "appearance").map((item) => item.id), ["command:theme"]);
|
||||
assert.deepEqual(search.searchItems(items, "zoom").map((item) => item.id), ["command:fit"]);
|
||||
|
||||
// A word that is a screen's last segment opens that screen; part of one still leads with the command.
|
||||
const theme = { id: "screen:theme", kind: "screen", title: "/settings/theme", keywords: ["/settings/theme"], context: "", order: 3, screenId: "theme" };
|
||||
assert.deepEqual(search.searchItems([...items, theme], "theme").map((item) => item.id), ["screen:theme", "command:theme"]);
|
||||
assert.deepEqual(search.searchItems([...items, theme], "Theme ").map((item) => item.id), ["screen:theme", "command:theme"]);
|
||||
assert.deepEqual(search.searchItems([...items, theme], "them").map((item) => item.id), ["command:theme", "screen:theme"]);
|
||||
});
|
||||
|
||||
test("the palette's commands follow the canvas: Compare steps changes with the arrows, the Map fits its camera, and suggestions lead with the next change", async () => {
|
||||
const { commandItems, suggestedCommands } = await tsImport("../../viewer/src/utils/commands.ts", import.meta.url);
|
||||
const calls = [];
|
||||
const actions = Object.fromEntries(["selectCanvas", "openFind", "openHandoff", "openShortcuts", "toggleChanges", "openChangedScreen", "setTheme", "chooseAppearance", "toggleInspector", "toggleFullscreen", "switchTarget", "zoom"]
|
||||
.map((name) => [name, (...args) => calls.push([name, ...args])]));
|
||||
const base = {
|
||||
phone: false, changed: [{ id: "a", route: "/a" }, { id: "b", route: "/b" }], selectedScreenId: "a", find: true, handoff: true,
|
||||
pullRequest: { number: 7, url: "https://github.com/expo/explore/pull/7" }, theme: "system", appearances: [], targets: [{ id: "android", label: "Pixel 8", platform: "android", place: 1, noun: "device" }], camera: true,
|
||||
};
|
||||
const map = commandItems({ ...base, canvas: "map", inspector: { open: false } }, actions);
|
||||
const ids = (items) => items.map((item) => item.id.replace(/^command:/, ""));
|
||||
assert.ok(ids(map).includes("camera:fit"));
|
||||
assert.ok(ids(map).includes("changes:open-selected"));
|
||||
assert.ok(ids(map).includes("link:repository"));
|
||||
assert.equal(map.find((item) => item.id === "command:changes:next").shortcut, undefined);
|
||||
assert.deepEqual(ids(suggestedCommands(map, "map")).slice(0, 3), ["changes:next", "changes:open-selected", "go:compare"]);
|
||||
map.find((item) => item.id === "command:changes:next").run();
|
||||
map.find((item) => item.id === "command:target:android").run();
|
||||
assert.deepEqual(calls, [["openChangedScreen", "b"], ["switchTarget", "android"]]);
|
||||
|
||||
const compare = commandItems({ ...base, canvas: "compare", camera: false }, actions);
|
||||
assert.ok(!ids(compare).includes("camera:fit"));
|
||||
assert.ok(!ids(compare).includes("changes:open-selected"));
|
||||
assert.ok(compare.find((item) => item.id === "command:changes:next").shortcut);
|
||||
assert.ok(!ids(compare).includes("go:compare"));
|
||||
assert.ok(ids(compare).includes("go:map"));
|
||||
|
||||
// A phone has no keyboard shortcuts to list.
|
||||
assert.ok(ids(map).includes("go:shortcuts"));
|
||||
assert.ok(!ids(commandItems({ ...base, canvas: "map", phone: true }, actions)).includes("go:shortcuts"));
|
||||
|
||||
// Next and Previous stop at the ends of the review, as Compare's arrows do.
|
||||
const last = commandItems({ ...base, canvas: "compare", camera: false, selectedScreenId: "b" }, actions);
|
||||
assert.ok(!ids(last).includes("changes:next"));
|
||||
assert.ok(ids(last).includes("changes:previous"));
|
||||
assert.ok(!ids(compare).includes("changes:previous"));
|
||||
const none = commandItems({ ...base, canvas: "map", selectedScreenId: undefined }, actions);
|
||||
assert.ok(ids(none).includes("changes:next") && ids(none).includes("changes:previous"));
|
||||
|
||||
// An app appearance is found by its own scheme, not the other one.
|
||||
const schemes = commandItems({ ...base, canvas: "map", appearances: [{ id: "light", label: "Light", current: true }, { id: "dark", label: "Dark", current: false }] }, actions);
|
||||
assert.deepEqual(search.searchItems(schemes, "dark").filter((item) => item.id.includes("appearance")).map((item) => item.id), ["command:view:appearance:dark"]);
|
||||
});
|
||||
|
||||
test("the palette finds a device by its own platform only", async () => {
|
||||
const { commandItems } = await tsImport("../../viewer/src/utils/commands.ts", import.meta.url);
|
||||
const actions = new Proxy({}, { get: () => () => {} });
|
||||
const items = commandItems({
|
||||
canvas: "map", phone: false, changed: [], find: true, handoff: false, theme: "system", appearances: [], camera: false,
|
||||
targets: [{ id: "duo-open", label: "iPhone Duo open", platform: "ios", place: 1, noun: "device" }, { id: "pixel", label: "Pixel 8", platform: "android", place: 2, noun: "device" }],
|
||||
}, actions);
|
||||
assert.deepEqual(search.searchItems(items, "android").map((item) => item.id), ["command:target:pixel"]);
|
||||
assert.deepEqual(search.searchItems(items, "ios").map((item) => item.id), ["command:target:duo-open"]);
|
||||
});
|
||||
+45
-3
@@ -11,7 +11,10 @@ import { CanvasVisibleFrameProvider } from "./components/canvas/visible-frame-pr
|
||||
import { AppLoading } from "./components/shared/app-loading";
|
||||
import { ReportLoadingShell } from "./components/shared/report-loading-shell";
|
||||
import { screenLabel } from "./utils/screen-path";
|
||||
import { AppPill, PLATFORM_NAMES, targetSwitch } from "./components/panels/app-pill";
|
||||
import { AppPill, PLATFORM_NAMES, runTargets, siblingReportUrl, targetSwitch } from "./components/panels/app-pill";
|
||||
import { useFullscreen } from "./components/panels/shell-actions";
|
||||
import { getCanvasZoomState, runCanvasZoomCommand } from "./utils/canvas-zoom";
|
||||
import { commandItems, suggestedCommands } from "./utils/commands";
|
||||
import { changedScreens, focusCounts as countFocusStatuses, isCapturedChange, type ChangedScreen } from "./utils/changed-screens";
|
||||
import { MapView } from "./components/views/semantic-map";
|
||||
import { RightPanel } from "./components/panels/right";
|
||||
@@ -327,6 +330,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
|
||||
const [findRequest, setFindRequest] = useState<number>();
|
||||
const clearFindRequest = useCallback(() => setFindRequest(undefined), []);
|
||||
const [shortcutsOpen, setShortcutsOpen] = useState(false);
|
||||
const [fullscreen, toggleFullscreen] = useFullscreen();
|
||||
// Compare steps through the changed screens in review order. Callbacks read it from a ref,
|
||||
// because they are created before the diff that produces it.
|
||||
const compareOrderRef = useRef<readonly ChangedScreen[]>([]);
|
||||
@@ -1558,6 +1562,44 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
|
||||
};
|
||||
const openHandoff = () => setHandoffOpen(true);
|
||||
handoffAvailableRef.current = Boolean(handoffInput);
|
||||
// ⌘K: the commands for this canvas, built while the palette is open, ahead of the screens in its search.
|
||||
const paletteCommands = searchOpen ? commandItems({
|
||||
canvas: route.canvas,
|
||||
phone,
|
||||
changed: compareOrder,
|
||||
selectedScreenId,
|
||||
find: !phone,
|
||||
handoff: Boolean(handoffInput),
|
||||
pullRequest: review?.pullRequest,
|
||||
theme: themePreference,
|
||||
appearances: appearances.length > 1 ? appearances.map((option) => ({ id: option, label: appearanceLabel(option), current: option === appearance })) : [],
|
||||
inspector: phone || comparingScreens ? undefined : { open: !rightCollapsed },
|
||||
fullscreen: !phone && typeof document.documentElement.requestFullscreen === "function" ? fullscreen : undefined,
|
||||
targets: (() => {
|
||||
const run = runTargets(map.run);
|
||||
const noun = run.targets.every((target) => target.id === target.platform) ? "platform" as const : "device" as const;
|
||||
const page = new URL(window.location.href);
|
||||
return run.targets.flatMap((target, place) => target.id !== run.current && siblingReportUrl(page, target.id) ? [{ id: target.id, label: target.label, platform: target.platform, place, noun }] : []);
|
||||
})(),
|
||||
camera: !phone && route.canvas === "map" && Boolean(getCanvasZoomState().api),
|
||||
}, {
|
||||
selectCanvas,
|
||||
openFind: () => { selectCanvas("screens"); setFindRequest((count) => (count ?? 0) + 1); },
|
||||
openHandoff,
|
||||
openShortcuts: () => setShortcutsOpen(true),
|
||||
toggleChanges: () => setChangesOpen((open) => !open),
|
||||
openChangedScreen,
|
||||
setTheme: setThemePreference,
|
||||
chooseAppearance,
|
||||
toggleInspector: toggleRightPanel,
|
||||
toggleFullscreen,
|
||||
switchTarget: (id) => {
|
||||
const url = siblingReportUrl(new URL(window.location.href), id);
|
||||
if (url && !REPORT_SOURCE.switchTarget(id, url)) window.location.assign(url);
|
||||
},
|
||||
zoom: (command) => runCanvasZoomCommand(command === "fit" && getCanvasZoomState().api?.hasSelection() ? "selection" : command),
|
||||
}) : [];
|
||||
const paletteSuggestions = [...suggestedCommands(paletteCommands, route.canvas), ...searchSuggestions.filter((item) => item.screenId === selectedScreenId)];
|
||||
const handoffAction = handoffInput ? <HandoffButton {...(phone ? { className: "collapsed-search" } : { tooltip: true })} onOpen={openHandoff} /> : null;
|
||||
|
||||
const viewer = (
|
||||
@@ -1682,8 +1724,8 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
|
||||
) : null}
|
||||
<SearchCommand
|
||||
open={searchOpen}
|
||||
items={searchIndex}
|
||||
suggestions={searchSuggestions}
|
||||
items={[...paletteCommands, ...searchIndex]}
|
||||
suggestions={paletteSuggestions}
|
||||
onClose={closeSearch}
|
||||
onSelectScreen={selectSearchScreen}
|
||||
/>
|
||||
|
||||
@@ -81,7 +81,7 @@ export function shortcutGroups(context: ShortcutContext): Group[][] {
|
||||
...(CANVAS_NUMBER_KEYS
|
||||
? [{ label: "The same, by their place in the toolbar", keys: sections.map((section) => SHORTCUTS.canvasByNumber[section]) }]
|
||||
: []),
|
||||
{ label: "Search screens", keys: [SHORTCUTS.app.search] },
|
||||
{ label: "Search screens and commands", keys: [SHORTCUTS.app.search] },
|
||||
{ label: "Find a screen on the Screens page", keys: ["/"] },
|
||||
...(context.handoff ? [{ label: "Hand off to AI", keys: [SHORTCUTS.app.handoff] }] : []),
|
||||
...(context.hasChanges ? [{ label: "Changed screens menu", keys: [SHORTCUTS.app.changes] }] : []),
|
||||
|
||||
@@ -1,15 +1,36 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { CornerDownLeft, Route, Search, X } from "lucide-react";
|
||||
import { searchItems, type SearchItem } from "../utils/search";
|
||||
import { Command, CornerDownLeft, Route, Search, X } from "lucide-react";
|
||||
import { searchItems, type SearchItem, type SearchItemKind } from "../utils/search";
|
||||
import { AutoHideScrollArea } from "./shared/auto-hide-scroll-area";
|
||||
import { useModalDialog } from "../hooks/use-modal-dialog";
|
||||
|
||||
const KIND_LABELS: Record<SearchItem["kind"], string> = {
|
||||
/** Screens are labelled; a command's key, or nothing, sits where the label would. */
|
||||
const KIND_LABELS: Record<SearchItemKind, string> = {
|
||||
screen: "Screen",
|
||||
command: "Command",
|
||||
};
|
||||
|
||||
function ResultIcon() {
|
||||
return <Route strokeWidth={1.75} />;
|
||||
function ResultIcon({ kind }: { kind: SearchItemKind }) {
|
||||
return kind === "screen" ? <Route strokeWidth={1.75} /> : <Command strokeWidth={1.75} />;
|
||||
}
|
||||
|
||||
/** The results grouped by kind, in the order the first result sets, so ↑ and ↓ step through the rows as they read. */
|
||||
function groupedByKind(results: readonly SearchItem[]): SearchItem[] {
|
||||
return [...new Set(results.map((item) => item.kind))].flatMap((kind) => results.filter((item) => item.kind === kind));
|
||||
}
|
||||
|
||||
/** Grouped results in their sections, with each item's place in the flat list. */
|
||||
function sections(results: readonly SearchItem[], suggested: boolean): { label: string; entries: { item: SearchItem; index: number }[] }[] {
|
||||
const byKind = new Map<SearchItemKind, { item: SearchItem; index: number }[]>();
|
||||
results.forEach((item, index) => {
|
||||
const entries = byKind.get(item.kind) ?? [];
|
||||
entries.push({ item, index });
|
||||
byKind.set(item.kind, entries);
|
||||
});
|
||||
return [...byKind].map(([kind, entries]) => ({
|
||||
label: kind === "command" ? (suggested ? "Suggested" : "Commands") : suggested ? "Selected screen" : "Screens",
|
||||
entries,
|
||||
}));
|
||||
}
|
||||
|
||||
type SearchCommandProps = {
|
||||
@@ -27,7 +48,7 @@ export function SearchCommand(props: SearchCommandProps) {
|
||||
const dialogRef = useModalDialog(props.open, props.onClose);
|
||||
const listboxId = useId();
|
||||
const results = useMemo(
|
||||
() => query.trim() ? searchItems(props.items, query) : [...props.suggestions],
|
||||
() => groupedByKind(query.trim() ? searchItems(props.items, query) : props.suggestions),
|
||||
[props.items, props.suggestions, query],
|
||||
);
|
||||
|
||||
@@ -59,8 +80,11 @@ export function SearchCommand(props: SearchCommandProps) {
|
||||
props.onClose();
|
||||
if (item.kind === "screen" && item.screenId) {
|
||||
props.onSelectScreen(item.screenId);
|
||||
} else if (item.kind === "command") {
|
||||
item.run?.();
|
||||
}
|
||||
};
|
||||
const suggested = !query.trim();
|
||||
|
||||
const moveActive = (delta: number) => {
|
||||
if (results.length === 0) return;
|
||||
@@ -85,7 +109,7 @@ export function SearchCommand(props: SearchCommandProps) {
|
||||
<input
|
||||
ref={inputRef}
|
||||
role="combobox"
|
||||
aria-label="Search screens"
|
||||
aria-label="Search screens and commands"
|
||||
aria-autocomplete="list"
|
||||
aria-expanded="true"
|
||||
aria-controls={listboxId}
|
||||
@@ -94,7 +118,7 @@ export function SearchCommand(props: SearchCommandProps) {
|
||||
: {})}
|
||||
autoComplete="off"
|
||||
spellCheck="false"
|
||||
placeholder="Search screens"
|
||||
placeholder="Search screens and commands"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
@@ -116,42 +140,46 @@ export function SearchCommand(props: SearchCommandProps) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="search-command-section-label">
|
||||
{query.trim() ? "Results" : "Suggested"}
|
||||
</div>
|
||||
{results.length > 0 ? (
|
||||
<AutoHideScrollArea
|
||||
id={listboxId}
|
||||
shellClassName="search-command-results-shell"
|
||||
className="search-command-results"
|
||||
role="listbox">
|
||||
{results.map((item, index) => (
|
||||
<button
|
||||
key={item.id}
|
||||
id={`${listboxId}-option-${index}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={activeIndex === index}
|
||||
className={`search-command-result${activeIndex === index ? " active" : ""}`}
|
||||
onPointerMove={() => setActiveIndex(index)}
|
||||
onClick={() => select(item)}>
|
||||
<span className={`search-command-result-icon result-${item.kind}`} aria-hidden="true">
|
||||
<ResultIcon />
|
||||
</span>
|
||||
<span className="search-command-result-copy">
|
||||
<strong>{item.kind === "screen" ? <code>{item.title}</code> : item.title}</strong>
|
||||
{item.context && <small>{item.context}</small>}
|
||||
</span>
|
||||
<span className="search-command-result-kind">{KIND_LABELS[item.kind]}</span>
|
||||
{activeIndex === index && <CornerDownLeft className="search-command-enter" aria-hidden="true" />}
|
||||
</button>
|
||||
{sections(results, suggested).map((section) => (
|
||||
<div key={section.label} className="search-command-section" role="group" aria-label={section.label}>
|
||||
<div className="search-command-section-label">{section.label}</div>
|
||||
{section.entries.map(({ item, index }) => (
|
||||
<button
|
||||
key={item.id}
|
||||
id={`${listboxId}-option-${index}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={activeIndex === index}
|
||||
className={`search-command-result${activeIndex === index ? " active" : ""}`}
|
||||
onPointerMove={() => setActiveIndex(index)}
|
||||
onClick={() => select(item)}>
|
||||
<span className={`search-command-result-icon result-${item.kind}`} aria-hidden="true">
|
||||
<ResultIcon kind={item.kind} />
|
||||
</span>
|
||||
<span className="search-command-result-copy">
|
||||
<strong>{item.kind === "screen" ? <code>{item.title}</code> : item.title}</strong>
|
||||
{item.context && <small>{item.context}</small>}
|
||||
</span>
|
||||
{item.shortcut
|
||||
? <kbd className="search-command-result-key">{item.shortcut}</kbd>
|
||||
: item.kind === "screen" ? <span className="search-command-result-kind">{KIND_LABELS[item.kind]}</span> : null}
|
||||
{activeIndex === index && <CornerDownLeft className="search-command-enter" aria-hidden="true" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</AutoHideScrollArea>
|
||||
) : (
|
||||
<div className="search-command-empty" role="status">
|
||||
<Search aria-hidden="true" />
|
||||
<strong>No results</strong>
|
||||
<span>Try another screen.</span>
|
||||
<span>Try a route, or a command such as “dark” or “fit”.</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,7 @@ const FOCUSABLE = [
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(", ");
|
||||
|
||||
/** Escape to close, Tab wrapped inside the dialog, focus restored to the opener. */
|
||||
/** Escape to close, Tab wrapped inside the dialog, focus restored to the opener unless what closed it moved focus on. */
|
||||
export function useModalDialog(open: boolean, onClose: () => void) {
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
const restoreFocusRef = useRef<Element | null>(null);
|
||||
@@ -17,6 +17,7 @@ export function useModalDialog(open: boolean, onClose: () => void) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
restoreFocusRef.current = document.activeElement;
|
||||
const dialog = dialogRef.current;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
if (event.key !== "Tab") return;
|
||||
@@ -36,7 +37,7 @@ export function useModalDialog(open: boolean, onClose: () => void) {
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
(restoreFocusRef.current as HTMLElement | null)?.focus?.();
|
||||
if (document.activeElement === document.body || dialog?.contains(document.activeElement)) (restoreFocusRef.current as HTMLElement | null)?.focus?.();
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
|
||||
@@ -2200,6 +2200,18 @@ code {
|
||||
line-height: 1.45;
|
||||
}
|
||||
.search-command-result-copy code { color: inherit; font-size: inherit; }
|
||||
.search-command-section + .search-command-section { margin-top: 4px; }
|
||||
.search-command-section > .search-command-section-label { padding: 8px 8px 4px; }
|
||||
.search-command-result-key {
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
color: var(--tertiary);
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.search-command-result-kind {
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { Appearance } from "./appearance";
|
||||
import type { CanvasView, ThemePreference } from "./navigation";
|
||||
import type { CanvasZoomCommand } from "./canvas-zoom";
|
||||
import type { SearchItem } from "./search";
|
||||
import { formatShortcut, SHORTCUTS, TARGET_NUMBER_KEYS } from "./shortcuts";
|
||||
|
||||
/** What the reader is looking at decides which commands the palette offers. */
|
||||
export type CommandContext = {
|
||||
canvas: CanvasView;
|
||||
phone: boolean;
|
||||
/** The changed screens in review order; empty without a baseline. */
|
||||
changed: readonly { id: string; route: string }[];
|
||||
selectedScreenId?: string | undefined;
|
||||
/** The Screens page has a find field (desktop). */
|
||||
find: boolean;
|
||||
/** The report can be handed off to an agent (a hosted preview). */
|
||||
handoff: boolean;
|
||||
pullRequest?: { origin?: "local" | "compare" | undefined; number?: number | undefined; url?: string | undefined } | undefined;
|
||||
theme: ThemePreference;
|
||||
/** The captured appearances, when there is more than one to show. */
|
||||
appearances: readonly { id: Appearance; label: string; current: boolean }[];
|
||||
/** The Inspector's state where it exists (not on Compare, not on a phone). */
|
||||
inspector?: { open: boolean } | undefined;
|
||||
/** Full screen's state where the browser supports it. */
|
||||
fullscreen?: boolean | undefined;
|
||||
/** The run's other targets this page can open, with their platform and their place in the targets menu. */
|
||||
targets: readonly { id: string; label: string; platform: string; place: number; noun: "device" | "platform" }[];
|
||||
/** A canvas camera is on screen (Map), so fit, center and zoom apply. */
|
||||
camera: boolean;
|
||||
};
|
||||
|
||||
export type CommandActions = {
|
||||
selectCanvas: (canvas: CanvasView) => void;
|
||||
openFind: () => void;
|
||||
openHandoff: () => void;
|
||||
openShortcuts: () => void;
|
||||
toggleChanges: () => void;
|
||||
openChangedScreen: (id: string) => void;
|
||||
setTheme: (theme: ThemePreference) => void;
|
||||
chooseAppearance: (appearance: Appearance) => void;
|
||||
toggleInspector: () => void;
|
||||
toggleFullscreen: () => void;
|
||||
switchTarget: (id: string) => void;
|
||||
zoom: (command: CanvasZoomCommand) => void;
|
||||
};
|
||||
|
||||
const THEME_TITLES: Record<ThemePreference, string> = { system: "Theme: Auto (system)", dark: "Theme: Dark", light: "Theme: Light" };
|
||||
|
||||
function repositoryOf(url: string | undefined): string | undefined {
|
||||
return /^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:pull\/\d+|compare\/.+)$/.exec(url ?? "")?.[1];
|
||||
}
|
||||
|
||||
function openLink(url: string): void {
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
|
||||
/**
|
||||
* The palette's commands for one context, as search items: each names its group as context and prints the key that
|
||||
* also runs it, so the list doubles as the shortcuts a reader can discover by typing.
|
||||
*/
|
||||
export function commandItems(context: CommandContext, actions: CommandActions): SearchItem[] {
|
||||
const items: SearchItem[] = [];
|
||||
const add = (id: string, group: string, title: string, run: () => void, options: { keywords?: string[]; shortcut?: string | undefined } = {}) => {
|
||||
items.push({ id: `command:${id}`, kind: "command", title, keywords: options.keywords ?? [], context: group, order: items.length, run,
|
||||
...(options.shortcut ? { shortcut: options.shortcut } : {}) });
|
||||
};
|
||||
const key = formatShortcut;
|
||||
const hasChanges = context.changed.length > 0;
|
||||
const selectedChange = context.changed.find((entry) => entry.id === context.selectedScreenId);
|
||||
|
||||
if (context.canvas !== "map") add("go:map", "Go to", "Map", () => actions.selectCanvas("map"), { keywords: ["canvas", "overview"], shortcut: key(SHORTCUTS.canvas.map) });
|
||||
if (context.canvas !== "screens") add("go:screens", "Go to", "Screens", () => actions.selectCanvas("screens"), { keywords: ["inventory", "grid", "list"], shortcut: key(SHORTCUTS.canvas.screens) });
|
||||
if (hasChanges && context.canvas !== "compare") add("go:compare", "Go to", "Compare", () => actions.selectCanvas("compare"), { keywords: ["review", "changes", "diff", "before", "after"], shortcut: key(SHORTCUTS.canvas.compare) });
|
||||
if (context.find) add("go:find", "Go to", "Find a screen", actions.openFind, { keywords: ["filter", "screens", "search"], shortcut: "/" });
|
||||
if (context.handoff) add("go:handoff", "Go to", "Hand off to AI", actions.openHandoff, { keywords: ["agent", "prompt", "claude", "codex", "copy"], shortcut: key(SHORTCUTS.app.handoff) });
|
||||
if (!context.phone) add("go:shortcuts", "Go to", "Keyboard shortcuts", actions.openShortcuts, { keywords: ["keys", "help"], shortcut: "?" });
|
||||
if (hasChanges && !context.phone) add("go:changes-menu", "Go to", "Changed screens menu", actions.toggleChanges, { keywords: ["changes", "list", "filter"], shortcut: key(SHORTCUTS.app.changes) });
|
||||
|
||||
if (hasChanges) {
|
||||
// The ends stop, as Compare's arrows do; with no change selected, the steps start from either end.
|
||||
const at = context.changed.findIndex((entry) => entry.id === context.selectedScreenId);
|
||||
const next = context.changed[at < 0 ? 0 : at + 1];
|
||||
const previous = context.changed[at < 0 ? context.changed.length - 1 : at - 1];
|
||||
const compare = context.canvas === "compare";
|
||||
if (next) add("changes:next", "Changes", "Next changed screen", () => actions.openChangedScreen(next.id),
|
||||
{ keywords: ["change", "step", "forward"], shortcut: compare ? key(SHORTCUTS.compare.nextScreen) : undefined });
|
||||
if (previous) add("changes:previous", "Changes", "Previous changed screen", () => actions.openChangedScreen(previous.id),
|
||||
{ keywords: ["change", "step", "back"], shortcut: compare ? key(SHORTCUTS.compare.previousScreen) : undefined });
|
||||
if (selectedChange && !compare) add("changes:open-selected", "Changes", `Open ${selectedChange.route} in Compare`, () => actions.selectCanvas("compare"), { keywords: ["selected", "review", "diff"] });
|
||||
}
|
||||
|
||||
if (context.inspector) {
|
||||
add("view:inspector", "View", context.inspector.open ? "Hide the inspector" : "Show the inspector", actions.toggleInspector,
|
||||
{ keywords: ["panel", "details", "sidebar"], shortcut: key(SHORTCUTS.panel.right) });
|
||||
}
|
||||
for (const theme of ["system", "dark", "light"] as const) {
|
||||
add(`view:theme:${theme}`, context.theme === theme ? "View · current" : "View", THEME_TITLES[theme], () => actions.setTheme(theme),
|
||||
{ keywords: ["theme", "appearance", "viewer", "color", "mode"] });
|
||||
}
|
||||
for (const appearance of context.appearances) {
|
||||
add(`view:appearance:${appearance.id}`, appearance.current ? "View · current" : "View", `App appearance: ${appearance.label}`, () => actions.chooseAppearance(appearance.id),
|
||||
{ keywords: ["app", "appearance", "scheme", "captured"], shortcut: !appearance.current && context.appearances.length === 2 ? key(SHORTCUTS.appearance.app) : undefined });
|
||||
}
|
||||
if (context.fullscreen !== undefined) {
|
||||
add("view:fullscreen", "View", context.fullscreen ? "Exit full screen" : "Enter full screen", actions.toggleFullscreen, { keywords: ["fullscreen", "window", "focus"] });
|
||||
}
|
||||
|
||||
for (const target of context.targets) {
|
||||
const numbered = TARGET_NUMBER_KEYS ? SHORTCUTS.targetByNumber[target.place] : undefined;
|
||||
add(`target:${target.id}`, target.noun === "device" ? "Devices" : "Platforms", `Switch to ${target.label}`, () => actions.switchTarget(target.id),
|
||||
{ keywords: [target.noun, "report", "switch", target.platform], shortcut: numbered ? key(numbered) : undefined });
|
||||
}
|
||||
|
||||
if (context.camera) {
|
||||
add("camera:fit", "Canvas", "Fit the canvas", () => actions.zoom("fit"), { keywords: ["zoom", "fit", "all"], shortcut: key(SHORTCUTS.camera.fit) });
|
||||
add("camera:center", "Canvas", "Center the canvas", () => actions.zoom("recenter"), { keywords: ["zoom", "center", "recenter"], shortcut: key(SHORTCUTS.camera.center) });
|
||||
add("camera:100", "Canvas", "Zoom to 100%", () => actions.zoom("100"), { keywords: ["zoom", "actual", "reset"], shortcut: key(SHORTCUTS.camera.zoom100) });
|
||||
add("camera:in", "Canvas", "Zoom in", () => actions.zoom("in"), { keywords: ["zoom", "closer"], shortcut: key(SHORTCUTS.camera.zoomIn) });
|
||||
add("camera:out", "Canvas", "Zoom out", () => actions.zoom("out"), { keywords: ["zoom", "away"], shortcut: key(SHORTCUTS.camera.zoomOut) });
|
||||
}
|
||||
|
||||
const pr = context.pullRequest;
|
||||
if (pr?.url) {
|
||||
const url = pr.url;
|
||||
const title = pr.origin === "compare" ? "Open the compare on GitHub" : pr.origin === "local" ? "Open the review on GitHub" : `Open pull request #${pr.number} on GitHub`;
|
||||
add("link:pull-request", "Links", title, () => openLink(url), { keywords: ["github", "pr", "pull request", "browser"] });
|
||||
const repository = repositoryOf(url);
|
||||
if (repository) add("link:repository", "Links", `Open ${repository} on GitHub`, () => openLink(`https://github.com/${repository}`), { keywords: ["github", "repo", "repository", "source"] });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The commands the empty palette leads with: what a reader on this canvas is most likely to do next. */
|
||||
export function suggestedCommands(items: readonly SearchItem[], canvas: CanvasView, limit = 6): SearchItem[] {
|
||||
const priority: Record<CanvasView, string[]> = {
|
||||
map: ["changes:next", "changes:open-selected", "go:compare", "camera:fit", "go:find", "go:handoff", "go:screens", "view:inspector"],
|
||||
screens: ["go:find", "changes:next", "changes:open-selected", "go:compare", "go:map", "go:handoff", "view:inspector"],
|
||||
compare: ["changes:next", "changes:previous", "go:map", "go:screens", "go:handoff", "go:shortcuts"],
|
||||
};
|
||||
return priority[canvas].flatMap((id) => items.filter((item) => item.id === `command:${id}`)).slice(0, limit);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Screen } from "../../../src/types";
|
||||
import { displayPathForScreen } from "./screen-path";
|
||||
|
||||
export type SearchItemKind = "screen";
|
||||
export type SearchItemKind = "screen" | "command";
|
||||
|
||||
export type SearchItem = {
|
||||
id: string;
|
||||
@@ -12,13 +12,19 @@ export type SearchItem = {
|
||||
order: number;
|
||||
route?: string;
|
||||
screenId?: string;
|
||||
/** Commands: the key that also runs it, printed, and what it does. */
|
||||
shortcut?: string;
|
||||
run?: () => void;
|
||||
};
|
||||
|
||||
export type SearchSuggestionContext = {
|
||||
screenId?: string;
|
||||
};
|
||||
|
||||
const KIND_ORDER: Record<SearchItemKind, number> = { screen: 0 };
|
||||
/** Route-shaped queries ("/settings", "settings/profile") are after a screen; words ("dark", "fit") are after a command. */
|
||||
function preferredKind(query: string): SearchItemKind {
|
||||
return query.includes("/") ? "screen" : "command";
|
||||
}
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value.trim().toLocaleLowerCase().replace(/\s+/g, " ");
|
||||
@@ -26,10 +32,13 @@ export function normalizeSearchText(value: string): string {
|
||||
|
||||
function resultScore(item: SearchItem, query: string): number | undefined {
|
||||
const title = normalizeSearchText(item.title);
|
||||
// A word that is a screen's last segment ("theme" for /settings/theme) names that screen, ahead of any command.
|
||||
if (item.kind === "screen" && title.split("/").filter(Boolean).pop() === query) return -1;
|
||||
if (title === query) return 0;
|
||||
if (title.startsWith(query)) return 1;
|
||||
if (title.split(/[^\p{L}\p{N}]+/u).some((word) => word.startsWith(query))) return 2;
|
||||
if (title.includes(query)) return 3;
|
||||
if (item.keywords.some((keyword) => normalizeSearchText(keyword).includes(query))) return 4;
|
||||
if (item.route && normalizeSearchText(item.route).includes(query)) return 4;
|
||||
return undefined;
|
||||
}
|
||||
@@ -41,6 +50,8 @@ export function searchItems(
|
||||
): SearchItem[] {
|
||||
const query = normalizeSearchText(rawQuery);
|
||||
if (!query || limit <= 0) return [];
|
||||
const preferred = preferredKind(query);
|
||||
const kindOrder = (item: SearchItem) => (item.kind === preferred ? 0 : 1);
|
||||
return items
|
||||
.flatMap((item) => {
|
||||
const score = resultScore(item, query);
|
||||
@@ -48,7 +59,7 @@ export function searchItems(
|
||||
})
|
||||
.sort((left, right) => (
|
||||
left.score - right.score
|
||||
|| KIND_ORDER[left.item.kind] - KIND_ORDER[right.item.kind]
|
||||
|| kindOrder(left.item) - kindOrder(right.item)
|
||||
|| left.item.order - right.item.order
|
||||
|| left.item.title.localeCompare(right.item.title)
|
||||
|| left.item.id.localeCompare(right.item.id)
|
||||
|
||||
Reference in new issue
Block a user