feat(mobile): Figma-like hide-UI toggle — Cmd/Ctrl+\ hotkey + floating button, snapshot-exact chrome restore

Chrome visibility is now a runtime toggle on any device instead of being
device-wired: mobile defaults to canvas-only, desktop to full UI, and the
floating top-right button (or Figma's Cmd/Ctrl+\ chord — free in KiCad,
only bare \ is bound) flips between them live.

- chrome-visibility.ts: module-global store (default isMobileMode(),
  session-only) + pure hotkey matcher (rejects AltGr backslash + repeats)
- WasmTool: capture-phase hotkey (stopped before the wx layer), floating
  toggle pill (matches the comment FAB design), useLayoutEffect apply with
  sync first call + retry; overlays follow the toggle, capability-gated on
  the kicad_editor bundle's kicadSetChrome export
- boot.ts mobile opt now installs touch gestures only
- kicadSetChrome: frame-keyed hide-time snapshot so restore re-shows ONLY
  what hide took away (blanket Show(true) surfaced KiCad's default-hidden
  Search/Properties/Net-Inspector panes); toolbars-only fallback otherwise
- tests: chrome-toggle.spec.ts (desktop hide/restore + geometric
  restore-exactness ±3px), mobile toggle round-trip, 12 new unit tests,
  test:web:mobile npm script

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Istvan Matejcsok 2026-07-09 16:11:19 +02:00
commit d44ba9bdfb
9 changed files with 558 additions and 66 deletions

View file

@ -1,12 +1,13 @@
import { Route, Routes } from "react-router-dom";
import { VersionBadge } from "@/components/VersionBadge";
import { isMobileMode } from "@/lib/mobile-mode";
import { useChromeHidden } from "@/lib/chrome-visibility";
import { HomePage } from "@/pages/HomePage";
import { LibToolPage } from "@/pages/LibToolPage";
import { ProjectView } from "@/pages/ProjectView";
import { ToolPage } from "@/pages/ToolPage";
export default function App() {
const chromeHidden = useChromeHidden();
return (
<>
<Routes>
@ -19,8 +20,8 @@ export default function App() {
<Route path="/:scope/libs/:name" element={<LibToolPage />} />
</Routes>
{/* Version + source link, bottom-right on every route (home + editor).
Mobile mode is canvas-only no persistent overlays. */}
{!isMobileMode() && <VersionBadge />}
Keys off the Figma-like hide-UI toggle (hidden is the mobile default). */}
{!chromeHidden && <VersionBadge />}
</>
);
}

View file

@ -14,7 +14,7 @@ import {
type KicadDoc,
type Tool,
} from "@pcbjam/shared";
import { ChevronDown, ChevronUp, Loader2 } from "lucide-react";
import { ChevronDown, ChevronUp, EyeOff, Loader2, PanelsTopLeft } from "lucide-react";
import {
currentScope,
libsSourceConfig,
@ -84,10 +84,30 @@ import { MemoryExhaustedDialog } from "@/recovery/MemoryExhaustedDialog";
import type { SourceDescriptor } from "@/lib/project-source-shared";
import { SourceChip } from "@/components/SourceChip";
import { isMobileMode } from "@/lib/mobile-mode";
import {
isChromeToggleHotkey,
toggleChromeHidden,
useChromeHidden,
} from "@/lib/chrome-visibility";
// Tools with the v2 items bridge (kicadCollabSnapshotItems/ApplyItems embind exports).
const COLLAB_TOOLS = new Set<Tool>(["pl_editor", "eeschema", "pcbnew"]);
// Chrome (editor UI) toggle: only the merged kicad_editor bundle exports
// kicadSetChrome (gerbview/calculator/pl_editor don't) — everything about the
// toggle is feature-gated on the export being there.
function chromeSetter(win: Window): ((show: boolean) => boolean) | null {
const fn = (win as { Module?: { kicadSetChrome?: unknown } }).Module
?.kicadSetChrome;
return typeof fn === "function" ? (fn as (show: boolean) => boolean) : null;
}
// Tooltip only — the matcher accepts both chords on any platform.
const CHROME_HOTKEY_LABEL =
typeof navigator !== "undefined" && /Mac/i.test(navigator.platform)
? "⌘\\"
: "Ctrl+\\";
// Which library item kind each tool browses — drives the load-screen pre-sync
// (warm the right bundles into IDB while the wasm downloads). Tools that don't
// browse a library are omitted (no pre-sync).
@ -690,9 +710,13 @@ export function WasmTool({
}) {
const containerRef = React.useRef<HTMLDivElement>(null);
const startedRef = React.useRef(false);
// Canvas-only mobile mode (features/mobile): the shell hides its persistent
// overlays, boot installs the touch-gesture shim + hides the editor chrome.
// Mobile device (features/mobile): boot installs the touch-gesture shim.
// Chrome/overlay visibility is the separate runtime toggle below.
const mobileUi = React.useMemo(() => isMobileMode(), []);
// Figma-like "hide UI" toggle: mobile defaults to hidden, the floating
// button / Cmd+\ flips it live; shell overlays key off this, and the layout
// effect below applies it to the wasm frame.
const chromeHidden = useChromeHidden();
const driftRef = React.useRef<{ stop(): void } | null>(null);
const presenceRef = React.useRef<PresenceHandle | null>(null);
const presenceBridgeRef = React.useRef<{ destroy(): void } | null>(null);
@ -979,6 +1003,18 @@ export function WasmTool({
};
win.addEventListener("keydown", swallowBrowserSave, true);
// Cmd/Ctrl+\ (Figma's hide-UI chord) is ours alone: unlike Cmd+S it must
// NOT reach the wx layer, so also stop propagation — capture on window
// fires before wx's bubble-phase window listeners (wasm/app.cpp).
const chromeHotkey = (e: KeyboardEvent) => {
if (!isChromeToggleHotkey(e)) return;
if (!chromeSetter(win)) return; // bundle without the export
e.preventDefault();
e.stopImmediatePropagation();
toggleChromeHidden();
};
win.addEventListener("keydown", chromeHotkey, true);
void (async () => {
try {
// Resolve the per-tool asset base at runtime (CDN manifest → versioned
@ -1173,6 +1209,7 @@ export function WasmTool({
return () => {
win.removeEventListener("keydown", swallowBrowserSave, true);
win.removeEventListener("keydown", chromeHotkey, true);
commentsRef.current?.destroy();
commentsRef.current = null;
presenceBridgeRef.current?.destroy();
@ -1196,6 +1233,49 @@ export function WasmTool({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tool, slug, assetBaseUrl, append]);
// kicadSetChrome, once the editor is up (null on bundles without it).
const setChromeFn = React.useMemo(
() => (ready ? chromeSetter(window) : null),
[ready],
);
// Apply the chrome-visibility state to the wasm frame. A LAYOUT effect with
// a synchronous first attempt: `ready` unmounts the opaque boot overlay in
// this same commit, and a passive effect would let one frame of full chrome
// paint on mobile. appliedRef skips the initial "shown" apply — never
// relayout a frame this component never hid.
const appliedRef = React.useRef<boolean | null>(null);
React.useLayoutEffect(() => {
if (!setChromeFn) return;
if (appliedRef.current === chromeHidden) return;
if (appliedRef.current === null && !chromeHidden) return;
const apply = () => {
try {
return setChromeFn(!chromeHidden) === true;
} catch (err) {
append(`[chrome] kicadSetChrome failed: ${String(err)}`);
return true; // don't retry a throwing binding
}
};
if (apply()) {
appliedRef.current = chromeHidden;
return;
}
// The editor frame can lag `ready` (waitForWxUi falls through after 25 s)
// — retry briefly rather than dropping the toggle.
const t0 = Date.now();
const tick = window.setInterval(() => {
if (apply()) {
appliedRef.current = chromeHidden;
window.clearInterval(tick);
} else if (Date.now() - t0 > 30_000) {
window.clearInterval(tick);
}
}, 300);
return () => window.clearInterval(tick);
}, [setChromeFn, chromeHidden, append]);
return (
<div className="relative h-screen w-screen overflow-hidden bg-[#1a1a2e]">
{/*
@ -1312,19 +1392,35 @@ export function WasmTool({
</div>
)}
{/* Top-right overlay chips: who else is in this file (awareness roster) +
where this project lives / whether Save persists (chip hidden in
canvas-only mobile mode). */}
{ready && (peers.length > 0 || (sourceDescriptor && !mobileUi)) && (
<div className="absolute right-3 top-3 z-20 flex items-center gap-2">
{peers.length > 0 && (
<PresenceRoster peers={peers} activeSheetPath={activeSheetPath} />
)}
{sourceDescriptor && !mobileUi && (
<SourceChip descriptor={sourceDescriptor} />
)}
</div>
)}
{/* Top-right overlay row: who else is in this file (awareness roster),
where this project lives / whether Save persists (chip hidden while
the UI is hidden), and the Figma-like hide/show-UI toggle the one
control that stays up in canvas-only mode. */}
{ready &&
(setChromeFn !== null ||
peers.length > 0 ||
(sourceDescriptor && !chromeHidden)) && (
<div className="absolute right-3 top-3 z-20 flex items-center gap-2">
{peers.length > 0 && (
<PresenceRoster peers={peers} activeSheetPath={activeSheetPath} />
)}
{sourceDescriptor && !chromeHidden && (
<SourceChip descriptor={sourceDescriptor} />
)}
{setChromeFn !== null && (
<button
data-testid="chrome-toggle"
aria-pressed={chromeHidden}
// same pill design as the comment-bar toggle below it
className="flex h-8 min-w-8 items-center justify-center rounded-full bg-black/70 text-white shadow-sm ring-1 ring-inset ring-white/20 hover:bg-black/85"
title={`${chromeHidden ? "Show" : "Hide"} UI (${CHROME_HOTKEY_LABEL})`}
onClick={() => toggleChromeHidden()}
>
{chromeHidden ? <PanelsTopLeft size={15} /> : <EyeOff size={15} />}
</button>
)}
</div>
)}
{/* Figma-like comments (0005): GAL pin dots + this DOM layer (hit targets,
thread popovers, comment mode, panel). */}
@ -1373,7 +1469,7 @@ export function WasmTool({
</button>
)}
{!mobileUi && (
{!chromeHidden && (
<div className="absolute bottom-0 left-0 right-0 z-20">
<button
className="flex items-center gap-1 bg-black/70 px-3 py-1 font-mono text-xs text-white"

View file

@ -0,0 +1,104 @@
import { afterEach, describe, expect, it } from "vitest";
import {
getChromeHidden,
isChromeToggleHotkey,
resetChromeHiddenForTests,
setChromeHidden,
subscribeChromeHidden,
toggleChromeHidden,
} from "./chrome-visibility";
/**
* Chrome-visibility store (features/mobile, Figma-like "hide UI" toggle):
* module-global hidden/shown state every shell consumer shares, defaulting to
* the device signal (isMobileMode) and toggled at runtime by the floating
* button / Cmd+\ hotkey. Plus the pure hotkey matcher.
*/
afterEach(() => resetChromeHiddenForTests());
describe("chrome-visibility store", () => {
it("defaults via device detection (desktop-like test env → shown)", () => {
// node env has no window: the lazy default must resolve to "not hidden"
// rather than crash on the missing global.
expect(getChromeHidden()).toBe(false);
});
it("set + toggle flip the state", () => {
setChromeHidden(true);
expect(getChromeHidden()).toBe(true);
toggleChromeHidden();
expect(getChromeHidden()).toBe(false);
toggleChromeHidden();
expect(getChromeHidden()).toBe(true);
});
it("notifies subscribers on every change, in subscription order", () => {
const seen: string[] = [];
subscribeChromeHidden(() => seen.push(`a:${getChromeHidden()}`));
subscribeChromeHidden(() => seen.push(`b:${getChromeHidden()}`));
setChromeHidden(true);
toggleChromeHidden();
expect(seen).toEqual(["a:true", "b:true", "a:false", "b:false"]);
});
it("does not notify on a no-op set", () => {
setChromeHidden(false); // resolves the lazy default to false
let calls = 0;
subscribeChromeHidden(() => calls++);
setChromeHidden(false);
expect(calls).toBe(0);
});
it("unsubscribe stops notifications", () => {
let calls = 0;
const off = subscribeChromeHidden(() => calls++);
setChromeHidden(true);
off();
setChromeHidden(false);
expect(calls).toBe(1);
});
});
describe("isChromeToggleHotkey", () => {
const key = (over: Partial<Parameters<typeof isChromeToggleHotkey>[0]>) => ({
key: "\\",
code: "Backslash",
metaKey: false,
ctrlKey: false,
altKey: false,
repeat: false,
...over,
});
it("accepts Ctrl+\\ and Cmd+\\", () => {
expect(isChromeToggleHotkey(key({ ctrlKey: true }))).toBe(true);
expect(isChromeToggleHotkey(key({ metaKey: true }))).toBe(true);
});
it("accepts the physical Backslash key even when the layout maps it elsewhere", () => {
// e.g. HU layout: physical US-backslash key produces "ű"
expect(isChromeToggleHotkey(key({ ctrlKey: true, key: "ű" }))).toBe(true);
});
it("accepts a layout-produced backslash on a different physical key", () => {
expect(isChromeToggleHotkey(key({ ctrlKey: true, code: "IntlBackslash" }))).toBe(true);
});
it("rejects bare \\ (that's KiCad's Decrease Via Size)", () => {
expect(isChromeToggleHotkey(key({}))).toBe(false);
});
it("rejects AltGr-produced backslash (ctrl+alt while typing \\ in a field)", () => {
expect(isChromeToggleHotkey(key({ ctrlKey: true, altKey: true }))).toBe(false);
});
it("rejects key auto-repeat (held hotkey must not strobe the layout)", () => {
expect(isChromeToggleHotkey(key({ ctrlKey: true, repeat: true }))).toBe(false);
});
it("rejects other ctrl shortcuts", () => {
expect(isChromeToggleHotkey(key({ ctrlKey: true, key: "s", code: "KeyS" }))).toBe(false);
});
});

View file

@ -0,0 +1,75 @@
/**
* Chrome (editor UI) visibility the Figma-like "hide UI" toggle state
* (features/mobile).
*
* One module-global boolean every shell consumer shares: WasmTool applies it
* to the wasm frame (kicadSetChrome), the floating button and the Cmd+\ /
* Ctrl+\ hotkey flip it, and the shell overlays (version badge, source chip,
* console toggle) key their visibility off it.
*
* Session semantics, like Figma: nothing is persisted a reload restores the
* device default (isMobileMode: mobile hidden, desktop shown; `?mobile=`
* still forces it). Being module-global the toggled state survives SPA
* navigation (e.g. editor Home keeps the badge hidden); tool switches are
* full page loads, so in practice that only affects Home.
*/
import { useSyncExternalStore } from "react";
import { isMobileMode } from "./mobile-mode";
// Resolved lazily so merely importing the module never touches `window`
// (unit tests run in the node environment).
let hidden: boolean | null = null;
const listeners = new Set<() => void>();
export function getChromeHidden(): boolean {
hidden ??= typeof window === "undefined" ? false : isMobileMode();
return hidden;
}
export function setChromeHidden(value: boolean): void {
if (value === getChromeHidden()) return;
hidden = value;
for (const listener of [...listeners]) listener();
}
export function toggleChromeHidden(): void {
setChromeHidden(!getChromeHidden());
}
/** Returns the unsubscriber. */
export function subscribeChromeHidden(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function useChromeHidden(): boolean {
return useSyncExternalStore(subscribeChromeHidden, getChromeHidden);
}
/** Test-only: back to the unresolved default, all subscribers dropped. */
export function resetChromeHiddenForTests(value: boolean | null = null): void {
hidden = value;
listeners.clear();
}
/**
* The Figma "hide UI" shortcut: Cmd+\ (mac) / Ctrl+\. Free in KiCad only
* BARE `\` is bound (Decrease Via Size, pcbnew), no modifier+backslash
* anywhere. Matches by key OR physical code so it works on layouts where `\`
* moved (or the Backslash key produces something else). Rejects altKey
* because AltGr-typed `\` (HU/DE layouts) reports ctrl+alt — typing a
* backslash into a text field must not toggle the UI and rejects repeats so
* holding the chord doesn't strobe full AUI relayouts.
*/
export function isChromeToggleHotkey(e: {
key: string;
code: string;
metaKey: boolean;
ctrlKey: boolean;
altKey: boolean;
repeat: boolean;
}): boolean {
if (!(e.metaKey || e.ctrlKey) || e.altKey || e.repeat) return false;
return e.key === "\\" || e.code === "Backslash" || e.code === "IntlBackslash";
}

View file

@ -78,9 +78,10 @@ export interface BootOptions {
* `--frame=<token>` in `Module.arguments`; parsed in single_top.cpp. Omitted
* the bundle's build-time default frame. See `TOOL_FRAME` in constants.ts. */
frame?: string;
/** Canvas-only mobile mode (features/mobile): install the touch-gesture shim
* (pinch-zoom / one-finger pan / tap-select) on the input canvas and hide the
* editor chrome (toolbars/panels/menubar) once the frame is up. */
/** Mobile device (features/mobile): install the touch-gesture shim
* (pinch-zoom / one-finger pan / tap-select) on the input canvas. Gestures
* only chrome visibility is owned by the shell's chrome-visibility store
* (WasmTool applies it via kicadSetChrome). */
mobile?: boolean;
}
@ -468,32 +469,6 @@ async function doBoot(opts: BootOptions): Promise<void> {
log("[boot] runtime initialized");
const canvas = (w.Module as { canvas?: HTMLCanvasElement }).canvas;
if (canvas) canvas.style.display = "block";
if (opts.mobile) {
// Hide the editor chrome (toolbars/panels/menubar) so the canvas fills
// the frame. kicadSetChrome (embind) returns false until the editor
// frame exists — main() builds it after runtime init — so poll.
const mod = w.Module as unknown as {
kicadSetChrome?: (show: boolean) => boolean;
};
const t0 = Date.now();
const tick = setInterval(() => {
let hidden = false;
try {
hidden = mod.kicadSetChrome?.(false) === true;
} catch (err) {
log(`[boot] mobile: kicadSetChrome failed: ${String(err)}`);
clearInterval(tick);
return;
}
if (hidden) {
log("[boot] mobile: editor chrome hidden");
clearInterval(tick);
} else if (Date.now() - t0 > 120_000) {
log("[boot] mobile: gave up waiting for the editor frame");
clearInterval(tick);
}
}, 300);
}
onStatus("");
},
// Resolve wasm + pthread worker against the asset base, not the SPA route.