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:
parent
dc7c60f723
commit
d44ba9bdfb
9 changed files with 558 additions and 66 deletions
|
|
@ -13,6 +13,7 @@
|
|||
"setup:kicad": "./scripts/setup-kicad-wasm.sh",
|
||||
"test:web": "npm run setup:kicad && playwright test --config=playwright-web.config.ts --project=firefox",
|
||||
"test:web:headed": "npm run setup:kicad && playwright test --config=playwright-web.config.ts --project=chromium --headed",
|
||||
"test:web:mobile": "npm run setup:kicad && playwright test --config=playwright-web.config.ts --project=mobile-chromium --headed",
|
||||
"test:kicad:firefox": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=firefox",
|
||||
"test:kicad:chrome": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=chromium --headed",
|
||||
"test:kicad": "npm run test:kicad:firefox",
|
||||
|
|
|
|||
131
tests/web/chrome-toggle.spec.ts
Normal file
131
tests/web/chrome-toggle.spec.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import { test, expect, type Browser, type Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Figma-like "hide UI" toggle e2e (desktop): Cmd/Ctrl+\ and the floating
|
||||
* button flip the editor between full UI and canvas-only, and a restore
|
||||
* brings back EXACTLY the chrome that was visible before — panes KiCad keeps
|
||||
* hidden by default (Search, Properties, …) must not appear. That last part
|
||||
* is asserted geometrically: the GAL canvas box after hide→show must equal
|
||||
* the pre-hide box (an over-shown panel would shrink the AUI center pane).
|
||||
*
|
||||
* Boots once (beforeAll) and runs the round trip over the shared page —
|
||||
* the config is workers:1 / fullyParallel:false, so file order holds.
|
||||
*/
|
||||
|
||||
const SCOPE = 'default';
|
||||
const FRONTEND_URL = process.env.WEB_APP_URL ?? 'http://localhost:3048';
|
||||
|
||||
let page: Page;
|
||||
/** Full-UI GAL canvas box captured before the first hide — the restore-exactness baseline. */
|
||||
let fullUiBox: { x: number; y: number; width: number; height: number };
|
||||
|
||||
/** Count of visible menubar titles (0 ⇒ menubar hidden). */
|
||||
async function visibleMenuTitles(pg: Page): Promise<number> {
|
||||
return pg.evaluate(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('.wx-menu-title')).filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0 && getComputedStyle(el).display !== 'none';
|
||||
}).length,
|
||||
);
|
||||
}
|
||||
|
||||
/** The visible GAL WebGL canvas box (same lookup as mobile-editor.spec.ts). */
|
||||
async function getGlBox(pg: Page): Promise<{ x: number; y: number; width: number; height: number }> {
|
||||
const id = await pg.evaluate(() => {
|
||||
const visible = Array.from(document.querySelectorAll('[id^="glcanvas-"]'))
|
||||
.map((c) => c as HTMLCanvasElement)
|
||||
.find((c) => {
|
||||
const rect = c.getBoundingClientRect();
|
||||
return window.getComputedStyle(c).display !== 'none' && rect.width > 0 && rect.height > 0;
|
||||
});
|
||||
return (visible ?? (document.querySelector('[id^="glcanvas-"]') as HTMLCanvasElement | null))?.id ?? null;
|
||||
});
|
||||
if (!id) throw new Error('No visible GL canvas found');
|
||||
const box = await pg.locator(`#${id}`).boundingBox();
|
||||
if (!box) throw new Error('GL canvas bounding box unavailable');
|
||||
return box;
|
||||
}
|
||||
|
||||
test.beforeAll(async ({ browser }: { browser: Browser }) => {
|
||||
test.setTimeout(420_000); // cold load: 136 MB wasm download + compile
|
||||
page = await browser.newPage({ baseURL: FRONTEND_URL });
|
||||
await page.goto(`/${SCOPE}/projects/demo/demo.kicad_pcb`);
|
||||
await expect(page.locator('#canvas')).toBeVisible({ timeout: 180000 });
|
||||
await expect
|
||||
.poll(() => page.title(), { timeout: 120000, intervals: [1000] })
|
||||
.toMatch(/demo — PCB Editor/i);
|
||||
// Loading overlays (boot + lib fat-load, both `inset-0 z-30`) must be gone
|
||||
// before geometry is trusted.
|
||||
await expect(page.locator('div.inset-0.z-30')).toHaveCount(0, { timeout: 180000 });
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await page?.close();
|
||||
});
|
||||
|
||||
test('Ctrl+\\ hides every non-canvas UI element; the canvas reclaims the viewport', async () => {
|
||||
test.setTimeout(120_000);
|
||||
const vp = page.viewportSize()!;
|
||||
|
||||
// full-UI baseline: menubar + console footer present, canvas NOT full-bleed
|
||||
expect(await visibleMenuTitles(page), 'menubar visible before hide').toBeGreaterThan(0);
|
||||
await expect(page.getByText(/console \(/)).toHaveCount(1);
|
||||
fullUiBox = await getGlBox(page);
|
||||
expect(fullUiBox.width, 'chrome occupies width before hide').toBeLessThan(vp.width * 0.95);
|
||||
|
||||
await page.keyboard.press('Control+\\');
|
||||
|
||||
await expect.poll(() => visibleMenuTitles(page), { timeout: 15000 }).toBe(0);
|
||||
await expect
|
||||
.poll(async () => (await getGlBox(page)).width, { timeout: 15000 })
|
||||
.toBeGreaterThan(vp.width * 0.95);
|
||||
expect((await getGlBox(page)).height, 'GL canvas height ≈ viewport').toBeGreaterThan(
|
||||
vp.height * 0.9,
|
||||
);
|
||||
// shell overlays follow the toggle…
|
||||
await expect(page.getByText(/console \(/)).toHaveCount(0);
|
||||
// …but the toggle button itself stays reachable
|
||||
await expect(page.locator('[data-testid="chrome-toggle"]')).toBeVisible();
|
||||
|
||||
await page.screenshot({ path: 'test-results/web-chrome-hidden.png', scale: 'css' });
|
||||
});
|
||||
|
||||
test('the floating button restores EXACTLY the pre-hide chrome (no over-shown panes)', async () => {
|
||||
test.setTimeout(120_000);
|
||||
|
||||
// still hidden from the previous test — restore via the button
|
||||
await page.locator('[data-testid="chrome-toggle"]').click();
|
||||
|
||||
await expect.poll(() => visibleMenuTitles(page), { timeout: 15000 }).toBeGreaterThan(0);
|
||||
await expect(page.getByText(/console \(/)).toHaveCount(1);
|
||||
|
||||
// The restored GAL canvas box must MATCH the pre-hide baseline: a blanket
|
||||
// Show(true) would also reveal KiCad's default-hidden panels (Search,
|
||||
// Properties, …), shrinking the AUI center pane and moving this box.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const b = await getGlBox(page);
|
||||
return (
|
||||
Math.abs(b.x - fullUiBox.x) <= 3 &&
|
||||
Math.abs(b.y - fullUiBox.y) <= 3 &&
|
||||
Math.abs(b.width - fullUiBox.width) <= 3 &&
|
||||
Math.abs(b.height - fullUiBox.height) <= 3
|
||||
);
|
||||
},
|
||||
{
|
||||
message: 'restored GL canvas box must equal the pre-hide baseline (over-shown pane?)',
|
||||
timeout: 15000,
|
||||
},
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
// hotkey round trip still works after a button toggle
|
||||
await page.keyboard.press('Control+\\'); // hide
|
||||
await expect.poll(() => visibleMenuTitles(page), { timeout: 15000 }).toBe(0);
|
||||
await page.keyboard.press('Control+\\'); // show
|
||||
await expect.poll(() => visibleMenuTitles(page), { timeout: 15000 }).toBeGreaterThan(0);
|
||||
|
||||
await page.screenshot({ path: 'test-results/web-chrome-restored.png', scale: 'css' });
|
||||
});
|
||||
|
|
@ -280,20 +280,24 @@ test('pan: one-finger drag translates the view (not a rubber-band select)', asyn
|
|||
expect(dBack, 'panning back returns near baseline').toBeLessThan(dPan / 3);
|
||||
});
|
||||
|
||||
test('editor is canvas-only: no menubar, GL canvas fills the viewport', async () => {
|
||||
await shot('chrome');
|
||||
|
||||
// The menubar is real DOM (.wx-menu-title per menu); AUI toolbars/panels are
|
||||
// canvas islands, so the GL-canvas-fills-viewport check below is what proves
|
||||
// THEY are gone (hidden AUI panes release their space to the center pane).
|
||||
const menus = await page.evaluate(
|
||||
/** Count of visible menubar titles (0 ⇒ menubar hidden). */
|
||||
async function visibleMenuTitles(pg: Page): Promise<number> {
|
||||
return pg.evaluate(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('.wx-menu-title')).filter((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0 && getComputedStyle(el).display !== 'none';
|
||||
}).length,
|
||||
);
|
||||
expect(menus, 'no visible menubar titles').toBe(0);
|
||||
}
|
||||
|
||||
test('editor is canvas-only: no menubar, GL canvas fills the viewport', async () => {
|
||||
await shot('chrome');
|
||||
|
||||
// The menubar is real DOM (.wx-menu-title per menu); AUI toolbars/panels are
|
||||
// canvas islands, so the GL-canvas-fills-viewport check below is what proves
|
||||
// THEY are gone (hidden AUI panes release their space to the center pane).
|
||||
expect(await visibleMenuTitles(page), 'no visible menubar titles').toBe(0);
|
||||
|
||||
// the drawing canvas reclaims the whole viewport
|
||||
const box = await getGlBox(page);
|
||||
|
|
@ -304,3 +308,30 @@ test('editor is canvas-only: no menubar, GL canvas fills the viewport', async ()
|
|||
// the shell's own persistent overlays are gone too
|
||||
expect(await page.getByText(/console \(/).count(), 'console toggle hidden').toBe(0);
|
||||
});
|
||||
|
||||
test('the floating toggle brings the full UI up and back off (Figma-like hide-UI)', async () => {
|
||||
// Canvas-only is the mobile DEFAULT, but the toggle must stay reachable.
|
||||
const toggle = page.locator('[data-testid="chrome-toggle"]');
|
||||
await expect(toggle, 'toggle button present in canvas-only mode').toBeVisible();
|
||||
|
||||
await toggle.tap();
|
||||
await expect
|
||||
.poll(() => visibleMenuTitles(page), { timeout: 15000 })
|
||||
.toBeGreaterThan(0);
|
||||
// console footer follows the toggle (full shell UI back)
|
||||
await expect(page.getByText(/console \(/)).toHaveCount(1);
|
||||
// chrome takes real estate again (side toolbars + layers panel eat width)
|
||||
const shown = await getGlBox(page);
|
||||
const vp = page.viewportSize()!;
|
||||
expect(shown.width, 'chrome reclaims width').toBeLessThan(vp.width * 0.95);
|
||||
await shot('toggle-shown');
|
||||
|
||||
// …and back to canvas-only, leaving the file in its baseline hidden state.
|
||||
await toggle.tap();
|
||||
await expect.poll(() => visibleMenuTitles(page), { timeout: 15000 }).toBe(0);
|
||||
await expect
|
||||
.poll(async () => (await getGlBox(page)).width, { timeout: 15000 })
|
||||
.toBeGreaterThan(vp.width * 0.95);
|
||||
expect(await page.getByText(/console \(/).count(), 'console toggle hidden again').toBe(0);
|
||||
await shot('toggle-rehidden');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@
|
|||
#ifdef __EMSCRIPTEN__
|
||||
#include <emscripten.h>
|
||||
#include <emscripten/bind.h>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <wx/app.h>
|
||||
|
|
@ -124,13 +125,34 @@ static bool kicadOpenFile( std::string path )
|
|||
}
|
||||
|
||||
|
||||
// Canvas-only mobile chrome toggle (features/mobile): hide/show every AUI pane
|
||||
// Canvas-only chrome toggle (features/mobile): hide/show every AUI pane
|
||||
// except the central draw canvas, plus the menubar and status bar, so the GAL
|
||||
// canvas fills the frame. Generic wxFrame/wxAui surface only (keeps this TU
|
||||
// header-light and serves both editor frames). Hidden bars release their space
|
||||
// because the wasm port's frame client-area math skips !IsShown() bars (native
|
||||
// parity, see wxwidgets/src/wasm/frame.cpp). Returns false until the editor
|
||||
// frame exists — main() builds it after runtime init — so JS polls this.
|
||||
|
||||
// Hide-time visibility snapshot. KiCad keeps several panes hidden by default
|
||||
// (Search, Properties, Net Inspector, …), so a blanket Show(true) on restore
|
||||
// would surface panes the user never had open — restore only what the hide
|
||||
// actually took away. Keyed to the frame so a snapshot never leaks onto a
|
||||
// different frame's wxAuiManager.
|
||||
static struct
|
||||
{
|
||||
wxFrame* frame = nullptr;
|
||||
bool valid = false;
|
||||
bool menuShown = false;
|
||||
bool statusShown = false;
|
||||
std::vector<wxString> paneNames;
|
||||
} s_chromeSnap;
|
||||
|
||||
static bool chromeSkipsPane( const wxAuiPaneInfo& aPane )
|
||||
{
|
||||
// keep the central editor canvas (named "DrawFrame" in both editors)
|
||||
return aPane.dock_direction == wxAUI_DOCK_CENTER || aPane.name == wxT( "DrawFrame" );
|
||||
}
|
||||
|
||||
static bool kicadSetChrome( bool aShow )
|
||||
{
|
||||
wxFrame* frame =
|
||||
|
|
@ -139,15 +161,50 @@ static bool kicadSetChrome( bool aShow )
|
|||
if( !frame )
|
||||
return false;
|
||||
|
||||
if( wxMenuBar* menuBar = frame->GetMenuBar() )
|
||||
menuBar->Show( aShow );
|
||||
wxMenuBar* menuBar = frame->GetMenuBar();
|
||||
wxStatusBar* statusBar = frame->GetStatusBar();
|
||||
wxAuiManager* mgr = wxAuiManager::GetManager( frame );
|
||||
|
||||
if( !aShow )
|
||||
{
|
||||
// A repeated hide keeps the original snapshot (idempotent).
|
||||
if( !s_chromeSnap.valid || s_chromeSnap.frame != frame )
|
||||
{
|
||||
s_chromeSnap.frame = frame;
|
||||
s_chromeSnap.menuShown = menuBar && menuBar->IsShown();
|
||||
s_chromeSnap.statusShown = statusBar && statusBar->IsShown();
|
||||
s_chromeSnap.paneNames.clear();
|
||||
|
||||
if( mgr )
|
||||
{
|
||||
wxAuiPaneInfoArray& panes = mgr->GetAllPanes();
|
||||
|
||||
for( size_t i = 0; i < panes.GetCount(); ++i )
|
||||
{
|
||||
wxAuiPaneInfo& pane = panes.Item( i );
|
||||
|
||||
if( !chromeSkipsPane( pane ) && pane.IsShown() )
|
||||
s_chromeSnap.paneNames.push_back( pane.name );
|
||||
}
|
||||
}
|
||||
|
||||
s_chromeSnap.valid = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A show with no snapshot (or one taken on a different frame) falls back
|
||||
// to revealing the standard chrome instead of obeying stale state.
|
||||
const bool haveSnap = s_chromeSnap.valid && s_chromeSnap.frame == frame;
|
||||
|
||||
if( menuBar )
|
||||
menuBar->Show( aShow && ( haveSnap ? s_chromeSnap.menuShown : true ) );
|
||||
|
||||
// Kept alive rather than detached: KiCad SetStatusText()s on every cursor
|
||||
// move, and wxFrameBase wxCHECKs a null status bar.
|
||||
if( wxStatusBar* statusBar = frame->GetStatusBar() )
|
||||
statusBar->Show( aShow );
|
||||
if( statusBar )
|
||||
statusBar->Show( aShow && ( haveSnap ? s_chromeSnap.statusShown : true ) );
|
||||
|
||||
if( wxAuiManager* mgr = wxAuiManager::GetManager( frame ) )
|
||||
if( mgr )
|
||||
{
|
||||
wxAuiPaneInfoArray& panes = mgr->GetAllPanes();
|
||||
|
||||
|
|
@ -155,16 +212,37 @@ static bool kicadSetChrome( bool aShow )
|
|||
{
|
||||
wxAuiPaneInfo& pane = panes.Item( i );
|
||||
|
||||
// keep the central editor canvas (named "DrawFrame" in both editors)
|
||||
if( pane.dock_direction == wxAUI_DOCK_CENTER || pane.name == wxT( "DrawFrame" ) )
|
||||
if( chromeSkipsPane( pane ) )
|
||||
continue;
|
||||
|
||||
pane.Show( aShow );
|
||||
if( !aShow )
|
||||
{
|
||||
pane.Show( false );
|
||||
}
|
||||
else if( haveSnap )
|
||||
{
|
||||
if( std::find( s_chromeSnap.paneNames.begin(), s_chromeSnap.paneNames.end(),
|
||||
pane.name )
|
||||
!= s_chromeSnap.paneNames.end() )
|
||||
{
|
||||
pane.Show( true );
|
||||
}
|
||||
}
|
||||
else if( pane.IsToolbar() )
|
||||
{
|
||||
// Show with no (or a stale, other-frame) snapshot: reveal the
|
||||
// toolbars only — blanket-showing plain panels would surface
|
||||
// the default-hidden ones.
|
||||
pane.Show( true );
|
||||
}
|
||||
}
|
||||
|
||||
mgr->Update();
|
||||
}
|
||||
|
||||
if( aShow )
|
||||
s_chromeSnap.valid = false;
|
||||
|
||||
frame->SendSizeEvent();
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
104
web/standalone/src/lib/chrome-visibility.test.ts
Normal file
104
web/standalone/src/lib/chrome-visibility.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
75
web/standalone/src/lib/chrome-visibility.ts
Normal file
75
web/standalone/src/lib/chrome-visibility.ts
Normal 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";
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
Loading…
Reference in a new issue