Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Top bar: one button per menu, hover intent and smooth switching

Adarshc72f80947f2c
diff --git a/package.json b/package.json
index 9f7cb420..964b9c41 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
"test:e2e:shell": "node tests/e2e/shell.mjs",
"test:e2e:mega-menus": "node tests/e2e/mega-menus.mjs",
+ "test:e2e:bar-menus": "node tests/e2e/bar-menus.mjs",
"test:e2e:tabs": "node tests/e2e/instant-tabs.mjs",
"test:e2e:motion": "node tests/e2e/motion.mjs",
"test:e2e:tab-rows": "node tests/e2e/tab-rows.mjs",
diff --git a/src/app/motion.css b/src/app/motion.css
index 9a37f10a..1a6861bb 100644
--- a/src/app/motion.css
+++ b/src/app/motion.css
@@ -148,21 +148,121 @@
}
}
-/* ----- The bar's grouped menus (Studios, Apps, Motions & effects, Canvas): utility menus, so they are quick. The
- panel drops in from the bar and its columns follow 20 ms apart (3 steps at most: every column reads by 260 ms). It
- goes at once when it closes, so a menu that replaces it (data-switched, which just appears) never overlaps it. ----- */
-:is(#studios-launcher, [data-mega-panel]) {
- --tw-duration: var(--motion-base);
- --tw-ease: var(--ease-enter);
- --tw-enter-translate-y: calc(var(--motion-d2) * -1);
+/* ----- The top bar's menus (bar-menus.tsx): quick utility motion, transitions only (never keyframes), so a change of
+ mind half-way turns back from where it is and a fast glide never restarts anything.
+ Big panels (Studios, Apps, Motions & effects, Canvas) sit on one shared sheet under the bar ([data-mega-stage]):
+ the sheet comes down from the bar (8 px, base, enter) and goes back up (4 px, fast, exit); between two panels its
+ bottom edge moves to the new height (transform only, base, standard) while the old content leaves sideways (fast,
+ exit) and the new one comes in from the side the pointer went, a stagger later: every switch ends by 240 ms. The
+ columns follow 20 ms apart on a fresh open (3 steps at most: every column reads by 260 ms), never on a switch.
+ Cards (Create, More) grow in from their item (scale 0.97, 4 px) and shrink out (0.98, fast, exit).
+ data-phase: open | exit (inert, still painted) | gone (hidden). Under reduced motion every token is 0. ----- */
+[data-mega-panel] {
--launcher-step: calc(var(--motion-stagger) * 0.5);
+ --enter-delay: 0ms;
+ opacity: 0;
+ translate: var(--exit-x, 0px) var(--exit-y, calc(var(--motion-d1) * -1));
+ pointer-events: none;
+ transition:
+ opacity var(--motion-fast) var(--ease-exit),
+ translate var(--motion-fast) var(--ease-exit);
+ &[hidden] { display: none; }
+ &[data-phase="open"] {
+ opacity: 1;
+ translate: 0 0;
+ pointer-events: auto;
+ transition:
+ opacity var(--motion-base) var(--ease-enter) var(--enter-delay),
+ translate var(--motion-base) var(--ease-enter) var(--enter-delay);
+ }
+ /* The one in front during a switch is the new one; the old one fades under it. */
+ &[data-phase="exit"] { z-index: 0; }
+ &[data-phase="open"] { z-index: 1; }
+ &[data-phase="open"][data-enter="fresh"] [data-col] { animation: motion-rise-near var(--motion-base) var(--ease-enter) backwards; }
+ &[data-phase="open"][data-enter="fresh"] [data-col="1"] { animation-delay: var(--launcher-step); }
+ &[data-phase="open"][data-enter="fresh"] [data-col="2"] { animation-delay: calc(var(--launcher-step) * 2); }
+ &[data-phase="open"][data-enter="fresh"] :is([data-col="3"], [data-col="4"], [data-col="5"], [data-col="6"], [data-col="7"], [data-col="8"]) { animation-delay: calc(var(--launcher-step) * 3); }
+ /* A menu still loading: its skeleton shows only after a moment (most loads finish first). */
+ & [data-mega-skeleton] { animation: motion-fade var(--motion-fast) var(--ease-enter) 150ms backwards; }
+}
+@starting-style {
+ [data-mega-panel][data-phase="open"] {
+ opacity: 0;
+ translate: var(--enter-x, 0px) var(--enter-y, calc(var(--motion-d2) * -1));
+ }
+}
+[data-mega-stage] {
+ & [data-mega-backdrop] { translate: 0 calc(var(--panel-h, 0px) - 100%); }
+ &[data-morph] [data-mega-backdrop] { transition: translate var(--motion-base) var(--ease-standard); }
+ & [data-mega-sheet] {
+ opacity: 0;
+ translate: 0 calc(var(--motion-d1) * -1);
+ transition:
+ opacity var(--motion-fast) var(--ease-exit),
+ translate var(--motion-fast) var(--ease-exit);
+ }
+ &[data-open] [data-mega-sheet] {
+ opacity: 1;
+ translate: 0 0;
+ transition:
+ opacity var(--motion-base) var(--ease-enter),
+ translate var(--motion-base) var(--ease-enter);
+ }
+}
+[data-bar-card] {
+ transform-origin: top left;
+ opacity: 0;
+ scale: var(--motion-scale-out);
+ pointer-events: none;
+ transition:
+ opacity var(--motion-fast) var(--ease-exit),
+ scale var(--motion-fast) var(--ease-exit),
+ translate var(--motion-fast) var(--ease-exit);
&[hidden] { display: none; }
- &:not([hidden]) [data-col] { animation: motion-rise-near var(--motion-base) var(--ease-enter) backwards; }
- &:not([hidden]) [data-col="1"] { animation-delay: var(--launcher-step); }
- &:not([hidden]) [data-col="2"] { animation-delay: calc(var(--launcher-step) * 2); }
- &:not([hidden]) :is([data-col="3"], [data-col="4"], [data-col="5"], [data-col="6"], [data-col="7"], [data-col="8"]) { animation-delay: calc(var(--launcher-step) * 3); }
- &[data-switched] [data-col] { animation: none; }
+ &[data-phase="open"] {
+ opacity: 1;
+ scale: 1;
+ translate: 0 0;
+ pointer-events: auto;
+ transition:
+ opacity var(--motion-base) var(--ease-enter),
+ scale var(--motion-base) var(--ease-enter),
+ translate var(--motion-base) var(--ease-enter);
+ }
+}
+@starting-style {
+ [data-bar-card][data-phase="open"] {
+ opacity: 0;
+ scale: var(--motion-scale-in);
+ translate: 0 calc(var(--motion-d1) * -1);
+ }
+}
+/* The open item's highlight (BarIndicator): it shows in place, slides from item to item (translate, and scale from the
+ old item's width: transform only), fades out last. */
+[data-bar-indicator] {
+ background-color: var(--nav-hi);
+ transform-origin: left center;
+ opacity: 0;
+ transition: opacity var(--motion-fast) var(--ease-exit);
+ &[data-on] { opacity: 1; transition: none; }
+ &[data-on][data-slide] {
+ transition:
+ translate var(--motion-base) var(--ease-standard),
+ scale var(--motion-base) var(--ease-standard);
+ }
+}
+/* The dimmed page under any open menu: in with the menu, out only once nothing has been open a moment (a switch never
+ fades it). Half the overlay's strength: the page stays as context for a menu that opens on hover. */
+[data-bar-scrim] {
+ opacity: 0;
+ transition: opacity var(--motion-fast) var(--ease-exit) 120ms;
+ &[data-open] { opacity: 0.5; transition: opacity var(--motion-base) var(--ease-standard); }
}
+/* The bar and an open big panel read as one surface: the bar's bottom line steps aside. */
+[data-top-bar]:has([data-mega-stage][data-open]) { border-bottom-color: transparent; }
+/* The chevron turns while its menu is open (a transition, so a reversal mid-turn starts from where it is). */
+[data-bar-chevron] { transition: transform var(--motion-base) var(--ease-standard); }
+[data-bar-menu][data-open] [data-bar-chevron] { transform: rotate(180deg); }
/* ----- Toasts (sonner, top centre): in from just above, out quicker; the stack moves on the standard curve. ----- */
[data-sonner-toaster] [data-sonner-toast] {
diff --git a/src/app/nav-states.css b/src/app/nav-states.css
index e0346897..99272d5b 100644
--- a/src/app/nav-states.css
+++ b/src/app/nav-states.css
@@ -13,8 +13,9 @@
* pressed --nav-press fill while the mouse button or finger is down (no grey tap flash).
* current the open page: never a fill. A 3 px --nav-mark pip (.nav-mark-start on rows,
* .nav-mark-under on bar items and tiles), the icon in --nav-mark, the label semibold.
- * open a bar trigger whose menu is open: foreground words and the turned chevron, never a fill (the menu's
- * highlighted row is the one fill on screen).
+ * open a bar item whose menu is open: foreground words, the turned chevron, and the bar's one open highlight
+ * behind it ([data-bar-indicator], --nav-hi: the same colour as hover, so hover to open shows no step).
+ * It slides from item to item as the open menu changes; meanwhile the items' own hover fill steps aside.
* disabled aria-disabled=true / data-disabled (Radix "", cmdk "true") / :disabled: 45 % opacity, no
* highlight, no press.
*
@@ -114,19 +115,10 @@ html:not([data-input="pointer"]) .nav-focus-out:focus-visible {
.nav-mark-start:is(.nav-row[aria-current="page"], .nav-row[data-current]) > svg:first-child {
color: var(--nav-mark);
}
-/* A split bar item (a name and a chevron: Create, Studios, Motions & effects): the pip sits under the whole pill, as under
- a plain item with a chevron, inside the area or on its own page. */
-[data-bar-split].nav-mark-under:is([data-active], :has(> [aria-current="page"]))::before {
- content: "";
- position: absolute;
- bottom: 3px;
- left: 50%;
- width: 16px;
- height: 3px;
- margin-left: -8px;
- border-radius: 9999px;
- background-color: var(--nav-mark);
- pointer-events: none;
+/* While a bar menu is open its item has the one open highlight (motion.css: [data-bar-indicator]): the items' own hover
+ and focus fill steps aside, so the highlight never doubles up while it slides. */
+html [data-top-bar][data-menu-open] [data-bar-menu].nav-row:is(:hover, :focus-visible) {
+ background-color: transparent;
}
/* More, below 1280 px, holds Apps and Motions & effects: their page marks it there. */
@media (max-width: 1279.98px) {
@@ -144,7 +136,12 @@ html:not([data-input="pointer"]) .nav-focus-out:focus-visible {
}
}
@media (forced-colors: active) {
- [data-bar-split].nav-mark-under:is([data-active], :has(> [aria-current="page"]))::before,
+ [data-bar-indicator] {
+ background-color: transparent;
+ outline: 2px solid CanvasText;
+ outline-offset: -2px;
+ }
+ [data-bar-menu][data-open] { text-decoration: underline; text-underline-offset: 6px; }
:is(.nav-row[aria-current="page"], .nav-row[data-current], .nav-row[data-active]) :is(.nav-mark-start, .nav-mark-under)::before,
:is(.nav-mark-start, .nav-mark-under):is(.nav-row[aria-current="page"], .nav-row[data-current], .nav-row[data-active])::before {
background-color: Highlight;
diff --git a/src/components/nav/bar-menus.tsx b/src/components/nav/bar-menus.tsx
new file mode 100644
index 00000000..92e2e622
--- /dev/null
+++ b/src/components/nav/bar-menus.tsx
@@ -0,0 +1,635 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ aiming,
+ restDue,
+ restMove,
+ restStart,
+ switchDirection,
+ switchesAtOnce,
+ type BarMenuAction,
+ type BarMenuId,
+ type BarMenuState,
+ type Box,
+ type MenuVia,
+ type Move,
+ type Pt,
+ type Rest,
+} from "@/lib/bar-intent";
+import { megaMove } from "@/lib/mega-menus";
+import { ms, NAV_INTENT } from "@/lib/ui-motion";
+import { useNavUi } from "./nav-ui";
+
+/*
+ * The top bar's six menus (Create, Studios, Apps, Motions & effects, Canvas, More) under one controller, so every item
+ * behaves the same way, on every page:
+ *
+ * mouse resting on an item opens its menu (NAV_INTENT.rest; a glide along the bar opens nothing); while one is
+ * open, moving onto another item switches at once, unless the pointer is heading into the open menu (the
+ * safe triangle, a short hold). A menu the pointer opened closes a moment after the pointer leaves it.
+ * click opens a menu pinned (a click on a menu the pointer opened pins it; a click on a pinned one closes it).
+ * Ctrl/Cmd-click or a middle click opens the item's page in a new tab.
+ * touch/pen never hover: a tap toggles, a tap on another item switches, a tap outside only closes.
+ * keys Enter/Space toggle (focus stays on the item); ArrowDown/ArrowUp open and focus the first/last row;
+ * Left/Right/Home/End move along the bar (an open menu follows); Esc closes and gives focus back.
+ *
+ * The state is NavUi's (one menu at most, bar-intent.ts's reducer); this file owns the one timer, the pointer's recent
+ * moves, and where each item and its menu are on the page. Each item is one <button aria-expanded aria-controls>,
+ * each menu a <section> of links straight after it (a disclosure, not an ARIA menu).
+ */
+
+type Part = {
+ trigger?: HTMLElement | null;
+ surface?: HTMLElement | null;
+ /** A full-width panel under the bar (not a card under its item). */
+ big?: boolean;
+ /** Its data and code are here (a hover open waits a moment for them). */
+ ready?: () => boolean;
+ /** Start loading its data and code. */
+ warm?: () => void;
+};
+
+type Timer = { kind: "open" | "close" | "switch"; id: BarMenuId; h: number };
+type Handlers<E extends HTMLElement> = {
+ onPointerEnter: (e: React.PointerEvent<E>) => void;
+ onPointerMove: (e: React.PointerEvent<E>) => void;
+ onPointerLeave: (e: React.PointerEvent<E>) => void;
+};
+export type TriggerHandlers = Handlers<HTMLButtonElement> & {
+ onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
+ onAuxClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
+ onMouseDown: (e: React.MouseEvent<HTMLButtonElement>) => void;
+ onKeyDown: (e: React.KeyboardEvent<HTMLButtonElement>) => void;
+ onFocus: () => void;
+};
+export type SurfaceHandlers = Handlers<HTMLElement> & {
+ onClick: (e: React.MouseEvent<HTMLElement>) => void;
+ onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => void;
+};
+
+export interface BarController {
+ register(id: BarMenuId, patch: Part): () => void;
+ part(id: BarMenuId): Part | undefined;
+ trigger(id: BarMenuId): TriggerHandlers;
+ surface(id: BarMenuId): SurfaceHandlers;
+ /** Keys on the bar itself: Left/Right/Home/End between its items. */
+ navKey(e: React.KeyboardEvent<HTMLElement>): void;
+ /** Closes `id` if it is the open menu (focus back to its item when `focusBack`). */
+ close(id: BarMenuId, focusBack?: boolean): void;
+ /** Focus a row of the open menu once it shows. */
+ focusIn(id: BarMenuId, which: "first" | "last" | { group: string }): void;
+ install(): () => void;
+}
+
+/** Visible on the page (not inside a hidden row or a closed panel). */
+export const shows = (el: Element) =>
+ typeof (el as HTMLElement).checkVisibility === "function" ? (el as HTMLElement).checkVisibility() : el.getClientRects().length > 0;
+
+const now = () => performance.now();
+const isKeyboard = () => typeof document !== "undefined" && document.documentElement.dataset.input === "keyboard";
+const box = (el: Element | null | undefined): Box | null => {
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return r.width || r.height ? { left: r.left, top: r.top, right: r.right, bottom: r.bottom } : null;
+};
+
+/** A row to focus in a menu: its first lead row, its first column's last row, or the asked-for column's first. */
+function rowIn(surface: HTMLElement, which: "first" | "last" | { group: string }): HTMLElement | null {
+ if (typeof which === "object") {
+ const g = surface.querySelector<HTMLElement>(`[data-group="${CSS.escape(which.group)}"] [data-row="0"]`);
+ if (g && shows(g)) return g;
+ return rowIn(surface, "first");
+ }
+ const col = [...surface.querySelectorAll<HTMLElement>('[data-col="0"]')].filter(shows);
+ col.sort((a, b) => Number(a.dataset.row) - Number(b.dataset.row));
+ return (which === "first" ? col[0] : col[col.length - 1]) ?? null;
+}
+
+export function createBarController(act: (a: BarMenuAction) => BarMenuState, state: () => BarMenuState, returnTo: () => HTMLElement | null): BarController {
+ const parts = new Map<BarMenuId, Part>();
+ let timer: Timer | null = null;
+ let rest: Rest | null = null;
+ /** The item and the menu under the mouse. */
+ let hoverOn: BarMenuId | null = null;
+ let overSurface: BarMenuId | null = null;
+ /** Where the pointer left the open menu's item (the safe triangle's tip). */
+ let exit: Pt | null = null;
+ const moves: Move[] = [];
+ let lastType = "mouse";
+
+ const clear = () => {
+ if (timer) clearTimeout(timer.h);
+ timer = null;
+ };
+ const arm = (kind: Timer["kind"], id: BarMenuId, delay: number, fn: () => void) => {
+ clear();
+ const t: Timer = { kind, id, h: 0 };
+ t.h = window.setTimeout(
+ () => {
+ if (timer !== t) return;
+ timer = null;
+ fn();
+ },
+ Math.max(0, delay),
+ );
+ timer = t;
+ };
+ const isAiming = (id: BarMenuId) => aiming(exit, box(parts.get(id)?.surface), moves.slice(-4), now());
+
+ const open = (id: BarMenuId, mode: "hover" | "pinned", via: MenuVia) => {
+ clear();
+ rest = null;
+ act({ type: "open", id, mode, via, clicked: via === "key", now: now() });
+ };
+ /** Onto another item while a menu is open (or just closed): it takes over at once, in the open one's mode. */
+ const switchTo = (id: BarMenuId) => {
+ const s = state();
+ open(id, s.id ? s.mode : "hover", "pointer");
+ };
+ const close = (id: BarMenuId, focusBack = false) => {
+ const s = state();
+ if (s.id !== id) return;
+ clear();
+ const back = focusBack ? (s.via === "area" && returnTo()?.isConnected ? returnTo() : parts.get(id)?.trigger) : null;
+ act({ type: "close", id, now: now() });
+ back?.focus();
+ };
+ const hoverOpen = (id: BarMenuId) => {
+ const started = now();
+ const go = () => {
+ if (hoverOn !== id) return;
+ const ready = parts.get(id)?.ready;
+ // The data is on its way: wait a moment for it, so the menu opens whole rather than as a skeleton.
+ if (ready && !ready() && now() - started < NAV_INTENT.dataWait) return arm("open", id, 16, go);
+ open(id, "hover", "pointer");
+ };
+ go();
+ };
+ const armRest = (id: BarMenuId) => {
+ if (rest) arm("open", id, restDue(rest) - now(), () => hoverOpen(id));
+ };
+ const armClose = (id: BarMenuId, held = 0) => {
+ arm("close", id, held ? 50 : NAV_INTENT.grace, () => {
+ const s = state();
+ if (s.id !== id || s.mode !== "hover" || hoverOn === id || overSurface === id) return;
+ // Still heading into the menu (a long diagonal): hold the close a little longer.
+ if (held < NAV_INTENT.aimMax && isAiming(id)) return armClose(id, held + 50);
+ act({ type: "close", id, now: now() });
+ });
+ };
+ const warm = (id: BarMenuId) => parts.get(id)?.warm?.();
+ const hubOf = (id: BarMenuId) => parts.get(id)?.trigger?.dataset.href;
+ const newTab = (href: string) => window.open(href, "_blank", "noopener");
+
+ const focusIn: BarController["focusIn"] = (id, which) => {
+ const start = now();
+ const tick = () => {
+ if (state().id !== id) return;
+ const s = parts.get(id)?.surface;
+ const el = s && rowIn(s, which);
+ if (el) {
+ el.focus();
+ if (document.activeElement === el) return;
+ }
+ if (now() - start < 4000) requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ };
+
+ const triggers = new Map<BarMenuId, TriggerHandlers>();
+ const surfaces = new Map<BarMenuId, SurfaceHandlers>();
+
+ const trigger = (id: BarMenuId): TriggerHandlers => {
+ const had = triggers.get(id);
+ if (had) return had;
+ const h: TriggerHandlers = {
+ onPointerEnter(e) {
+ warm(id);
+ if (e.pointerType !== "mouse") return;
+ hoverOn = id;
+ const s = state();
+ if (s.id === id) {
+ if (timer?.id === id && timer.kind === "close") clear();
+ return;
+ }
+ if (switchesAtOnce(s, now())) {
+ // Crossing this item on the way into an open card (Create, More): hold the switch a moment.
+ if (s.id && !parts.get(s.id)?.big && isAiming(s.id)) return arm("switch", id, NAV_INTENT.aimHold, () => hoverOn === id && switchTo(id));
+ return switchTo(id);
+ }
+ rest = restStart(e.clientX, e.clientY, now());
+ armRest(id);
+ },
+ onPointerMove(e) {
+ if (e.pointerType !== "mouse" || timer?.id !== id) return;
+ if (timer.kind === "open" && rest) {
+ const r = restMove(rest, e.clientX, e.clientY, now());
+ if (r !== rest) {
+ rest = r;
+ armRest(id);
+ }
+ } else if (timer.kind === "switch") {
+ const s = state();
+ if (!s.id || !isAiming(s.id)) switchTo(id);
+ }
+ },
+ onPointerLeave(e) {
+ if (e.pointerType !== "mouse") return;
+ if (hoverOn === id) hoverOn = null;
+ if (timer?.id === id && timer.kind !== "close") {
+ clear();
+ rest = null;
+ }
+ const s = state();
+ if (s.id !== id) return;
+ exit = { x: e.clientX, y: e.clientY };
+ if (s.mode === "hover") armClose(id);
+ },
+ onClick(e) {
+ const href = hubOf(id);
+ if ((e.ctrlKey || e.metaKey) && href) {
+ e.preventDefault();
+ newTab(href);
+ return;
+ }
+ const pt = (e.nativeEvent as PointerEvent).pointerType;
+ const via: MenuVia = e.detail === 0 && !pt ? "key" : (pt || lastType) === "mouse" ? "pointer" : "touch";
+ clear();
+ rest = null;
+ warm(id);
+ act({ type: "click", id, via, now: now() });
+ },
+ onAuxClick(e) {
+ const href = hubOf(id);
+ if (e.button !== 1 || !href) return;
+ e.preventDefault();
+ newTab(href);
+ },
+ onMouseDown(e) {
+ // A middle press opens the page in a new tab (on release), never the browser's autoscroll.
+ if (e.button === 1) e.preventDefault();
+ },
+ onKeyDown(e) {
+ if (e.altKey || e.ctrlKey || e.metaKey || (e.key !== "ArrowDown" && e.key !== "ArrowUp")) return;
+ e.preventDefault();
+ warm(id);
+ open(id, "pinned", "key");
+ focusIn(id, e.key === "ArrowDown" ? "first" : "last");
+ },
+ onFocus() {
+ warm(id);
+ },
+ };
+ triggers.set(id, h);
+ return h;
+ };
+
+ const surface = (id: BarMenuId): SurfaceHandlers => {
+ const had = surfaces.get(id);
+ if (had) return had;
+ const h: SurfaceHandlers = {
+ onPointerEnter(e) {
+ if (e.pointerType !== "mouse" || state().id !== id) return;
+ overSurface = id;
+ warm(id);
+ // Reached the open menu: its close, or a switch held for the way here, is off.
+ if (timer && (timer.kind === "switch" || (timer.kind === "close" && timer.id === id))) clear();
+ },
+ onPointerMove(e) {
+ // The mouse moves the keyboard's place: the row under it takes focus (quietly: the ring is the keyboard's), so the
+ // arrow keys go on from where the mouse left off and only one row is ever highlighted.
+ if (e.pointerType !== "mouse") return;
+ const at = (e.target as HTMLElement).closest<HTMLElement>("[data-col]");
+ if (at && at !== document.activeElement) at.focus({ preventScroll: true });
+ },
+ onPointerLeave(e) {
+ if (e.pointerType !== "mouse") return;
+ if (overSurface === id) overSurface = null;
+ const s = state();
+ if (s.id === id && s.mode === "hover") {
+ exit = null;
+ armClose(id);
+ }
+ },
+ onClick(e) {
+ // A link followed: the menu closes with it.
+ if ((e.target as Element).closest("a[href]")) close(id);
+ },
+ onKeyDown(e) {
+ gridKey(e);
+ },
+ };
+ surfaces.set(id, h);
+ return h;
+ };
+
+ const navKey: BarController["navKey"] = (e) => {
+ const el = e.target as HTMLElement;
+ if (!el.matches("[data-bar-item]") || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key)) return;
+ const items = [...e.currentTarget.querySelectorAll<HTMLElement>("[data-bar-item]")].filter(shows);
+ const i = items.indexOf(el);
+ if (i < 0) return;
+ const n = items.length;
+ const next = items[e.key === "Home" ? 0 : e.key === "End" ? n - 1 : (i + (e.key === "ArrowLeft" ? n - 1 : 1)) % n];
+ e.preventDefault();
+ const s = state();
+ const nid = next.dataset.barMenu as BarMenuId | undefined;
+ if (s.id) {
+ if (nid) {
+ warm(nid);
+ open(nid, "pinned", "key");
+ } else close(s.id);
+ }
+ next.focus();
+ };
+
+ const install = () => {
+ const onMove = (e: PointerEvent) => {
+ lastType = e.pointerType;
+ if (e.pointerType !== "mouse") return;
+ moves.push({ x: e.clientX, y: e.clientY, t: now() });
+ if (moves.length > 6) moves.shift();
+ };
+ const swallowClick = () => {
+ const stop = (ev: MouseEvent) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ };
+ document.addEventListener("click", stop, { capture: true, once: true });
+ window.setTimeout(() => document.removeEventListener("click", stop, true), 800);
+ };
+ const onDown = (e: PointerEvent) => {
+ lastType = e.pointerType;
+ const s = state();
+ if (!s.id) return;
+ const target = e.target as Element | null;
+ // A press on an item is the item's own (its click switches or toggles); a press in the open menu is the menu's.
+ if (target?.closest?.("[data-bar-menu]") || parts.get(s.id)?.surface?.contains(target)) return;
+ close(s.id);
+ // A tap meant to dismiss never follows a link on the dimmed page under it.
+ if (e.pointerType === "touch" || e.pointerType === "pen") swallowClick();
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== "Escape" || e.defaultPrevented) return;
+ const s = state();
+ if (!s.id) return;
+ e.preventDefault();
+ const p = parts.get(s.id);
+ const a = document.activeElement;
+ const inside = !!a && (!!p?.trigger?.contains(a) || !!p?.surface?.contains(a));
+ // Opened by the pointer while typing elsewhere: Esc closes it and focus stays where it is.
+ close(s.id, inside || s.via === "area");
+ };
+ const onFocusOut = (e: FocusEvent) => {
+ const s = state();
+ if (!s.id) return;
+ const to = e.relatedTarget as Element | null;
+ if (!to) return;
+ const p = parts.get(s.id);
+ const inOpen = (n: Node | null) => !!n && (!!p?.trigger?.contains(n) || !!p?.surface?.contains(n));
+ if (!inOpen(e.target as Node) || inOpen(to)) return;
+ // A press on another item focuses it before its click switches: that click decides, not the focus.
+ if (to.closest?.("[data-bar-menu]") && !isKeyboard()) return;
+ close(s.id);
+ };
+ document.addEventListener("pointermove", onMove, { capture: true, passive: true });
+ document.addEventListener("pointerdown", onDown, true);
+ document.addEventListener("keydown", onKey);
+ document.addEventListener("focusout", onFocusOut);
+ return () => {
+ clear();
+ document.removeEventListener("pointermove", onMove, true);
+ document.removeEventListener("pointerdown", onDown, true);
+ document.removeEventListener("keydown", onKey);
+ document.removeEventListener("focusout", onFocusOut);
+ };
+ };
+
+ return {
+ register(id, patch) {
+ const p = parts.get(id) ?? {};
+ Object.assign(p, patch);
+ parts.set(id, p);
+ return () => {
+ for (const k of Object.keys(patch) as (keyof Part)[]) if (p[k] === patch[k]) delete p[k];
+ };
+ },
+ part: (id) => parts.get(id),
+ trigger,
+ surface,
+ navKey,
+ close,
+ focusIn,
+ install,
+ };
+}
+
+/**
+ * Arrow keys in a menu's grid of links (each link has data-col and data-row): up and down a column, left and right to
+ * the same place in the next one, Home and End. The links that show count (a row hidden by the window's height is
+ * skipped). ArrowDown on "See all" (data-see-all, before the grid) goes to the first lead row.
+ */
+export function gridKey(e: React.KeyboardEvent<HTMLElement>) {
+ const root = e.currentTarget;
+ const target = e.target as HTMLElement;
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
+ if (target.matches("[data-see-all]") && e.key === "ArrowDown") {
+ const first = rowIn(root, "first");
+ if (first) {
+ e.preventDefault();
+ first.focus();
+ }
+ return;
+ }
+ const at = target.closest<HTMLElement>("[data-col]");
+ if (!at) return;
+ const cols: HTMLElement[][] = [];
+ for (const el of root.querySelectorAll<HTMLElement>("[data-col]")) {
+ if (!shows(el)) continue;
+ (cols[Number(el.dataset.col)] ??= []).push(el);
+ }
+ for (let i = 0; i < cols.length; i++) (cols[i] ??= []).sort((x, y) => Number(x.dataset.row) - Number(y.dataset.row));
+ const col = Number(at.dataset.col);
+ const row = cols[col]?.indexOf(at) ?? -1;
+ if (row < 0) return;
+ const next = megaMove(
+ cols.map((c) => c.length),
+ { col, row },
+ e.key,
+ );
+ if (/^(Arrow|Home$|End$)/.test(e.key)) e.preventDefault();
+ if (next) cols[next.col][next.row]?.focus();
+}
+
+const BarCtx = createContext<BarController | null>(null);
+
+/** The bar's menu controller (null outside the bar: a menu rendered alone in a check is inert). */
+export function useBarController(): BarController | null {
+ return useContext(BarCtx);
+}
+
+/** Holds the controller for the bar and what hangs from it (its menus, the open highlight, the dimmed page). */
+export function BarMenusProvider({ children }: { children: React.ReactNode }) {
+ const { menuAct, menuNow, menuReturnTo, menu } = useNavUi();
+ const ctl = useMemo(() => createBarController(menuAct, menuNow, menuReturnTo), [menuAct, menuNow, menuReturnTo]);
+ useEffect(() => ctl.install(), [ctl]);
+ // Opened from a button elsewhere (openArea, "All studios"): the asked-for column (or the first row) takes focus.
+ useEffect(() => {
+ if (menu.id && menu.via === "area") ctl.focusIn(menu.id, menu.group ? { group: menu.group } : "first");
+ }, [ctl, menu.id, menu.via, menu.group, menu.seq]);
+ return <BarCtx.Provider value={ctl}>{children}</BarCtx.Provider>;
+}
+
+/** A new page (a link, back, a notification) closes the open menu. Reads the path: render it inside Suspense. */
+export function CloseMenusOnRoute() {
+ const pathname = usePathname();
+ const { menuNow, menuAct } = useNavUi();
+ const at = useRef(pathname);
+ useEffect(() => {
+ if (at.current === pathname) return;
+ at.current = pathname;
+ if (menuNow().id) menuAct({ type: "close", now: performance.now() });
+ }, [pathname, menuNow, menuAct]);
+ return null;
+}
+
+/**
+ * A menu's surface on the page: "open", "exit" (its exit is playing: inert, still painted) or "gone" (hidden). Exits
+ * take the fast token (0 under reduced motion).
+ */
+export function usePresence(open: boolean): "open" | "exit" | "gone" {
+ const [gone, setGone] = useState(!open);
+ if (open && gone) setGone(false);
+ useEffect(() => {
+ if (open) return;
+ const t = window.setTimeout(() => setGone(true), ms("fast"));
+ return () => window.clearTimeout(t);
+ }, [open]);
+ return open ? "open" : gone ? "gone" : "exit";
+}
+
+/**
+ * One bar menu's wiring: registers its item and surface with the controller and says how its surface moves.
+ * `big`: a full-width panel (Studios, Apps, Motions & effects, Canvas); else a card under its item (Create, More).
+ */
+export function useBarMenu(id: BarMenuId, { big = false, ready, warm }: { big?: boolean; ready?: () => boolean; warm?: () => void } = {}) {
+ const ctl = useBarController();
+ const { menu } = useNavUi();
+ const open = menu.id === id;
+ const phase = usePresence(open);
+ useEffect(() => ctl?.register(id, { big, ready, warm }), [ctl, id, big, ready, warm]);
+ const triggerRef = useCallback((el: HTMLButtonElement | null) => ctl?.register(id, { trigger: el }), [ctl, id]);
+ const surfaceRef = useCallback((el: HTMLElement | null) => ctl?.register(id, { surface: el }), [ctl, id]);
+ // How it comes in and goes out: a switch between two big panels slides sideways (the way the pointer went);
+ // anything else enters from the bar and leaves the same way.
+ const other = open ? menu.prev : menu.id;
+ const sideways = big && !!other && !!ctl?.part(other)?.big;
+ const dir = open ? switchDirection(menu.prev, id) : switchDirection(id, menu.id);
+ const motion = sideways && dir ? (open ? { "--enter-x": `calc(var(--motion-d2) * ${dir})`, "--enter-y": "0px", "--enter-delay": "var(--motion-stagger)" } : { "--exit-x": `calc(var(--motion-d2) * ${-dir})`, "--exit-y": "0px" }) : {};
+ return {
+ open,
+ phase,
+ /** A switch from another panel: no column cascade, the content changes as one piece. */
+ entered: open && sideways ? ("switch" as const) : ("fresh" as const),
+ style: motion as React.CSSProperties,
+ triggerRef,
+ surfaceRef,
+ trigger: ctl?.trigger(id),
+ surface: ctl?.surface(id),
+ close: (focusBack = false) => ctl?.close(id, focusBack),
+ };
+}
+
+/** The open item's highlight: one fill that slides from item to item as the open menu changes. */
+export function BarIndicator() {
+ const ctl = useBarController();
+ const { menu } = useNavUi();
+ const ref = useRef<HTMLSpanElement>(null);
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const trig = menu.id ? ctl?.part(menu.id)?.trigger : null;
+ if (!trig) {
+ el.removeAttribute("data-on");
+ return;
+ }
+ const place = () => {
+ const host = el.parentElement?.getBoundingClientRect();
+ const r = trig.getBoundingClientRect();
+ if (!host || !r.width) return;
+ el.style.width = `${r.width}px`;
+ el.style.height = `${r.height}px`;
+ el.style.translate = `${r.left - host.left}px ${r.top - host.top}px`;
+ };
+ // Slides only from one open item to the next; from nothing it shows in place. The slide moves transform only: the
+ // box takes the new item's size at once and starts scaled to the old one's width, then settles (FLIP).
+ const slide = el.hasAttribute("data-on") && !!menu.prev;
+ const was = slide ? { w: parseFloat(el.style.width), t: el.style.translate } : null;
+ el.removeAttribute("data-slide");
+ place();
+ const w = parseFloat(el.style.width);
+ if (was && w > 0 && was.w > 0) {
+ const to = el.style.translate;
+ el.style.translate = was.t;
+ el.style.scale = `${was.w / w} 1`;
+ void el.offsetWidth;
+ el.setAttribute("data-slide", "");
+ el.style.translate = to;
+ el.style.scale = "1 1";
+ } else el.style.scale = "1 1";
+ el.setAttribute("data-on", "");
+ const ro = new ResizeObserver(place);
+ ro.observe(trig);
+ window.addEventListener("resize", place);
+ return () => {
+ ro.disconnect();
+ window.removeEventListener("resize", place);
+ };
+ }, [ctl, menu.id, menu.prev]);
+ return <span ref={ref} aria-hidden data-bar-indicator className="pointer-events-none absolute top-0 left-0 rounded-[10px] print:hidden" />;
+}
+
+/**
+ * The sheet under the bar that the four big panels share: one surface whose bottom edge moves to the open panel's
+ * height (by transform only), so a switch from Studios to Apps grows or shrinks it rather than cutting.
+ */
+export function BarStage() {
+ const ctl = useBarController();
+ const { menu } = useNavUi();
+ const ref = useRef<HTMLDivElement>(null);
+ const big = menu.id && ctl?.part(menu.id)?.big ? menu.id : null;
+ const morph = !!big && !!menu.prev && !!ctl?.part(menu.prev)?.big;
+ useLayoutEffect(() => {
+ const stage = ref.current;
+ const panel = big ? ctl?.part(big)?.surface : null;
+ if (!stage || !panel) return;
+ const set = () => stage.style.setProperty("--panel-h", `${panel.offsetHeight}px`);
+ set();
+ const ro = new ResizeObserver(set);
+ ro.observe(panel);
+ return () => ro.disconnect();
+ }, [ctl, big]);
+ return (
+ <div
+ ref={ref}
+ aria-hidden
+ data-mega-stage
+ data-open={big ? "" : undefined}
+ data-morph={morph ? "" : undefined}
+ className="pointer-events-none absolute inset-x-0 top-full h-[calc(100dvh-3.5rem)] overflow-hidden print:hidden"
+ >
+ <div data-mega-backdrop className="absolute inset-0">
+ <div data-mega-sheet className="absolute inset-0 border-b border-sidebar-border bg-popover shadow-heavy" />
+ </div>
+ </div>
+ );
+}
+
+/** Dims the page under any open menu (decoration: presses go through to the page, which closes the menu). */
+export function BarScrim() {
+ const { openMenu } = useNavUi();
+ return <div aria-hidden data-bar-scrim data-open={openMenu ? "" : undefined} className="pointer-events-none fixed inset-x-0 top-14 bottom-0 z-[39] hidden bg-overlay md:block print:hidden" />;
+}
diff --git a/src/components/nav/bar-split.tsx b/src/components/nav/bar-split.tsx
index 404c4d2f..593a962a 100644
--- a/src/components/nav/bar-split.tsx
+++ b/src/components/nav/bar-split.tsx
@@ -1,304 +1,151 @@
"use client";
import { ChevronDown } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { IntentLink } from "@/components/intent-link";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
-import { isPlainClick } from "@/lib/use-tapped-tab";
+import { useCallback, useEffect, useState } from "react";
+import type { BarMenuId } from "@/lib/bar-intent";
import { cn } from "@/lib/utils";
-import { warmNav, type NavPanel } from "./nav-prefetch";
-import { useNavUi } from "./nav-ui";
+import { useBarMenu, type TriggerHandlers } from "./bar-menus";
/*
- * A bar item with a page and a menu (Create, Studios, Motions & effects): one pill made of two controls. Its name is a
- * link to the area's page (/create, /studios, /motions-and-effects); the chevron beside it opens the menu, as does
- * ArrowDown on the name, and, with a mouse, resting on the item (not on the item of the page you are on). A touch
- * screen never opens it by hovering: a tap on the name goes to the page, a tap on the chevron opens the menu.
+ * A bar item with a menu (Create, Studios, Apps, Motions & effects, Canvas, More): one button, one hit area, one
+ * highlight. It shows and hides its menu (aria-expanded, aria-controls: the menu's section, straight after it); a plain
+ * click never leaves the page. Its area's own page is the menu's first link ("See all"), and Ctrl/Cmd-click or a middle
+ * click opens that page in a new tab (data-href).
*
- * States are the nav's (nav-states.css): each half has the highlight on hover or keyboard focus and the pressed fill;
- * the pill shows the open page's pip under it (data-active inside the area, aria-current="page" on the name on the
- * area's own page), and while the menu is open (data-open, data-state="open" on the chevron) foreground words and a
- * turned chevron, never a fill. The pill is exactly as wide as a plain item with a chevron (the name keeps its padding on the left, the
- * chevron takes the right padding and the gap), so the bar never grows.
+ * States are the nav's (nav-states.css): the highlight on hover or keyboard focus, the pressed fill, the open page's pip
+ * under it (data-active: one of the area's pages is open), and while its menu is open foreground words, a turned
+ * chevron and the bar's one open highlight (BarIndicator) behind it.
*/
-/** The pill around the two controls. */
-export const BAR_SPLIT =
- "nav-mark-under group/bar-item inline-flex h-10 shrink-0 items-stretch rounded-[10px] text-[14px] whitespace-nowrap text-foreground/80 [@media(pointer:coarse)]:h-11 data-[active]:font-semibold data-[active]:text-foreground has-[[aria-current=page]]:font-semibold has-[[aria-current=page]]:text-foreground data-[open]:text-foreground";
+/** The item: 40 px (44 to tap), 10 px left and 8 px right of the words (14 and 10 from 1440 px), then the chevron. */
+export const BAR_TRIGGER =
+ "nav-row nav-mark-under group/bar-item inline-flex h-10 shrink-0 items-center gap-1 rounded-[10px] pr-2 pl-2.5 text-[14px] whitespace-nowrap text-foreground/80 nav-hover:text-foreground focus-visible:text-foreground data-[open]:text-foreground data-[active]:font-semibold data-[active]:text-foreground min-[1440px]:pr-2.5 min-[1440px]:pl-3.5 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:min-w-11";
-/** The name: the area's page. */
-export const BAR_LABEL = "nav-row inline-flex items-center gap-1.5 rounded-l-[10px] pr-1 pl-2.5 nav-hover:text-foreground focus-visible:text-foreground min-[1440px]:pl-3.5";
-
-/** The chevron: the menu. 26 px wide (30 from 1440) with a mouse; 44 px to tap. */
-export const BAR_CHEVRON =
- "nav-row inline-flex w-[26px] items-center justify-center rounded-r-[10px] text-muted-foreground nav-hover:text-foreground focus-visible:text-foreground data-[state=open]:text-foreground min-[1440px]:w-[30px] [@media(pointer:coarse)]:w-11";
-
-export const BarChevron = () => <ChevronDown aria-hidden className="size-3.5 group-data-[open]/bar-item:rotate-180 motion-safe:transition-transform" />;
+/** The chevron: a quiet mark inside the item (no box of its own); it turns while the menu is open. */
+export const BarChevron = () => (
+ <ChevronDown
+ aria-hidden
+ data-bar-chevron
+ className="size-3 shrink-0 text-muted-foreground group-hover/bar-item:text-foreground group-data-[open]/bar-item:text-foreground"
+ />
+);
/**
- * How long the pointer rests on an item before its menu opens (long enough that sweeping along the bar to the search
- * opens nothing), and how long after it leaves before it closes.
+ * The item. `id`: its menu; `panelId`: its section's id; `href`: its area's page (none for More); `label`: its words
+ * (the accessible name, unless `name` says more: "Studios, 29 studios"); `active`: one of its pages is open.
*/
-export const HOVER_OPEN_MS = 300;
-export const HOVER_CLOSE_MS = 250;
-/** Only a mouse (a fine pointer that can hover) opens a menu by resting on it. */
-export const HOVER_QUERY = "(hover: hover) and (pointer: fine)";
-
-const canHover = (e: React.PointerEvent) => e.pointerType === "mouse" && typeof window !== "undefined" && window.matchMedia(HOVER_QUERY).matches;
-
-/**
- * Open on rest, close on leave, for a menu opened by hovering only: a menu opened by a click or a key stays until it is
- * closed (pinned). `open`: whether it is open now; `onOpen`/`onClose` change it; `off`: resting opens nothing (the
- * item is the page you are on, so its menu would only cover it). Put `enter`/`leave` on the item and on its panel, so
- * moving from one to the other keeps it open.
- */
-export function useHoverIntent(open: boolean, onOpen: () => void, onClose: () => void, off = false) {
- const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
- /** Opened by hovering and not pinned since. */
- const byHover = useRef(false);
- const openRef = useRef(open);
- const cancel = useCallback(() => clearTimeout(timer.current), []);
- useEffect(() => cancel, [cancel]);
- useEffect(() => {
- openRef.current = open;
- // Closed some other way (Esc, a click outside, a row followed): the next hover starts afresh.
- if (!open) byHover.current = false;
- }, [open]);
-
- // `now`: open without the rest (another of the bar's grouped menus is open: moving along the bar switches at once).
- const enter = useCallback(
- (e: React.PointerEvent, now = false) => {
- if (!canHover(e)) return;
- cancel();
- if (openRef.current || off) return;
- const go = () => {
- byHover.current = true;
- onOpen();
- };
- if (now) go();
- else timer.current = setTimeout(go, HOVER_OPEN_MS);
- },
- [cancel, onOpen, off],
- );
- const leave = useCallback(
- (e: React.PointerEvent) => {
- if (!canHover(e)) return;
- cancel();
- if (!openRef.current || !byHover.current) return;
- timer.current = setTimeout(() => {
- byHover.current = false;
- onClose();
- }, HOVER_CLOSE_MS);
- },
- [cancel, onClose],
+export function BarTrigger({
+ id,
+ panelId,
+ href,
+ label,
+ name,
+ icon,
+ active,
+ open,
+ handlers,
+ triggerRef,
+ className,
+ ...rest
+}: {
+ id: BarMenuId;
+ panelId: string;
+ href?: string;
+ label: React.ReactNode;
+ name?: string;
+ icon?: React.ReactNode;
+ active?: boolean;
+ open: boolean;
+ handlers?: TriggerHandlers;
+ triggerRef?: React.Ref<HTMLButtonElement>;
+ className?: string;
+} & Omit<React.ComponentProps<"button">, "id" | "ref" | "onClick">) {
+ return (
+ <button
+ ref={triggerRef}
+ type="button"
+ aria-expanded={open}
+ aria-controls={panelId}
+ aria-label={name}
+ aria-current={active ? "true" : undefined}
+ data-bar-menu={id}
+ data-bar-item=""
+ data-href={href}
+ data-active={active || undefined}
+ data-open={open || undefined}
+ className={cn(BAR_TRIGGER, className)}
+ {...handlers}
+ {...rest}
+ >
+ {icon}
+ {label}
+ <BarChevron />
+ </button>
);
- /** A click or a key took over: no timer, and the menu stays open until closed. */
- const pin = useCallback(() => {
- cancel();
- byHover.current = false;
- }, [cancel]);
- return { enter, leave, cancel, pin, openedByHover: () => byHover.current };
}
/**
- * Opened by resting the pointer: focus stays where it was (a prompt being typed keeps its keys, and the menu's type-to-jump
- * never takes them). Radix's root menu content takes onOpenAutoFocus at run time; its public props leave it out.
- */
-const keepFocusOnHover = (byHover: () => boolean) =>
- ({
- onOpenAutoFocus: (e: Event) => {
- if (byHover()) e.preventDefault();
- },
- }) as unknown as Partial<React.ComponentProps<typeof DropdownMenuContent>>;
-
-/**
- * A split item whose menu is a Radix menu (Create, Motions & effects): arrow keys, typeahead, Esc and focus return come
- * with it. `name`: the chevron's accessible name ("Create menu"); `panel`: the routes to load ahead when it opens;
- * `onTap`: the name was clicked (the bar marks it at once).
+ * A bar item whose menu is a card under it (Create, More): the same one button and the same controller as the big
+ * panels, with the card hanging 8 px under the item, left-aligned to it (the 8 px band counts as the card, so the
+ * pointer can cross it). Its rows render once the pointer or focus comes near (or it opens).
*/
-export function BarSplitMenu({
+export function BarCardMenu({
+ id,
href,
label,
name,
+ icon,
active,
- current,
- panel,
- onTap,
className,
- contentClassName,
- onContentKeyDown,
+ cardClassName,
+ onOpen,
children,
+ ...rest
}: {
- href: string;
- label: React.ReactNode;
- name: string;
+ id: BarMenuId;
+ href?: string;
+ label: string;
+ name?: string;
+ icon?: React.ReactNode;
active?: boolean;
- current?: boolean;
- panel: NavPanel;
- onTap?: (href: string) => void;
+ /** The wrapper's (which widths show the item). */
className?: string;
- contentClassName?: string;
- /** Keys the menu's content handles beyond Radix's own (the Create menu's Left and Right across its columns). */
- onContentKeyDown?: (e: React.KeyboardEvent<HTMLDivElement>) => void;
+ cardClassName?: string;
+ /** It opened (start loading what its rows lead to). */
+ onOpen?: () => void;
children: React.ReactNode;
-}) {
- const [open, setOpen] = useState(false);
- const [offset, setOffset] = useState(0);
- const openRef = useRef(open);
- useEffect(() => {
- openRef.current = open;
- }, [open]);
- const { openMenu, setOpenMenu } = useNavUi();
- const pill = useRef<HTMLDivElement>(null);
- const nameLink = useRef<HTMLAnchorElement>(null);
- const chevron = useRef<HTMLButtonElement>(null);
- const content = useRef<HTMLDivElement>(null);
- /** Opened from the name with ArrowDown: the first row takes focus, and Esc brings it back to the name. */
- const focusFirst = useRef(false);
- const fromName = useRef(false);
- /** Closed because the pointer left: focus stays where it is (on the page), not on the chevron. */
- const quietClose = useRef(false);
-
- /** Open or close. `pinned`: by a click or a key, so its rows start loading; a bare hover loads them only once the pointer reaches the menu. */
- const show = useCallback(
- (o: boolean, pinned = true) => {
- if (o) {
- // The menu lines up with the pill's left edge, not the chevron's.
- const p = pill.current?.getBoundingClientRect();
- const c = chevron.current?.getBoundingClientRect();
- if (p && c) setOffset(p.left - c.left);
- if (pinned) warmNav(panel);
- }
- setOpen(o);
- },
- [panel],
- );
- // A grouped menu opened (Studios, Apps …): this one closes, quietly (focus is the other menu's now).
+} & Omit<React.ComponentProps<"button">, "id" | "ref" | "onClick" | "className" | "children">) {
+ const [near, setNear] = useState(false);
+ const heat = useCallback(() => setNear(true), []);
+ const { open, phase, trigger, surface, triggerRef, surfaceRef } = useBarMenu(id, { warm: heat });
useEffect(() => {
- if (openMenu && openRef.current) {
- quietClose.current = true;
- setOpen(false);
- }
- }, [openMenu]);
- // Opened from the name with ArrowDown: once the menu has taken focus, its first row gets it.
- useEffect(() => {
- if (!open || !focusFirst.current) return;
- focusFirst.current = false;
- const id = requestAnimationFrame(() => content.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus());
- return () => cancelAnimationFrame(id);
- }, [open]);
- const hover = useHoverIntent(
- open,
- useCallback(() => {
- fromName.current = false;
- // One panel at a time: an open grouped menu gives way (focus stays where it is).
- if (openMenu) setOpenMenu(null);
- show(true, false);
- }, [show, openMenu, setOpenMenu]),
- useCallback(() => {
- quietClose.current = true;
- show(false);
- }, [show]),
- current,
- );
-
+ if (open) onOpen?.();
+ }, [open, onOpen]);
+ const panelId = `${id}-menu`;
return (
- <DropdownMenu
- modal={false}
- open={open}
- onOpenChange={(o) => {
- if (o) {
- hover.pin();
- fromName.current = false;
- if (openMenu) setOpenMenu(null);
- }
- show(o);
- }}
- >
- <div
- ref={pill}
- data-bar-split
- data-active={active || undefined}
- data-open={open || undefined}
- className={cn(BAR_SPLIT, className)}
- onPointerEnter={hover.enter}
- onPointerLeave={hover.leave}
+ <div className={cn("relative inline-flex shrink-0", className)}>
+ <BarTrigger id={id} panelId={panelId} href={href} label={label} name={name} icon={icon} active={active} open={open} handlers={trigger} triggerRef={triggerRef} {...rest} />
+ <section
+ ref={surfaceRef}
+ id={panelId}
+ data-bar-card={id}
+ data-phase={phase}
+ aria-label={label}
+ hidden={phase === "gone"}
+ inert={phase !== "open"}
+ aria-hidden={phase === "exit" || undefined}
+ {...surface}
+ className="absolute top-full left-0 z-50 pt-2"
>
- <IntentLink
- ref={nameLink}
- href={href}
- aria-current={current ? "page" : undefined}
- className={BAR_LABEL}
- onClick={(e) => {
- hover.cancel();
- if (open) {
- quietClose.current = true;
- setOpen(false);
- }
- if (isPlainClick(e)) onTap?.(href);
- }}
- onKeyDown={(e) => {
- if (e.key !== "ArrowDown" || e.altKey || e.metaKey || e.ctrlKey) return;
- e.preventDefault();
- focusFirst.current = true;
- fromName.current = true;
- hover.pin();
- if (openMenu) setOpenMenu(null);
- show(true);
- }}
+ <div
+ className={cn(
+ "max-h-[calc(100dvh-4.5rem)] overflow-x-hidden overflow-y-auto overscroll-contain rounded-xl bg-popover p-1.5 text-popover-foreground shadow-md ring-1 ring-foreground/10",
+ cardClassName,
+ )}
>
- {label}
- </IntentLink>
- <DropdownMenuTrigger
- ref={chevron}
- aria-label={name}
- className={BAR_CHEVRON}
- onPointerDown={(e) => {
- // Open by hovering: a click on the chevron keeps it open (pins it) rather than closing it.
- if (open && hover.openedByHover()) {
- e.preventDefault();
- hover.pin();
- }
- }}
- >
- <BarChevron />
- </DropdownMenuTrigger>
- </div>
- <DropdownMenuContent
- ref={content}
- align="start"
- alignOffset={offset}
- sideOffset={8}
- collisionPadding={12}
- className={contentClassName}
- onKeyDown={onContentKeyDown}
- onPointerEnter={(e) => {
- hover.enter(e);
- warmNav(panel);
- }}
- onPointerLeave={hover.leave}
- // A press on the chevron is the trigger's own (it closes the menu, or pins one opened by hovering): it never
- // also counts as a press outside, which would close a menu the press meant to pin.
- onInteractOutside={(e) => {
- if (chevron.current?.contains(e.target as Node)) e.preventDefault();
- }}
- {...keepFocusOnHover(hover.openedByHover)}
- onCloseAutoFocus={(e) => {
- if (quietClose.current) {
- quietClose.current = false;
- e.preventDefault();
- return;
- }
- // Opened from the name with ArrowDown: Esc goes back to the name, not the chevron.
- if (fromName.current) {
- fromName.current = false;
- e.preventDefault();
- nameLink.current?.focus();
- }
- }}
- >
- {children}
- </DropdownMenuContent>
- </DropdownMenu>
+ {(near || phase !== "gone") && children}
+ </div>
+ </section>
+ </div>
);
}
diff --git a/src/components/nav/create-menu.tsx b/src/components/nav/create-menu.tsx
index 4057398f..78384127 100644
--- a/src/components/nav/create-menu.tsx
+++ b/src/components/nav/create-menu.tsx
@@ -4,20 +4,21 @@ import { Plus } from "lucide-react";
import { usePathname } from "next/navigation";
import { useId } from "react";
import { IntentLink } from "@/components/intent-link";
-import { DropdownMenuGroup, DropdownMenuLabel, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { navActive, NEW_CREATION_HREF } from "@/lib/nav";
import { area } from "@/lib/nav-areas";
import { CREATE_COLUMNS, entry, visibleTo, type NavEntry, type ViewerKind } from "@/lib/nav-model";
import { cn } from "@/lib/utils";
-import { BarSplitMenu } from "./bar-split";
+import { BarCardMenu } from "./bar-split";
+import { warmNav } from "./nav-prefetch";
import { NavIcon } from "./cover-thumb";
import { useViewerKind } from "./nav-ui";
-import { MENU_HEADING, MENU_ROW_1, MENU_ROW_2, NavMenuItem, ROW_LINE, rowName, SeeAllRow, SHEET_HEADING, SHEET_ROW } from "./nav-row";
+import { CARD_ROW, MENU_HEADING, MENU_ROW_1, MENU_ROW_2, ROW_LINE, rowName, SeeAllRow, SHEET_HEADING, SHEET_ROW } from "./nav-row";
/*
- * Create: the tools that start from words or a picture, in two labelled columns. The bar's Create menu (a menu: arrow
- * keys, typeahead, Esc and focus return come with it) and the phone's Create sheet (a plain list) show the same items.
+ * Create: the tools that start from words or a picture, in two labelled columns. The bar's Create card (links in a
+ * grid: arrow keys move up and down a column and across to the other, Esc gives focus back to the item) and the
+ * phone's Create sheet (a plain list) show the same items.
* "New creation" (a fresh composer on Home) closes both.
*/
@@ -52,47 +53,45 @@ export function CreateList({ variant, onNavigate }: { variant: "menu" | "sheet";
if (variant === "menu")
return (
<>
- <div className="grid grid-cols-2 gap-x-1.5" data-menu-columns>
+ {/* The area's own page: first in Tab order (the item, then See all, then the rows), at the top right. */}
+ <SeeAllRow href={CREATE_AREA_HREF} name="See all of Create" data-see-all className="absolute top-1.5 right-1.5 h-8" />
+ <div className="grid grid-cols-2 gap-x-1.5">
{columns.map((c, i) => (
- <DropdownMenuGroup key={c.label} aria-labelledby={`${ids}-${i}`} data-menu-column={i} className="flex min-w-0 flex-col">
- <DropdownMenuLabel id={`${ids}-${i}`} className={MENU_HEADING}>
+ <div key={c.label} role="group" aria-labelledby={`${ids}-${i}`} className="flex min-w-0 flex-col">
+ <div id={`${ids}-${i}`} className={MENU_HEADING}>
{c.label}
- </DropdownMenuLabel>
- {c.entries.map((e) => {
+ </div>
+ {c.entries.map((e, r) => {
const on = current(pathname, e.href, CREATE_HREFS);
return (
- <NavMenuItem key={e.id} asChild className={cn(MENU_ROW_2, "items-start")}>
- <IntentLink href={e.href} eager={e.eager} aria-current={on ? "page" : undefined}>
- <NavIcon name={e.icon} className="nav-icon mt-px size-4 text-muted-foreground" />
- <span className="flex min-w-0 flex-col">
- <span className={rowName(on)}>{e.label}</span>
- <span className={ROW_LINE}>{e.what}</span>
- </span>
- </IntentLink>
- </NavMenuItem>
+ <IntentLink
+ key={e.id}
+ href={e.href}
+ eager={e.eager}
+ aria-current={on ? "page" : undefined}
+ data-col={i}
+ data-row={r}
+ className={cn(CARD_ROW, MENU_ROW_2, "items-start")}
+ >
+ <NavIcon name={e.icon} className="nav-icon mt-px size-4 text-muted-foreground" />
+ <span className="flex min-w-0 flex-col">
+ <span className={rowName(on)}>{e.label}</span>
+ <span className={ROW_LINE}>{e.what}</span>
+ </span>
+ </IntentLink>
);
})}
- </DropdownMenuGroup>
+ </div>
))}
</div>
- <DropdownMenuSeparator className="mx-2.5 my-1.5" />
- {/* The foot: two rows on the columns' grid (Left and Right move between them too). */}
- <div className="grid grid-cols-2 gap-x-1.5" data-menu-columns>
- <DropdownMenuGroup data-menu-column={0} className="flex min-w-0 flex-col">
- <NavMenuItem asChild className={cn(MENU_ROW_1, "font-medium")}>
- <IntentLink href={NEW_CREATION_HREF} eager>
- <Plus aria-hidden className="size-4 text-brand-text" />
- New creation
- <Kbd aria-hidden className="ml-auto [@media(hover:none)]:hidden">
- ↵
- </Kbd>
- </IntentLink>
- </NavMenuItem>
- </DropdownMenuGroup>
- <DropdownMenuGroup data-menu-column={1} className="flex min-w-0 flex-col">
- <SeeAllRow href={CREATE_AREA_HREF} name="See all of Create" />
- </DropdownMenuGroup>
- </div>
+ <div role="separator" className="mx-2.5 my-1.5 h-px bg-border" />
+ <IntentLink href={NEW_CREATION_HREF} eager data-col={0} data-row={columns[0]?.entries.length ?? 0} className={cn(CARD_ROW, MENU_ROW_1, "w-1/2 font-medium")}>
+ <Plus aria-hidden className="size-4 text-brand-text" />
+ New creation
+ <Kbd aria-hidden className="ml-auto [@media(hover:none)]:hidden">
+ ↵
+ </Kbd>
+ </IntentLink>
</>
);
const follow = (e: React.MouseEvent) => {
@@ -157,42 +156,17 @@ export function columnMove(lengths: readonly number[], at: { col: number; row: n
return { col, row: Math.min(at.row, len - 1) };
}
-/** Moves the menu's highlight across its columns (Radix's own keys are Up, Down, Home, End and typeahead). */
-function onColumnsKey(e: React.KeyboardEvent<HTMLElement>) {
- const item = (e.target as HTMLElement).closest<HTMLElement>('[role="menuitem"]');
- const column = item?.closest<HTMLElement>("[data-menu-column]");
- const grid = column?.closest<HTMLElement>("[data-menu-columns]");
- if (!item || !column || !grid) return;
- const columns = [...grid.querySelectorAll<HTMLElement>(":scope > [data-menu-column]")].map((c) => [...c.querySelectorAll<HTMLElement>('[role="menuitem"]')]);
- const col = Number(column.dataset.menuColumn);
- const next = columnMove(
- columns.map((c) => c.length),
- { col, row: columns[col]?.indexOf(item) ?? 0 },
- e.key,
- );
- if (!next) return;
- e.preventDefault();
- columns[next.col]?.[next.row]?.focus();
-}
+/** Opened: the routes its rows lead to start loading. */
+const warmCreate = () => warmNav("create");
/**
- * The bar's Create item: its name goes to /create, its chevron (or ArrowDown, or resting on it with a mouse) opens the
- * menu. `active`: a Create page is open; `current`: /create itself; `onTap`: the name was clicked.
+ * The bar's Create item: one button that opens the Create card (resting on it with a mouse, a click, a tap, Enter,
+ * Space or ArrowDown). Its page (/create) is the card's first link, "See all". `active`: a Create page is open.
*/
-export function CreateMenu({ active, current, onTap }: { active?: boolean; current?: boolean; onTap?: (href: string) => void }) {
+export function CreateMenu({ active }: { active?: boolean }) {
return (
- <BarSplitMenu
- href={CREATE_AREA_HREF}
- label="Create"
- name="Create menu"
- active={active}
- current={current}
- panel="create"
- onTap={onTap}
- contentClassName="w-[520px] max-w-[calc(100vw-24px)] p-1.5"
- onContentKeyDown={onColumnsKey}
- >
+ <BarCardMenu id="create" href={CREATE_AREA_HREF} label="Create" active={active} onOpen={warmCreate} cardClassName="relative w-[520px] max-w-[calc(100vw-24px)]">
<CreateList variant="menu" />
- </BarSplitMenu>
+ </BarCardMenu>
);
}
diff --git a/src/components/nav/mega-data.ts b/src/components/nav/mega-data.ts
index d405fef5..e63f90eb 100644
--- a/src/components/nav/mega-data.ts
+++ b/src/components/nav/mega-data.ts
@@ -89,3 +89,14 @@ export function resetMenus() {
entries.clear();
changed();
}
+
+/** A menu's data is here (Studios always is): a hover open waits a moment for it (bar-menus.tsx), never a click. */
+export function menuReady(id: MegaId): boolean {
+ return id === "studios" || entries.get(id)?.state === "ready";
+}
+
+/** At once (not when idle): the data of these menus, unless the browser asks to save data. */
+export function loadMenusNow(ids: readonly FetchedMegaId[]): void {
+ if (saveData()) return;
+ ids.forEach(loadMenu);
+}
diff --git a/src/components/nav/mega-launcher.tsx b/src/components/nav/mega-launcher.tsx
index a99087d5..99f11479 100644
--- a/src/components/nav/mega-launcher.tsx
+++ b/src/components/nav/mega-launcher.tsx
@@ -1,30 +1,25 @@
"use client";
-import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
-import { IntentLink } from "@/components/intent-link";
+import { lazy, Suspense, useCallback, useEffect, useState } from "react";
import { MEGA_AREAS, megaMove, megaPanelId, TILE_COLS, type MegaId } from "@/lib/mega-menus";
import { launcherActive, studioCount, subActive } from "@/lib/nav-model";
-import { isPlainClick } from "@/lib/use-tapped-tab";
import { cn } from "@/lib/utils";
-import { BAR_CHEVRON, BAR_LABEL, BAR_SPLIT, BarChevron, useHoverIntent } from "./bar-split";
-import { warmMenu } from "./mega-data";
-import { useNavUi } from "./nav-ui";
+import { BarScrim, useBarMenu } from "./bar-menus";
+import { BarTrigger } from "./bar-split";
+import { menuReady, warmMenu } from "./mega-data";
import { useSearchPalette } from "./search-context";
import { warmNav, type NavPanel } from "./nav-prefetch";
/*
* The bar's grouped menus: Studios, Apps, Motions & effects and Canvas, one panel under the bar each, grouped by what
* you want to make, one click and no scrolling (down to 1280x720). A disclosure for navigation (a button that shows a
- * panel of links), not a menu: Tab walks the links in order, and arrow keys move in the grid (up and down a column,
- * left and right to the same place in the next one). Esc, a click outside or focus leaving it closes it; Esc gives
- * focus back to what opened it. One open at a time: opening one closes the others and the bar's Radix menus.
+ * panel of links), not a menu: Tab walks the links in order ("See all" first), and arrow keys move in the grid (up and
+ * down a column, left and right to the same place in the next one).
*
- * The item's name goes to the area's page; its chevron (a click, Enter or Space) or ArrowDown on the name opens the
- * panel. Resting the mouse on an item opens it too (not on the item of the page you are on; it closes again when the
- * pointer leaves the item and the panel, unless a click or a key pinned it), and while one is open, moving onto another
- * item switches to that one at once, as a menubar does. The panel is mounted, hidden, the first time the
- * pointer or focus comes to the item, so its data and lead covers load before it opens. The panel's body (its links,
- * cards and tiles: mega-panel.tsx) is a chunk of its own, loaded then or once the page is idle (preloadMegaPanel).
+ * How the item opens and closes its panel (rest, click, tap, keys, switching from one to the next) is the bar's
+ * controller's (bar-menus.tsx), the same for all six menus. The panel's body (its links, cards and tiles:
+ * mega-panel.tsx) is a chunk of its own, loaded when the pointer or focus comes near or soon after the page is ready
+ * (preloadMegaPanel), so the first open never waits for it.
*/
/** The Studios panel's id (kept: the browser checks and the "All studios" buttons name it). */
@@ -41,9 +36,11 @@ export function launcherCurrent(pathname: string): string | undefined {
return launcherActive(pathname);
}
-/** The panel: under the bar, as wide as it, scrolling inside only when the window is too short for it. */
-export const LAUNCHER_PANEL =
- "absolute inset-x-0 top-full max-h-[calc(100dvh-3.5rem)] overflow-y-auto overscroll-contain border-b border-sidebar-border bg-popover text-popover-foreground shadow-heavy motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1 motion-safe:duration-150";
+/**
+ * The panel: under the bar, as wide as it, on the bar's shared sheet (it has no background of its own, so a switch
+ * cross-fades two panels over one surface); scrolling inside only when the window is too short for it.
+ */
+export const LAUNCHER_PANEL = "absolute inset-x-0 top-full max-h-[calc(100dvh-3.5rem)] overflow-y-auto overscroll-contain text-popover-foreground";
/** The routes a menu's links lead to that load ahead when it opens (each row also loads on hover: IntentLink). */
const WARM: Record<MegaId, NavPanel> = { studios: "studios", apps: "more", motions: "more", canvas: "more" };
@@ -57,7 +54,12 @@ export function megaCurrent(id: MegaId, pathname: string, search = ""): string |
}
/** The panel's body, loaded the first time it is asked for (once: the import is cached). */
-const loadPanel = () => import("./mega-panel");
+let panelLoaded = false;
+const loadPanel = () =>
+ import("./mega-panel").then((m) => {
+ panelLoaded = true;
+ return m;
+ });
const LazyPanel = lazy(() => loadPanel().then((m) => ({ default: m.MegaPanel })));
/** Loads the panel's body ahead (the bar does when the page is idle; hover and focus on an item do too). */
@@ -69,7 +71,7 @@ export function preloadMegaPanel(): void {
export function MegaSkeleton({ id }: { id?: MegaId }) {
if (id === "canvas") {
return (
- <div aria-hidden className="grid grid-cols-3 gap-x-4 gap-y-6 lg:grid-cols-6 2xl:gap-x-6">
+ <div aria-hidden data-mega-skeleton className="grid grid-cols-3 gap-x-4 gap-y-6 lg:grid-cols-6 2xl:gap-x-6">
<div className="col-span-3 flex flex-col gap-2 lg:col-span-2">
<span className="h-4 w-24 rounded bg-muted" />
<span className="aspect-[4/3] max-h-[max(64px,calc(100dvh-592px))] w-full rounded-t-[14px] bg-muted" />
@@ -90,7 +92,7 @@ export function MegaSkeleton({ id }: { id?: MegaId }) {
);
}
return (
- <div aria-hidden className="grid grid-cols-3 gap-x-4 gap-y-6 lg:grid-cols-6 2xl:gap-x-6">
+ <div aria-hidden data-mega-skeleton className="grid grid-cols-3 gap-x-4 gap-y-6 lg:grid-cols-6 2xl:gap-x-6">
{Array.from({ length: 6 }, (_, i) => (
<div key={i} className="flex flex-col gap-2">
<span className="h-4 w-24 rounded bg-muted" />
@@ -105,258 +107,74 @@ export function MegaSkeleton({ id }: { id?: MegaId }) {
);
}
-/** Visible on the page (not inside a hidden row or a closed panel). */
-const shows = (el: Element) => (typeof (el as HTMLElement).checkVisibility === "function" ? (el as HTMLElement).checkVisibility() : el.getClientRects().length > 0);
-
/**
- * A bar item with a grouped menu: its name goes to the area's page, its chevron (or ArrowDown on the name) opens the
- * panel. The panel hangs from the bar (the header is its positioned parent) and spans it.
- * `active`: one of the area's pages is open; `current`: the area's own page; `onTap`: the name was clicked.
+ * A bar item with a full-width panel (Studios, Apps, Motions & effects, Canvas): one button that shows and hides the
+ * panel. The panel hangs from the bar (the header is its positioned parent), spans it, and sits on the bar's shared
+ * sheet (BarStage). It is in the DOM straight after its item (Tab goes item, panel, next item), hidden and inert while
+ * closed; its body loads the first time the pointer or focus comes near (or soon after the page is ready).
+ * `active`: one of the area's pages is open (its own page included).
*/
-export function MegaLauncher({
- id,
- active,
- current,
- onTap,
- className,
-}: {
- id: MegaId;
- active?: boolean;
- current?: boolean;
- onTap?: (href: string) => void;
- className?: string;
-}) {
- const { openMenu, setOpenMenu, menuGroup, menuReturnTo } = useNavUi();
- const open = openMenu === id;
+export function MegaLauncher({ id, active, className }: { id: MegaId; active?: boolean; className?: string }) {
const area = MEGA_AREAS[id];
const search = useSearchPalette();
const [warm, setWarm] = useState(false);
- const shown = warm || open;
- const root = useRef<HTMLDivElement>(null);
- const trigger = useRef<HTMLButtonElement>(null);
- const label = useRef<HTMLAnchorElement>(null);
- const panel = useRef<HTMLElement>(null);
- // How it was opened: with its button or a key (focus to the first lead card), from the name (Esc comes back to the
- // name), or from elsewhere (openArea: the group asked for).
- const how = useRef<"button" | "name" | "hover" | null>(null);
- // Opened while another of the bar's grouped menus was open: it takes that one's place without a second entrance.
- const [switched, setSwitched] = useState(false);
- // Counts each opening (a click on a menu the mouse opened counts too: focus moves in then).
- const [opening, setOpening] = useState(0);
-
const heat = useCallback(() => {
warmMenu(id);
preloadMegaPanel();
setWarm(true);
}, [id]);
+ const ready = useCallback(() => panelLoaded && menuReady(id), [id]);
+ const { open, phase, close, entered, style, trigger, surface, triggerRef, surfaceRef } = useBarMenu(id, { big: true, ready, warm: heat });
+ const shown = warm || open;
- const close = useCallback(
- (returnFocus: boolean) => {
- const back = menuReturnTo();
- const from = how.current;
- how.current = null;
- setOpenMenu(null);
- if (returnFocus) (back?.isConnected ? back : from === "name" ? label.current : trigger.current)?.focus();
- },
- [menuReturnTo, setOpenMenu],
- );
- const closeQuietly = useCallback(() => {
- if (openMenu === id) close(false);
- }, [close, openMenu, id]);
-
- const show = useCallback(
- (by: "button" | "name" | "hover") => {
- how.current = by;
- setSwitched(!!openMenu && openMenu !== id);
- setOpening((n) => n + 1);
- heat();
- setOpenMenu(id);
- },
- [heat, openMenu, id, setOpenMenu],
- );
-
- // Resting the mouse opens it (never on its own page, which it would only cover).
- const hover = useHoverIntent(
- open,
- useCallback(() => show("hover"), [show]),
- useCallback(() => close(false), [close]),
- !!current,
- );
-
- useEffect(() => {
- if (!open) return;
- // Opened: the routes one click here leads to start loading.
- warmNav(WARM[id]);
- // Opened by resting the mouse: focus stays where it was (a prompt being typed keeps its keys).
- if (how.current === "hover") return;
- const byKey = how.current === "button" || how.current === "name";
- // The panel's links may come a moment later (a fetched menu): focus the asked-for column's lead once there.
- const focus = () => {
- const p = panel.current;
- if (!p) return false;
- const group = !byKey && menuGroup ? p.querySelector<HTMLElement>(`[data-group="${menuGroup}"] [data-row="0"]`) : null;
- const at = group ?? p.querySelector<HTMLElement>('[data-col="0"][data-row="0"]');
- at?.focus();
- return !!at;
- };
- if (focus()) return;
- const obs = new MutationObserver(() => focus() && obs.disconnect());
- if (panel.current) obs.observe(panel.current, { childList: true, subtree: true });
- return () => obs.disconnect();
- }, [open, opening, menuGroup, id]);
-
- // While open: a press outside closes it (the press goes on to what it was on), and Esc closes it from anywhere.
+ // Opened: the routes one click here leads to start loading.
useEffect(() => {
- if (!open) return;
- const down = (e: PointerEvent) => {
- // A press on another grouped menu's item opens that one in this one's place (no second entrance), closing this.
- if ((e.target as Element | null)?.closest?.("[data-mega]")) return;
- if (!root.current?.contains(e.target as Node)) close(false);
- };
- const key = (e: KeyboardEvent) => {
- if (e.key !== "Escape" || e.defaultPrevented) return;
- e.preventDefault();
- close(true);
- };
- document.addEventListener("pointerdown", down, true);
- document.addEventListener("keydown", key);
- return () => {
- document.removeEventListener("pointerdown", down, true);
- document.removeEventListener("keydown", key);
- };
- }, [open, close]);
-
- const toggle = (by: "button" | "name") => {
- // Opened by resting the mouse: a click keeps it open (pinned) and moves focus in, as on a closed one.
- if (open && hover.openedByHover()) {
- hover.pin();
- how.current = by;
- setOpening((n) => n + 1);
- return;
- }
- hover.pin();
- if (open) return close(false);
- show(by);
- };
-
- const onPanelKey = (e: React.KeyboardEvent) => {
- const at = (e.target as HTMLElement).closest<HTMLElement>("[data-col]");
- if (!at || !panel.current) return;
- // Columns as the keys see them: the links that show, top to bottom (a row hidden by the window's height is skipped,
- // and a section under another goes on from it).
- const cols: HTMLElement[][] = [];
- for (const el of panel.current.querySelectorAll<HTMLElement>("[data-col]")) {
- if (!shows(el)) continue;
- (cols[Number(el.dataset.col)] ??= []).push(el);
- }
- for (let i = 0; i < cols.length; i++) (cols[i] ??= []).sort((x, y) => Number(x.dataset.row) - Number(y.dataset.row));
- const col = Number(at.dataset.col);
- const row = cols[col]?.indexOf(at) ?? -1;
- if (row < 0) return;
- const next = megaMove(
- cols.map((c) => c.length),
- { col, row },
- e.key,
- );
- if (/^(Arrow|Home$|End$)/.test(e.key)) e.preventDefault();
- if (next) cols[next.col][next.row]?.focus();
- };
-
- // The mouse moves the keyboard's place: the link under it takes focus (quietly: the ring is the keyboard's), so the
- // arrow keys go on from where the mouse left off and only one link is ever highlighted.
- const onPanelPointer = (e: React.PointerEvent) => {
- if (e.pointerType !== "mouse") return;
- const at = (e.target as HTMLElement).closest<HTMLElement>("[data-col]");
- if (at && at !== document.activeElement) at.focus({ preventScroll: true });
- };
+ if (open) warmNav(WARM[id]);
+ }, [open, id]);
const n = id === "studios" ? studioCount() : undefined;
return (
- <div
- ref={root}
- className="contents"
- onBlur={(e) => {
- // Focus went somewhere else on the page (Tab past the last link, a click on a field): close. Focus lost to
- // nothing (a press on the panel's padding) keeps it open; a press outside closes it above.
- const to = e.relatedTarget as Node | null;
- if (open && to && !root.current?.contains(to)) close(false);
- }}
- >
- <div
- data-bar-split
+ <>
+ <BarTrigger
+ id={id}
+ panelId={megaPanelId(id)}
+ href={area.href}
+ name={n !== undefined ? `${area.label}, ${n} studios` : undefined}
+ label={
+ n !== undefined ? (
+ <span className="inline-flex items-center gap-1.5">
+ {area.label}
+ <span className="rounded-full bg-brand-faint px-1.5 py-px text-[11px] leading-4 font-semibold text-brand-text tabular-nums">{n}</span>
+ </span>
+ ) : (
+ area.label
+ )
+ }
+ active={active}
+ open={open}
+ handlers={trigger}
+ triggerRef={triggerRef}
data-mega={id}
- data-active={active || undefined}
- data-open={open || undefined}
- className={cn(BAR_SPLIT, className)}
- // The panel mounts, hidden, so its data and covers load before it opens.
- onPointerEnter={(e) => {
- heat();
- hover.enter(e, !!openMenu && openMenu !== id);
- }}
- onPointerLeave={hover.leave}
+ data-mega-trigger={id}
+ data-studios-trigger={id === "studios" || undefined}
+ className={className}
+ />
+ <section
+ ref={surfaceRef}
+ id={megaPanelId(id)}
+ data-mega-panel={id}
+ data-phase={phase}
+ data-enter={entered}
+ aria-label={area.panel}
+ hidden={phase === "gone"}
+ inert={phase !== "open"}
+ aria-hidden={phase === "exit" || undefined}
+ style={style}
+ {...surface}
+ className={LAUNCHER_PANEL}
>
- <IntentLink
- ref={label}
- href={area.href}
- aria-current={current ? "page" : undefined}
- aria-label={n !== undefined ? `${area.label}, ${n} studios` : undefined}
- className={BAR_LABEL}
- onFocus={heat}
- onClick={(e) => {
- if (open) close(false);
- if (isPlainClick(e)) onTap?.(area.href);
- }}
- onKeyDown={(e) => {
- if (e.key !== "ArrowDown" || e.altKey || e.metaKey || e.ctrlKey || open) return;
- e.preventDefault();
- toggle("name");
- }}
- >
- {area.label}
- {n !== undefined && <span className="rounded-full bg-brand-faint px-1.5 py-px text-[11px] leading-4 font-semibold text-brand-text tabular-nums">{n}</span>}
- </IntentLink>
- <button
- ref={trigger}
- type="button"
- aria-label={area.menu}
- aria-expanded={open}
- // The panel is on the page once warmed (hover, focus) or open.
- aria-controls={shown ? megaPanelId(id) : undefined}
- data-studios-trigger={id === "studios" || undefined}
- data-mega-trigger={id}
- data-state={open ? "open" : "closed"}
- className={BAR_CHEVRON}
- onFocus={heat}
- // Click, Enter and Space open it with focus on the first lead card (arrow keys and Tab go on from there).
- onClick={() => toggle("button")}
- onKeyDown={(e) => {
- if (e.key !== "ArrowDown" || open) return;
- e.preventDefault();
- toggle("button");
- }}
- >
- <BarChevron />
- </button>
- </div>
- {shown && (
- <section
- ref={panel}
- id={megaPanelId(id)}
- data-mega-panel={id}
- aria-label={area.panel}
- hidden={!open}
- inert={!open}
- onKeyDown={onPanelKey}
- onPointerMove={onPanelPointer}
- onClick={(e) => {
- if ((e.target as Element).closest("a[href]")) close(false);
- }}
- onPointerEnter={hover.enter}
- onPointerLeave={hover.leave}
- data-switched={switched || undefined}
- className={cn(LAUNCHER_PANEL, switched && "motion-safe:animate-none")}
- >
- {/* The body's place while its chunk loads: the count line's height, then the columns' skeleton. */}
+ {shown && (
+ /* The body's place while its chunk loads: the count line's height, then the columns' skeleton. */
<Suspense
fallback={
<div className="max-w-[1440px] px-6 pt-5 pb-6 lg:pt-6 lg:pb-7">
@@ -367,7 +185,7 @@ export function MegaLauncher({
>
<LazyPanel
id={id}
- onClose={closeQuietly}
+ onClose={close}
onSearch={() => {
// The item gets focus first, so it is where Esc in the search comes back to (the panel is gone by then).
close(true);
@@ -375,28 +193,17 @@ export function MegaLauncher({
}}
/>
</Suspense>
- </section>
- )}
- </div>
+ )}
+ </section>
+ </>
);
}
/** The bar's Studios item (MegaLauncher for Studios). */
-export function StudiosLauncher(props: { active?: boolean; current?: boolean; onTap?: (href: string) => void }) {
+export function StudiosLauncher(props: { active?: boolean }) {
return <MegaLauncher id="studios" {...props} />;
}
-/** Dims the page under an open grouped menu (decoration: presses go through to the page, which closes the menu). */
-export function MegaScrim() {
- const { openMenu } = useNavUi();
- if (!openMenu) return null;
- return (
- <div
- aria-hidden
- className="pointer-events-none fixed inset-x-0 top-14 bottom-0 z-[39] hidden bg-overlay md:block motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-150 print:hidden"
- />
- );
-}
-
-/** Kept name: the scrim under the launcher. */
-export const LauncherScrim = MegaScrim;
+/** Kept names: the dimmed page under the bar's menus (one for all six: BarScrim). */
+export const MegaScrim = BarScrim;
+export const LauncherScrim = BarScrim;
diff --git a/src/components/nav/mega-panel.tsx b/src/components/nav/mega-panel.tsx
index 9f5d5f0d..1d168ccf 100644
--- a/src/components/nav/mega-panel.tsx
+++ b/src/components/nav/mega-panel.tsx
@@ -365,6 +365,7 @@ export function MegaPanel({ id, onClose, onSearch }: { id: MegaId; onClose: () =
href={area.href}
aria-current={pathname === area.href ? "page" : undefined}
aria-label={model?.seeAll.name ?? `See all ${area.label.toLowerCase()}`}
+ data-see-all
className="nav-row group/all -ml-1 inline-flex h-9 items-center gap-1 rounded-[10px] px-2 text-[13px] font-medium text-brand-text"
>
See all
diff --git a/src/components/nav/nav-row.tsx b/src/components/nav/nav-row.tsx
index 339dae28..5e6b61ea 100644
--- a/src/components/nav/nav-row.tsx
+++ b/src/components/nav/nav-row.tsx
@@ -41,16 +41,24 @@ export function NavMenuItem({ className, onPointerLeave, ...props }: React.Compo
);
}
-/** "See all" at the foot of a menu: the area's own page, a one-line row in the brand's colour (`name`: for a screen reader). */
-export function SeeAllRow({ href, name, className }: { href: string; name: string; className?: string }) {
+/** A row of a bar card (Create, More): a plain link with the nav's states (the bar's controller moves focus with the mouse). */
+export const CARD_ROW =
+ "nav-row nav-mark-start flex cursor-pointer items-center gap-3 rounded-[10px] px-2.5 text-[13.5px] select-none [&_svg]:pointer-events-none [&_svg]:shrink-0";
+
+/** "See all": the area's own page, a one-line link in the brand's colour (`name`: for a screen reader). */
+export function SeeAllRow({ href, name, className, ...rest }: { href: string; name: string; className?: string } & Omit<React.ComponentProps<typeof IntentLink>, "href">) {
const pathname = usePathname();
return (
- <NavMenuItem asChild className={cn("group/all h-10 gap-2 font-medium text-brand-text", className)}>
- <IntentLink href={href} aria-current={pathname === href ? "page" : undefined} aria-label={name}>
- See all
- <ArrowRight aria-hidden className="size-4 motion-safe:transition-transform group-data-[highlighted]/all:translate-x-0.5" />
- </IntentLink>
- </NavMenuItem>
+ <IntentLink
+ href={href}
+ aria-current={pathname === href ? "page" : undefined}
+ aria-label={name}
+ className={cn(CARD_ROW, "group/all h-10 gap-2 font-medium text-brand-text", className)}
+ {...rest}
+ >
+ See all
+ <ArrowRight aria-hidden className="size-4 motion-safe:transition-transform group-hover/all:translate-x-0.5 group-focus-visible/all:translate-x-0.5" />
+ </IntentLink>
);
}
diff --git a/src/components/nav/nav-ui.tsx b/src/components/nav/nav-ui.tsx
index 45beeb53..fd546f85 100644
--- a/src/components/nav/nav-ui.tsx
+++ b/src/components/nav/nav-ui.tsx
@@ -4,6 +4,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use
import { useHydrated, useViewer } from "@/lib/api";
import type { NavCover, NavCovers } from "@/lib/nav-covers";
import type { MegaId } from "@/lib/mega-menus";
+import { barMenus, CLOSED_MENUS, type BarMenuAction, type BarMenuId, type BarMenuState } from "@/lib/bar-intent";
import { viewerKindOf, type LauncherGroupId, type ViewerKind } from "@/lib/nav-model";
import { installInputModality } from "./input-modality";
@@ -19,9 +20,16 @@ export type NavSheet = "studios" | "create" | "you";
export const PHONE_QUERY = "(max-width: 767px)";
export interface NavUi {
- /** The bar's open grouped menu (Studios, Apps, Motions & effects, Canvas): one at a time. */
- openMenu: MegaId | null;
- setOpenMenu(v: MegaId | null): void;
+ /** The bar's open menu (Create, Studios, Apps, Motions & effects, Canvas, More): one at a time. */
+ openMenu: BarMenuId | null;
+ /** The whole menu state: how it was opened, the menu it replaced (bar-intent.ts). */
+ menu: BarMenuState;
+ /** Changes it (bar-intent.ts's reducer); returns the new state at once. */
+ menuAct(a: BarMenuAction): BarMenuState;
+ /** The menu state now (for timers and handlers: never a render behind). */
+ menuNow(): BarMenuState;
+ /** Opens a menu pinned (by its own button), or closes the open one (null). */
+ setOpenMenu(v: BarMenuId | null): void;
/** The column the open menu was opened for (openArea(id, group)): it takes focus first. */
menuGroup: string | undefined;
/** Where focus goes back to when the menu closes with Esc: what opened it, when that was not its own button. */
@@ -42,17 +50,31 @@ const NavUiContext = createContext<NavUi | null>(null);
const CoversContext = createContext<NavCovers>({});
export function NavUiProvider({ covers, children }: { covers: NavCovers; children: React.ReactNode }) {
- const [menu, setMenu] = useState<{ id: MegaId | null; group?: string }>({ id: null });
+ const [menu, setMenu] = useState<BarMenuState>(CLOSED_MENUS);
+ const menuRef = useRef<BarMenuState>(CLOSED_MENUS);
const [sheet, setSheetState] = useState<{ sheet: NavSheet | null; family: MegaId; group?: string }>({ sheet: null, family: "studios" });
const menuReturn = useRef<HTMLElement | null>(null);
// Which input leads (keyboard or pointer), for the nav states: one highlighted row at a time.
useEffect(() => installInputModality(), []);
- // Opened or closed by a menu's own button: focus goes back to it. openArea() says otherwise.
- const setOpenMenu = useCallback((id: MegaId | null) => {
- menuReturn.current = null;
- setMenu((m) => (m.id === id && !m.group ? m : { id }));
+ const menuAct = useCallback((a: BarMenuAction) => {
+ const next = barMenus(menuRef.current, a);
+ if (next !== menuRef.current) {
+ menuRef.current = next;
+ setMenu(next);
+ }
+ return next;
}, []);
+ const menuNow = useCallback(() => menuRef.current, []);
+ // Opened or closed by a menu's own button: focus goes back to it. openArea() says otherwise.
+ const setOpenMenu = useCallback(
+ (id: BarMenuId | null) => {
+ menuReturn.current = null;
+ const now = performance.now();
+ menuAct(id ? { type: "open", id, mode: "pinned", via: "pointer", clicked: true, now } : { type: "close", now });
+ },
+ [menuAct],
+ );
const menuReturnTo = useCallback(() => menuReturn.current, []);
const setSheet = useCallback((v: NavSheet | null) => setSheetState((s) => ({ sheet: v, family: v === "studios" && s.sheet === "studios" ? s.family : "studios" })), []);
const openArea = useCallback((id: MegaId, group?: string) => {
@@ -63,13 +85,16 @@ export function NavUiProvider({ covers, children }: { covers: NavCovers; childre
}
const at = typeof document !== "undefined" ? document.activeElement : null;
menuReturn.current = at instanceof HTMLElement && at !== document.body ? at : null;
- setMenu({ id, group });
- }, []);
+ menuAct({ type: "open", id, mode: "pinned", via: "area", group, clicked: true, now: performance.now() });
+ }, [menuAct]);
const openStudios = useCallback((group?: LauncherGroupId) => openArea("studios", group), [openArea]);
const ui = useMemo<NavUi>(
() => ({
openMenu: menu.id,
+ menu,
+ menuAct,
+ menuNow,
setOpenMenu,
menuGroup: menu.id ? menu.group : undefined,
menuReturnTo,
@@ -80,7 +105,7 @@ export function NavUiProvider({ covers, children }: { covers: NavCovers; childre
openArea,
openStudios,
}),
- [menu, sheet, setOpenMenu, menuReturnTo, setSheet, openArea, openStudios],
+ [menu, sheet, menuAct, menuNow, setOpenMenu, menuReturnTo, setSheet, openArea, openStudios],
);
return (
@@ -92,6 +117,9 @@ export function NavUiProvider({ covers, children }: { covers: NavCovers; childre
const CLOSED: NavUi = {
openMenu: null,
+ menu: CLOSED_MENUS,
+ menuAct: () => CLOSED_MENUS,
+ menuNow: () => CLOSED_MENUS,
setOpenMenu: () => {},
menuGroup: undefined,
menuReturnTo: () => null,
diff --git a/src/components/nav/top-bar.tsx b/src/components/nav/top-bar.tsx
index cc8ef47d..97b55e48 100644
--- a/src/components/nav/top-bar.tsx
+++ b/src/components/nav/top-bar.tsx
@@ -1,10 +1,9 @@
"use client";
-import { ChevronDown, MoreHorizontal, Plus, Search } from "lucide-react";
+import { MoreHorizontal, Plus, Search } from "lucide-react";
import { usePathname } from "next/navigation";
-import { Suspense, useEffect } from "react";
+import { Suspense, useEffect, useRef } from "react";
import { IntentLink } from "@/components/intent-link";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { NEW_CREATION_HREF } from "@/lib/nav";
import { area, areaOfPath, areaPageOf, type AreaId } from "@/lib/nav-areas";
@@ -13,15 +12,16 @@ import { isPlainClick, useTappedTab } from "@/lib/use-tapped-tab";
import { cn } from "@/lib/utils";
import { CoverThumb, NavIcon } from "./cover-thumb";
import { CreateMenu } from "./create-menu";
-import { MENU_ROW_2, NavMenuItem, ROW_LINE, rowName, SeeAllRow } from "./nav-row";
-import { useViewerKind } from "./nav-ui";
+import { CARD_ROW, MENU_ROW_2, ROW_LINE, rowName, SeeAllRow } from "./nav-row";
+import { useNavUi, useViewerKind } from "./nav-ui";
import { useSearchPalette } from "./search-context";
import { BarPills } from "./status-chips";
import { NavPrefetcher, warmNav } from "./nav-prefetch";
import type { FetchedMegaId } from "@/lib/mega-menus";
-import { queueIdlePrefetch } from "@/lib/idle-prefetch";
-import { prefetchMenus } from "./mega-data";
-import { MegaLauncher, MegaScrim, preloadMegaPanel } from "./mega-launcher";
+import { loadMenusNow } from "./mega-data";
+import { MegaLauncher, preloadMegaPanel } from "./mega-launcher";
+import { BarCardMenu } from "./bar-split";
+import { BarIndicator, BarMenusProvider, BarScrim, BarStage, CloseMenusOnRoute, useBarController } from "./bar-menus";
import { ViewerSlot } from "./viewer-slot";
export { prefetchHrefs } from "./nav-prefetch";
@@ -40,9 +40,9 @@ export { prefetchHrefs } from "./nav-prefetch";
*/
/**
- * A bar item (link, menu button, the launcher's button). Its states are the nav's (nav-states.css): the highlight on
- * hover or keyboard focus, foreground words and a turned chevron while its menu is open, and for the open page (aria-current, or data-active: the page is
- * one of its destinations) a pip under the words, never a fill.
+ * A plain bar link (Assist, Library). Its states are the nav's (nav-states.css): the highlight on hover or keyboard
+ * focus, and for the open page (aria-current) a pip under the words, never a fill. The items with a menu are
+ * BAR_TRIGGER (bar-split.tsx).
*/
export const BAR_ITEM =
"nav-row nav-mark-under group/bar-item inline-flex h-10 shrink-0 [@media(pointer:coarse)]:h-11 items-center gap-1.5 rounded-[10px] px-2.5 text-[14px] whitespace-nowrap text-foreground/80 nav-hover:text-foreground focus-visible:text-foreground data-[state=open]:text-foreground data-[active]:font-semibold data-[active]:text-foreground aria-[current=page]:font-semibold aria-[current=page]:text-foreground min-[1440px]:px-3.5";
@@ -82,17 +82,15 @@ export function barActive(pathname: string): {
type Active = ReturnType<typeof barActive>;
const NONE: Active = barActive("");
-function RichItem({ e, current }: { e: NavEntry; current: boolean }) {
+function RichItem({ e, current, row }: { e: NavEntry; current: boolean; row: number }) {
return (
- <NavMenuItem asChild className={MENU_ROW_2}>
- <IntentLink href={e.href} aria-current={current ? "page" : undefined}>
- <CoverThumb id={e.cover} size="row" icon={e.icon} eager />
- <span className="flex min-w-0 flex-col">
- <span className={rowName(current)}>{e.label}</span>
- <span className={ROW_LINE}>{e.what}</span>
- </span>
- </IntentLink>
- </NavMenuItem>
+ <IntentLink href={e.href} aria-current={current ? "page" : undefined} data-col={0} data-row={row} className={cn(CARD_ROW, MENU_ROW_2)}>
+ <CoverThumb id={e.cover} size="row" icon={e.icon} eager />
+ <span className="flex min-w-0 flex-col">
+ <span className={rowName(current)}>{e.label}</span>
+ <span className={ROW_LINE}>{e.what}</span>
+ </span>
+ </IntentLink>
);
}
@@ -110,52 +108,49 @@ function MoreItems() {
const on = useOn();
return (
<>
- {pick(["apps", "motions", "effects"]).map((e) => (
+ {pick(["apps", "motions", "effects"]).map((e, i) => (
<div key={e.id} className="xl:hidden">
- <RichItem e={e} current={on(e)} />
+ <RichItem e={e} current={on(e)} row={i} />
</div>
))}
<div className="xl:hidden">
- <SeeAllRow href={MOTIONS_AREA_HREF} name="See all motions & effects" className="mt-1" />
- <DropdownMenuSeparator className="mx-2.5 my-1.5" />
+ <SeeAllRow href={MOTIONS_AREA_HREF} name="See all motions & effects" data-col={0} data-row={3} className="mt-1" />
+ <div role="separator" className="mx-2.5 my-1.5 h-px bg-border" />
</div>
- {pick(["canvas", "assist"]).map((e) => {
- return (
- <NavMenuItem key={e.id} asChild className={MENU_ROW_2}>
- <IntentLink href={e.href} eager={e.eager} aria-current={on(e) ? "page" : undefined}>
- <span className="grid h-[27px] w-9 shrink-0 place-items-center rounded-[6px] bg-muted">
- <NavIcon name={e.icon} className="nav-icon size-4 text-muted-foreground" />
- </span>
- <span className="flex min-w-0 flex-col">
- <span className={rowName(on(e))}>{e.label}</span>
- <span className={ROW_LINE}>{e.what}</span>
- </span>
- </IntentLink>
- </NavMenuItem>
- );
- })}
+ {pick(["canvas", "assist"]).map((e, i) => (
+ <IntentLink key={e.id} href={e.href} eager={e.eager} aria-current={on(e) ? "page" : undefined} data-col={0} data-row={4 + i} className={cn(CARD_ROW, MENU_ROW_2)}>
+ <span className="grid h-[27px] w-9 shrink-0 place-items-center rounded-[6px] bg-muted">
+ <NavIcon name={e.icon} className="nav-icon size-4 text-muted-foreground" />
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className={rowName(on(e))}>{e.label}</span>
+ <span className={ROW_LINE}>{e.what}</span>
+ </span>
+ </IntentLink>
+ ))}
</>
);
}
-/** More: the bar's items that don't fit at this width (each hides here where the bar shows it). */
+/** Opened: the routes its rows lead to start loading. */
+const warmMore = () => warmNav("more");
+
+/** More: the bar's items that don't fit at this width (each hides here where the bar shows it). One button, as every menu item. */
function MoreMenu({ active }: { active: Active }) {
return (
- <DropdownMenu modal={false} onOpenChange={(o) => o && warmNav("more")}>
- <DropdownMenuTrigger
- // Marked when it holds the open page at this width: Canvas and Assist always; Apps, Motions and Effects below xl.
- className={cn(BAR_ITEM, "min-[1440px]:hidden max-xl:data-[narrow]:font-semibold max-xl:data-[narrow]:text-foreground")}
- data-active={active.canvas || active.assist || undefined}
- data-narrow={active.apps || active.motions || undefined}
- >
- <MoreHorizontal aria-hidden className="size-4" />
- More
- <ChevronDown aria-hidden className="size-3.5 text-muted-foreground group-data-[state=open]/bar-item:rotate-180 motion-safe:transition-transform" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" sideOffset={8} className="w-80 p-1.5">
- <MoreItems />
- </DropdownMenuContent>
- </DropdownMenu>
+ <BarCardMenu
+ id="more"
+ label="More"
+ icon={<MoreHorizontal aria-hidden className="size-4" />}
+ onOpen={warmMore}
+ cardClassName="w-80"
+ className="min-[1440px]:hidden"
+ // Marked when it holds the open page at this width: Canvas and Assist always; Apps, Motions and Effects below xl.
+ active={active.canvas || active.assist}
+ data-narrow={active.apps || active.motions || undefined}
+ >
+ <MoreItems />
+ </BarCardMenu>
);
}
@@ -168,16 +163,16 @@ function BarLinks({ active, onTap }: { active: Active; onTap?: (href: string) =>
const tap = (href: string) => (e: React.MouseEvent) => isPlainClick(e) && onTap?.(href);
return (
<>
- <CreateMenu active={active.create} current={active.page === "create"} onTap={onTap} />
- <MegaLauncher id="studios" active={active.studios} current={active.page === "studios"} onTap={onTap} />
- {/* /apps is the area's own page (its name is marked); an app's page marks the item. */}
- <MegaLauncher id="apps" active={active.apps && active.page !== "apps"} current={active.page === "apps"} onTap={onTap} className="hidden xl:inline-flex" />
- <MegaLauncher id="motions" active={active.motions} current={active.page === "motions"} onTap={onTap} className="hidden xl:inline-flex" />
- <MegaLauncher id="canvas" active={active.canvas && !active.canvasHome} current={active.canvasHome} onTap={onTap} className="hidden min-[1440px]:inline-flex" />
- <IntentLink href="/assist" eager onClick={tap("/assist")} aria-current={cur(active.assist)} className={cn(BAR_ITEM, "hidden min-[1440px]:inline-flex")}>
+ {/* An item is marked anywhere in its area, its own page (/create, /studios …) included. */}
+ <CreateMenu active={active.create || active.page === "create"} />
+ <MegaLauncher id="studios" active={active.studios || active.page === "studios"} />
+ <MegaLauncher id="apps" active={active.apps || active.page === "apps"} className="hidden xl:inline-flex" />
+ <MegaLauncher id="motions" active={active.motions || active.page === "motions"} className="hidden xl:inline-flex" />
+ <MegaLauncher id="canvas" active={active.canvas || active.canvasHome} className="hidden min-[1440px]:inline-flex" />
+ <IntentLink href="/assist" eager data-bar-item="" onClick={tap("/assist")} aria-current={cur(active.assist)} className={cn(BAR_ITEM, "hidden min-[1440px]:inline-flex")}>
Assist
</IntentLink>
- <IntentLink href="/library" eager onClick={tap("/library")} aria-current={cur(active.library)} className={BAR_ITEM}>
+ <IntentLink href="/library" eager data-bar-item="" onClick={tap("/library")} aria-current={cur(active.library)} className={BAR_ITEM}>
Library
</IntentLink>
<MoreMenu active={active} />
@@ -255,44 +250,70 @@ function RightCluster() {
}
/**
- * Once the page has loaded and the browser is idle: the panels' body (its own chunk) and the data (no pictures) of the
- * grouped menus whose item the bar shows at this width, so the first open never waits for them. A phone loads none
- * (its sheet asks when it shows one).
+ * Everything the bar's menus need before their first open: the panels' body (its own chunk) and the data (no
+ * pictures) of the grouped menus whose item the bar shows at this width. A phone loads none (its sheet asks when it
+ * shows one); a browser saving data loads only the code.
*/
+export function warmBar(): void {
+ if (!window.matchMedia("(min-width: 768px)").matches) return;
+ const ids: FetchedMegaId[] = [];
+ if (window.matchMedia("(min-width: 1280px)").matches) ids.push("apps", "motions");
+ if (window.matchMedia("(min-width: 1440px)").matches) ids.push("canvas");
+ preloadMegaPanel();
+ loadMenusNow(ids);
+}
+
+/** Soon after the page is ready (idle, or 1.5 s at the latest), so the first hover never meets a skeleton. */
function MenuPrefetch() {
useEffect(() => {
- if (!window.matchMedia("(min-width: 768px)").matches) return;
- const ids: FetchedMegaId[] = [];
- if (window.matchMedia("(min-width: 1280px)").matches) ids.push("apps", "motions");
- if (window.matchMedia("(min-width: 1440px)").matches) ids.push("canvas");
- let cancel = () => {};
- const go = () => {
- const body = queueIdlePrefetch("nav", "mega-panel", preloadMegaPanel);
- const data = prefetchMenus(ids);
- cancel = () => {
- body();
- data();
- };
- };
- if (document.readyState === "complete") go();
- else window.addEventListener("load", go, { once: true });
- return () => {
- window.removeEventListener("load", go);
- cancel();
- };
+ if (typeof window.requestIdleCallback !== "function") {
+ const t = window.setTimeout(warmBar, 300);
+ return () => window.clearTimeout(t);
+ }
+ const h = window.requestIdleCallback(warmBar, { timeout: 1500 });
+ return () => window.cancelIdleCallback(h);
}, []);
return null;
}
+/** The main nav: its keys (Left and Right along the items); the first pointer or focus near it warms the menus. */
+function MainNav({ children }: { children: React.ReactNode }) {
+ const ctl = useBarController();
+ const warmed = useRef(false);
+ const warm = () => {
+ if (warmed.current) return;
+ warmed.current = true;
+ warmBar();
+ };
+ return (
+ <nav aria-label="Main" className="flex min-w-0 items-center gap-0.5" onKeyDown={(e) => ctl?.navKey(e)} onPointerEnter={warm} onFocus={warm}>
+ {children}
+ </nav>
+ );
+}
+
+/** The bar's header: marked while a menu is open (the items' own hover fill steps aside for the open highlight). */
+function BarHeader({ children }: { children: React.ReactNode }) {
+ const { openMenu } = useNavUi();
+ return (
+ <header
+ data-top-bar
+ data-menu-open={openMenu ? "" : undefined}
+ className="sticky top-0 z-40 hidden h-14 items-center gap-1 border-b border-sidebar-border bg-sidebar/90 pr-4 pl-5 backdrop-blur-md md:flex lg:max-[1439.98px]:pr-5 min-[1440px]:pr-6 print:hidden"
+ >
+ {children}
+ </header>
+ );
+}
+
/** The bar. Hidden below md and in print; same height on every page, full-screen studios included. */
export function TopBar() {
return (
- <>
- <header
- data-top-bar
- className="sticky top-0 z-40 hidden h-14 items-center gap-1 border-b border-sidebar-border bg-sidebar/90 pr-4 pl-5 backdrop-blur-md md:flex lg:max-[1439.98px]:pr-5 min-[1440px]:pr-6 print:hidden"
- >
- <nav aria-label="Main" className="flex min-w-0 items-center gap-0.5">
+ <BarMenusProvider>
+ <BarHeader>
+ <BarStage />
+ <BarIndicator />
+ <MainNav>
<IntentLink
href="/"
eager
@@ -304,15 +325,18 @@ export function TopBar() {
<Suspense fallback={<BarLinks active={NONE} />}>
<ActiveBarLinks />
</Suspense>
- </nav>
+ </MainNav>
<span className="min-w-2 flex-1" />
<div className="flex shrink-0 items-center gap-2">
<RightCluster />
</div>
- </header>
- <MegaScrim />
+ </BarHeader>
+ <BarScrim />
+ <Suspense fallback={null}>
+ <CloseMenusOnRoute />
+ </Suspense>
<NavPrefetcher />
<MenuPrefetch />
- </>
+ </BarMenusProvider>
);
}
diff --git a/src/lib/bar-intent.ts b/src/lib/bar-intent.ts
new file mode 100644
index 00000000..0a23a66f
--- /dev/null
+++ b/src/lib/bar-intent.ts
@@ -0,0 +1,160 @@
+import { NAV_INTENT } from "./ui-motion";
+
+/*
+ * The top bar's menus as plain logic (no React, no DOM): which menu is open and how, when resting the pointer on an
+ * item opens it, and whether the pointer is heading into the open menu (the "safe triangle"). The controller
+ * (components/nav/bar-menus.tsx) feeds it events and owns the one timer; tests/bar-intent.test.ts covers it.
+ *
+ * One menu at most is open. Opening one replaces the open one in place (never close-then-open, so a switch never has a
+ * frame with nothing open), and a close names its menu: a late timer for a menu that is no longer open does nothing.
+ */
+
+/** The bar's six menu items, left to right (the order a switch slides in). */
+export const BAR_MENUS = ["create", "studios", "apps", "motions", "canvas", "more"] as const;
+export type BarMenuId = (typeof BAR_MENUS)[number];
+
+/** Opened by resting the pointer (closes when the pointer leaves) or pinned by a click, a tap or a key. */
+export type MenuMode = "hover" | "pinned";
+/** What opened it: the mouse, the keyboard, a finger or pen, or a button elsewhere on the page (openArea). */
+export type MenuVia = "pointer" | "key" | "touch" | "area";
+
+export interface BarMenuState {
+ id: BarMenuId | null;
+ mode: MenuMode;
+ via: MenuVia;
+ /** The column asked for (openArea(id, group)): it takes focus first. */
+ group?: string;
+ /**
+ * Opened by a click, a tap or a key on this item (or a button elsewhere): the next click on it closes it. A menu the
+ * pointer opened, or switched to while another was pinned, is only pinned by a click, never closed.
+ */
+ clicked: boolean;
+ /** The menu this one replaced (a switch), or null when it opened from nothing. */
+ prev: BarMenuId | null;
+ /** When the last menu closed (performance.now ms), for the switch window. */
+ closedAt: number;
+ /** Counts every open, switch and re-open by a key or a button (focus moves in once per count). */
+ seq: number;
+}
+
+export const CLOSED_MENUS: BarMenuState = { id: null, mode: "hover", via: "pointer", clicked: false, prev: null, closedAt: Number.NEGATIVE_INFINITY, seq: 0 };
+
+export type BarMenuAction =
+ /**
+ * Open `id` (replacing the open menu in place). A hover open never unpins a pinned menu. `clicked`: by this item's
+ * own click or key (the next click closes it).
+ */
+ | { type: "open"; id: BarMenuId; mode: MenuMode; via: MenuVia; group?: string; clicked?: boolean; now: number }
+ /** A click or tap on an item: open it pinned; pin it when the pointer opened it; close it when pinned. */
+ | { type: "click"; id: BarMenuId; via: MenuVia; now: number }
+ /** Close the open menu, or (with `id`) only if `id` is the open one. */
+ | { type: "close"; id?: BarMenuId; now: number };
+
+export function barMenus(s: BarMenuState, a: BarMenuAction): BarMenuState {
+ switch (a.type) {
+ case "open": {
+ if (s.id === a.id) {
+ const mode: MenuMode = s.mode === "pinned" || a.mode === "pinned" ? "pinned" : "hover";
+ const refocus = a.via === "key" || a.via === "area";
+ const clicked = s.clicked || !!a.clicked;
+ if (mode === s.mode && !refocus && a.group === s.group && clicked === s.clicked) return s;
+ return { ...s, mode, clicked, via: a.mode === "pinned" ? a.via : s.via, group: a.group, seq: refocus ? s.seq + 1 : s.seq };
+ }
+ return { id: a.id, mode: a.mode, via: a.via, clicked: !!a.clicked, group: a.group, prev: s.id, closedAt: s.closedAt, seq: s.seq + 1 };
+ }
+ case "click": {
+ if (s.id === a.id) {
+ if (!s.clicked) return { ...s, mode: "pinned", via: a.via, clicked: true };
+ return barMenus(s, { type: "close", id: a.id, now: a.now });
+ }
+ return barMenus(s, { type: "open", id: a.id, mode: "pinned", via: a.via, clicked: true, now: a.now });
+ }
+ case "close": {
+ if (s.id === null || (a.id !== undefined && a.id !== s.id)) return s;
+ return { ...s, id: null, prev: null, group: undefined, mode: "hover", clicked: false, closedAt: a.now };
+ }
+ }
+}
+
+/** While a menu is open, or just after one closed, entering another item opens it at once (no rest). */
+export function switchesAtOnce(s: BarMenuState, now: number, window: number = NAV_INTENT.switchWindow): boolean {
+ return s.id !== null || now - s.closedAt < window;
+}
+
+/** The direction a switch travels: 1 to the right, -1 to the left, 0 when it opened from nothing. */
+export function switchDirection(prev: BarMenuId | null, id: BarMenuId | null): -1 | 0 | 1 {
+ if (!prev || !id || prev === id) return 0;
+ return BAR_MENUS.indexOf(id) > BAR_MENUS.indexOf(prev) ? 1 : -1;
+}
+
+/* ----- Rest: the pointer has stopped on an item. ----- */
+
+export interface Rest {
+ /** When the pointer came onto the item. */
+ enterAt: number;
+ /** Where and when it last stopped (moves within `restSlop` of here count as resting). */
+ anchor: { x: number; y: number; t: number };
+}
+
+export function restStart(x: number, y: number, t: number): Rest {
+ return { enterAt: t, anchor: { x, y, t } };
+}
+
+/** A move over the item: one more than `slop` px from the anchor starts the rest again from here. */
+export function restMove(r: Rest, x: number, y: number, t: number, slop: number = NAV_INTENT.restSlop): Rest {
+ if (Math.hypot(x - r.anchor.x, y - r.anchor.y) <= slop) return r;
+ return { ...r, anchor: { x, y, t } };
+}
+
+/** When the menu opens if the pointer stays: `rest` after it stopped, and never later than `cap` after it came. */
+export function restDue(r: Rest, rest: number = NAV_INTENT.rest, cap: number = NAV_INTENT.restCap): number {
+ return Math.min(r.anchor.t + rest, r.enterAt + cap);
+}
+
+/* ----- The safe triangle: the pointer heading from an item into its open menu. ----- */
+
+export interface Pt {
+ x: number;
+ y: number;
+}
+export interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+export interface Move extends Pt {
+ t: number;
+}
+
+const side = (p: Pt, a: Pt, b: Pt) => (p.x - b.x) * (a.y - b.y) - (a.x - b.x) * (p.y - b.y);
+
+/** Whether `p` is inside the triangle a, b, c (its edges count). */
+export function inTriangle(p: Pt, a: Pt, b: Pt, c: Pt): boolean {
+ const d1 = side(p, a, b);
+ const d2 = side(p, b, c);
+ const d3 = side(p, c, a);
+ const neg = d1 < 0 || d2 < 0 || d3 < 0;
+ const pos = d1 > 0 || d2 > 0 || d3 > 0;
+ return !(neg && pos);
+}
+
+const inBox = (p: Pt, b: Box) => p.x >= b.left && p.x <= b.right && p.y >= b.top && p.y <= b.bottom;
+
+/**
+ * The pointer is on its way into the open menu: inside the triangle from where it left the item (`exit`) to the menu's
+ * two top corners (widened by `pad`), still moving (the last move under `stop` ms ago, faster than 0.05 px/ms) and
+ * downwards. `moves`: the last few pointer moves, oldest first.
+ */
+export function aiming(exit: Pt | null, menu: Box | null, moves: readonly Move[], now: number, pad = 8, stop: number = NAV_INTENT.aimStop): boolean {
+ if (!exit || !menu || moves.length < 2) return false;
+ const last = moves[moves.length - 1];
+ const first = moves[0];
+ if (now - last.t > stop) return false;
+ const dt = Math.max(1, last.t - first.t);
+ const dx = last.x - first.x;
+ const dy = last.y - first.y;
+ if (dy <= 0 || Math.hypot(dx, dy) / dt < 0.05) return false;
+ if (inBox(last, menu)) return true;
+ return inTriangle(last, exit, { x: menu.left - pad, y: menu.top }, { x: menu.right + pad, y: menu.top });
+}
diff --git a/src/lib/ui-motion.ts b/src/lib/ui-motion.ts
index f04a6983..d922880f 100644
--- a/src/lib/ui-motion.ts
+++ b/src/lib/ui-motion.ts
@@ -334,3 +334,32 @@ export function fadeInOnLoad(img: HTMLImageElement, { offScreenOnly = false }: {
if (img.complete) return fail();
img.dataset.fade = "wait";
}
+
+/**
+ * The top-bar menus' intent timings (ms, px). Not motion: they stay the same under reduced motion, because they guard
+ * against menus opening by accident while the pointer crosses the bar.
+ */
+export const NAV_INTENT = {
+ /** The pointer rests this long on an item before its menu opens. */
+ rest: 120,
+ /** "Rests" = stays within this many px of where it stopped. */
+ restSlop: 8,
+ /** The menu opens anyway after this long on one item. */
+ restCap: 600,
+ /** A menu the pointer opened closes this long after the pointer left it and its item. */
+ grace: 300,
+ /** An item entered this soon after a menu closed opens at once (and at once while one is open). */
+ switchWindow: 300,
+ /** A switch waits at most this long while the pointer heads into the open menu. */
+ aimHold: 100,
+ /** Heading into the open menu holds a close at most this long beyond the grace. */
+ aimMax: 300,
+ /** A pointer that has not moved for this long has stopped (no longer heading anywhere). */
+ aimStop: 60,
+ /** A hover open waits at most this long for its menu's data. */
+ dataWait: 150,
+ /** A loading menu shows its skeleton only after this long. */
+ skeletonGrace: 150,
+ /** The dimmed page starts to fade only once nothing has been open this long. */
+ scrimHold: 120,
+} as const;
diff --git a/tests/bar-intent.test.ts b/tests/bar-intent.test.ts
new file mode 100644
index 00000000..037bd2f6
--- /dev/null
+++ b/tests/bar-intent.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from "vitest";
+import {
+ aiming,
+ barMenus,
+ CLOSED_MENUS,
+ inTriangle,
+ restDue,
+ restMove,
+ restStart,
+ switchDirection,
+ switchesAtOnce,
+ type BarMenuState,
+ type Move,
+} from "@/lib/bar-intent";
+import { NAV_INTENT } from "@/lib/ui-motion";
+
+/*
+ * The top bar's menus as plain logic (src/lib/bar-intent.ts): one menu at a time, opened in place, closes that name
+ * their menu (so a late timer never closes the menu you moved to), the rest that keeps a glide along the bar from
+ * opening menus, and the safe triangle into an open menu.
+ */
+
+const open = (s: BarMenuState, id: Parameters<typeof barMenus>[1] extends infer A ? (A extends { type: "open"; id: infer I } ? I : never) : never, mode: "hover" | "pinned" = "hover", now = 0) =>
+ barMenus(s, { type: "open", id, mode, via: "pointer", now });
+
+describe("the menu state", () => {
+ it("opens one menu, and opening another replaces it in place (never two, never none between)", () => {
+ const a = open(CLOSED_MENUS, "studios");
+ expect(a).toMatchObject({ id: "studios", mode: "hover", prev: null });
+ const b = open(a, "apps");
+ expect(b).toMatchObject({ id: "apps", mode: "hover", prev: "studios" });
+ expect(b.seq).toBe(a.seq + 1);
+ });
+
+ it("closeIf: a close for a menu that is no longer open does nothing (the stale-timer bug)", () => {
+ const s = open(open(CLOSED_MENUS, "studios"), "apps");
+ expect(barMenus(s, { type: "close", id: "studios", now: 10 })).toBe(s);
+ const closed = barMenus(s, { type: "close", id: "apps", now: 10 });
+ expect(closed).toMatchObject({ id: null, closedAt: 10, prev: null });
+ expect(barMenus(closed, { type: "close", now: 20 })).toBe(closed);
+ });
+
+ it("a click opens pinned, pins a menu the pointer opened (never closes it), and closes a pinned one", () => {
+ const hover = open(CLOSED_MENUS, "create");
+ const pinned = barMenus(hover, { type: "click", id: "create", via: "pointer", now: 30 });
+ expect(pinned).toMatchObject({ id: "create", mode: "pinned" });
+ const closed = barMenus(pinned, { type: "click", id: "create", via: "pointer", now: 60 });
+ expect(closed.id).toBeNull();
+ const fresh = barMenus(CLOSED_MENUS, { type: "click", id: "more", via: "touch", now: 0 });
+ expect(fresh).toMatchObject({ id: "more", mode: "pinned", via: "touch" });
+ // A click on another item while one is open switches to it, pinned.
+ expect(barMenus(fresh, { type: "click", id: "create", via: "touch", now: 5 })).toMatchObject({ id: "create", mode: "pinned", prev: "more" });
+ });
+
+ it("a click on a menu reached by moving from a pinned one pins it; only a menu its own click opened closes", () => {
+ const pinned = barMenus(CLOSED_MENUS, { type: "click", id: "studios", via: "pointer", now: 0 });
+ expect(pinned.clicked).toBe(true);
+ // Onto Apps with the pointer: it takes over, pinned (a menubar), but not by its own click.
+ const moved = open(pinned, "apps", "pinned");
+ expect(moved).toMatchObject({ id: "apps", mode: "pinned", clicked: false });
+ const click1 = barMenus(moved, { type: "click", id: "apps", via: "pointer", now: 10 });
+ expect(click1).toMatchObject({ id: "apps", mode: "pinned", clicked: true });
+ expect(barMenus(click1, { type: "click", id: "apps", via: "pointer", now: 20 }).id).toBeNull();
+ // A key open counts as the item's own (Enter next closes it).
+ const key = barMenus(CLOSED_MENUS, { type: "open", id: "canvas", mode: "pinned", via: "key", clicked: true, now: 0 });
+ expect(barMenus(key, { type: "click", id: "canvas", via: "key", now: 5 }).id).toBeNull();
+ });
+
+ it("a hover open never unpins a pinned menu; a key re-open counts again (focus moves in)", () => {
+ const pinned = open(CLOSED_MENUS, "canvas", "pinned");
+ expect(open(pinned, "canvas", "hover")).toBe(pinned);
+ const key = barMenus(pinned, { type: "open", id: "canvas", mode: "pinned", via: "key", now: 0 });
+ expect(key.seq).toBe(pinned.seq + 1);
+ expect(key.mode).toBe("pinned");
+ });
+
+ it("switches at once while a menu is open and for a moment after the last one closed", () => {
+ const s = open(CLOSED_MENUS, "studios");
+ expect(switchesAtOnce(s, 5000)).toBe(true);
+ const closed = barMenus(s, { type: "close", now: 1000 });
+ expect(switchesAtOnce(closed, 1000 + NAV_INTENT.switchWindow - 1)).toBe(true);
+ expect(switchesAtOnce(closed, 1000 + NAV_INTENT.switchWindow + 1)).toBe(false);
+ expect(switchesAtOnce(CLOSED_MENUS, 0)).toBe(false);
+ });
+
+ it("slides the way the pointer went, in bar order", () => {
+ expect(switchDirection("studios", "apps")).toBe(1);
+ expect(switchDirection("canvas", "studios")).toBe(-1);
+ expect(switchDirection("more", "create")).toBe(-1);
+ expect(switchDirection(null, "apps")).toBe(0);
+ });
+});
+
+/** A glide straight across an item `width` px wide at `speed` px/s, one move per 16 ms: does its menu open? */
+function glideOpens(width: number, speed: number): boolean {
+ const step = (speed * 16) / 1000;
+ let r = restStart(0, 20, 0);
+ let t = 0;
+ for (let x = step; x <= width; x += step) {
+ t += 16;
+ if (restDue(r) <= t) return true;
+ r = restMove(r, x, 20, t);
+ }
+ // The pointer leaves at the far edge.
+ return restDue(r) <= t;
+}
+
+describe("resting on an item", () => {
+ it("opens 120 ms after the pointer stops", () => {
+ const r = restStart(10, 10, 1000);
+ expect(restDue(r)).toBe(1000 + NAV_INTENT.rest);
+ });
+
+ it("small moves (8 px) count as resting; a bigger one starts the rest again", () => {
+ let r = restStart(10, 10, 0);
+ r = restMove(r, 15, 14, 50);
+ expect(r.anchor).toEqual({ x: 10, y: 10, t: 0 });
+ r = restMove(r, 30, 10, 80);
+ expect(r.anchor).toEqual({ x: 30, y: 10, t: 80 });
+ expect(restDue(r)).toBe(80 + NAV_INTENT.rest);
+ });
+
+ it("opens anyway 600 ms after the pointer came, however it moves", () => {
+ let r = restStart(0, 0, 0);
+ for (let t = 16; t < 700; t += 16) r = restMove(r, t, 0, t);
+ expect(restDue(r)).toBe(NAV_INTENT.restCap);
+ });
+
+ it("a glide along the bar at 600 or 1500 px/s opens nothing; at 300 px/s at most the cap opens one", () => {
+ for (const w of [100, 130, 160]) {
+ expect(glideOpens(w, 600)).toBe(false);
+ expect(glideOpens(w, 1500)).toBe(false);
+ }
+ // At 300 px/s the anchor still moves on every other step: only the 600 ms cap could open a menu, on an item wider
+ // than any in the bar.
+ expect(glideOpens(160, 300)).toBe(false);
+ expect(glideOpens(200, 300)).toBe(true);
+ });
+});
+
+describe("the safe triangle", () => {
+ it("knows inside from outside", () => {
+ const a = { x: 0, y: 0 };
+ const b = { x: 10, y: 10 };
+ const c = { x: -10, y: 10 };
+ expect(inTriangle({ x: 0, y: 5 }, a, b, c)).toBe(true);
+ expect(inTriangle({ x: 8, y: 2 }, a, b, c)).toBe(false);
+ });
+
+ // Create's card: 520 px from the item's left edge, 8 px under the bar (top 64).
+ const card = { left: 20, top: 64, right: 540, bottom: 700 };
+ const exit = { x: 105, y: 34 };
+ const path = (pts: [number, number, number][]): Move[] => pts.map(([x, y, t]) => ({ x, y, t }));
+
+ it("holds while the pointer heads down into the open card across the next item", () => {
+ expect(aiming(exit, card, path([[110, 36, 0], [120, 38, 16], [130, 40, 32]]), 40)).toBe(true);
+ });
+
+ it("lets go when the pointer moves sideways along the bar, goes up, or stops", () => {
+ expect(aiming(exit, card, path([[110, 34, 0], [125, 34, 16], [140, 33, 32]]), 40)).toBe(false);
+ expect(aiming(exit, card, path([[110, 36, 0], [120, 34, 16], [130, 32, 32]]), 40)).toBe(false);
+ expect(aiming(exit, card, path([[110, 36, 0], [120, 38, 16], [130, 40, 32]]), 32 + NAV_INTENT.aimStop + 1)).toBe(false);
+ });
+
+ it("is off without an exit point or a menu", () => {
+ expect(aiming(null, card, path([[110, 36, 0], [130, 40, 32]]), 40)).toBe(false);
+ expect(aiming(exit, null, path([[110, 36, 0], [130, 40, 32]]), 40)).toBe(false);
+ });
+});
diff --git a/tests/e2e/bar-menus.mjs b/tests/e2e/bar-menus.mjs
new file mode 100644
index 00000000..2338b06b
--- /dev/null
+++ b/tests/e2e/bar-menus.mjs
@@ -0,0 +1,720 @@
+// The top bar's six menus (Create, Studios, Apps, Motions & effects, Canvas, More) as a person uses them, in a real
+// browser: resting on an item opens its menu, moving along the bar switches at once and the menu stays, a glide across
+// the bar opens nothing, a diagonal into an open menu keeps it, clicks and taps toggle, the keys work, nothing is cut
+// off at small windows, reduced motion lands at once, and a guest never sees owner-only rows. Each check names the
+// complaint it guards: A "sometimes it shows the full menu, sometimes I have to press", B "sometimes nothing happens
+// when I hover", C "the item with an arrow looks confusing".
+// Usage: node tests/e2e/bar-menus.mjs [appUrl]
+// Run it against a production build (next start). E2E_OWNER_PASSWORD: the studio's password, for the owner's checks.
+// Exits 1 if any check fails. Timings allow ±40 ms (headless Chromium's frames).
+import { launch, openRoute } from "./_browser.mjs";
+
+const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const failures = [];
+const check = (ok, what, detail = "") => {
+ console.log(`${ok ? "✓" : "✗"} ${what}${!ok && detail ? ` (${detail})` : ""}`);
+ if (!ok) failures.push(what);
+};
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const SLACK = 40;
+const OWNER_WORDS = ["No cover yet", "Fuobe DoP", "free on your GPU", "Qwen", "Wan 2", "LTX", "Kling", "ComfyUI", "New board"];
+const HUBS = { create: "/create", studios: "/studios", apps: "/apps", motions: "/motions-and-effects", canvas: "/canvas" };
+
+/** In the page: every frame, which menus are open (interactive) and painted, and the dimmed page's opacity. */
+const SAMPLER = () => {
+ const rec = { frames: [], arrive: {}, lastMove: 0 };
+ window.__bm = rec;
+ const state = () => {
+ const open = [];
+ const painted = [];
+ for (const s of document.querySelectorAll("[data-mega-panel], [data-bar-card]")) {
+ const id = s.dataset.megaPanel || s.dataset.barCard;
+ if (s.dataset.phase === "open") open.push(id);
+ if (s.dataset.phase && s.dataset.phase !== "gone") painted.push(id);
+ }
+ const sc = document.querySelector("[data-bar-scrim]");
+ const skel = [...document.querySelectorAll("[data-mega-panel][data-phase=open] [data-mega-skeleton]")].some((e) => e.checkVisibility() && Number(getComputedStyle(e).opacity) > 0.05);
+ return { open, painted, scrim: sc ? Number(getComputedStyle(sc).opacity) : 0, skel };
+ };
+ window.__bmState = state;
+ const tick = () => {
+ rec.frames.push({ t: performance.now(), ...state() });
+ if (rec.frames.length > 6000) rec.frames.splice(0, 2000);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ document.addEventListener(
+ "pointerover",
+ (e) => {
+ const b = e.target.closest?.("[data-bar-menu]");
+ if (b) rec.arrive[b.dataset.barMenu] ??= performance.now();
+ },
+ true,
+ );
+ document.addEventListener("pointermove", () => (rec.lastMove = performance.now()), true);
+ window.__bmMark = () => {
+ rec.frames = [];
+ rec.arrive = {};
+ return performance.now();
+ };
+};
+
+const browser = await launch();
+
+async function context(opts = {}, who = "guest") {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, ...opts });
+ if (who === "owner") await ctx.request.post(`${app}/api/auth/login`, { data: { password: process.env.E2E_OWNER_PASSWORD } });
+ return ctx;
+}
+async function open(ctx, path = "/library", settle = 1600) {
+ const p = await ctx.newPage();
+ await p.addInitScript(SAMPLER);
+ await openRoute(p, app + path, { settleMs: settle });
+ return p;
+}
+const mark = (p) => p.evaluate(() => window.__bmMark());
+const frames = (p) => p.evaluate(() => window.__bm.frames);
+const arrive = (p) => p.evaluate(() => window.__bm.arrive);
+const now = (p) => p.evaluate(() => window.__bmState());
+const pageNow = (p) => p.evaluate(() => performance.now());
+async function rect(p, sel) {
+ return p.evaluate((sel) => {
+ const el = [...document.querySelectorAll(sel)].find((e) => e.checkVisibility());
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, left: r.left, right: r.right, top: r.top, bottom: r.bottom, w: r.width, h: r.height };
+ }, sel);
+}
+const item = (p, id) => rect(p, `[data-bar-menu="${id}"]`);
+const visibleItems = (p) => p.evaluate(() => [...document.querySelectorAll("[data-top-bar] [data-bar-menu]")].filter((e) => e.checkVisibility()).map((e) => e.dataset.barMenu));
+
+let cursor = { x: 700, y: 600 };
+/**
+ * Moves the mouse in a straight line at `speed` px/s (Infinity: one jump), about one move per frame. Where the pointer
+ * is follows the clock, so the speed holds even when a move takes the browser a while to deliver.
+ */
+async function glide(p, to, speed = 800) {
+ const from = { ...cursor };
+ const d = Math.hypot(to.x - from.x, to.y - from.y);
+ if (speed === Infinity || d < 1) {
+ await p.mouse.move(to.x, to.y);
+ } else {
+ const start = performance.now();
+ for (;;) {
+ const k = Math.min(1, ((performance.now() - start) / 1000) * (speed / d));
+ await p.mouse.move(from.x + (to.x - from.x) * k, from.y + (to.y - from.y) * k);
+ if (k >= 1) break;
+ await sleep(14);
+ }
+ }
+ cursor = { ...to };
+}
+/** The pointer off to the page's bottom corner, and nothing open (Esc for a pinned menu), past the switch window. */
+async function away(p) {
+ const vp = p.viewportSize();
+ await glide(p, { x: vp.width - 40, y: vp.height - 1 }, Infinity);
+ await sleep(450);
+ if ((await now(p)).open.length) await p.keyboard.press("Escape");
+ await sleep(450);
+}
+/** The first frame at or after `t0` where `pred` holds (ms after t0), or null. */
+const firstAt = (fs, t0, pred) => {
+ const f = fs.find((x) => x.t >= t0 && pred(x));
+ return f ? f.t - t0 : null;
+};
+
+try {
+ // ---------- 1. Semantics (C) ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ const r = await p.evaluate(() => {
+ const nav = document.querySelector('[data-top-bar] nav[aria-label="Main"]');
+ const out = [];
+ for (const b of nav.querySelectorAll("[data-bar-menu]")) {
+ if (!b.checkVisibility()) continue;
+ const text = b.innerText.trim().split(/\s+/)[0];
+ const name = b.getAttribute("aria-label") ?? b.innerText.trim();
+ const chev = b.querySelector("[data-bar-chevron]");
+ const cr = chev.getBoundingClientRect();
+ const hit = document.elementFromPoint(cr.x + cr.width / 2, cr.y + cr.height / 2);
+ out.push({
+ id: b.dataset.barMenu,
+ tag: b.tagName,
+ expanded: b.getAttribute("aria-expanded"),
+ controls: !!document.getElementById(b.getAttribute("aria-controls") ?? "-"),
+ named: name.includes(text),
+ inner: b.querySelectorAll("a, button, input, [tabindex]").length,
+ // Anything else to press that overlaps the item (the old split pill had a link and a chevron button).
+ siblingsFocusable: [...nav.querySelectorAll("a[href], button")].filter((s) => {
+ if (s === b || b.contains(s) || !s.checkVisibility()) return false;
+ const o = s.getBoundingClientRect();
+ const r = b.getBoundingClientRect();
+ return o.left < r.right - 1 && o.right > r.left + 1 && o.top < r.bottom - 1 && o.bottom > r.top + 1;
+ }).length,
+ chevHidden: chev.getAttribute("aria-hidden") === "true",
+ chevHit: b.contains(hit),
+ });
+ }
+ return { items: out, roles: nav.querySelectorAll('[role="menu"], [role="menuitem"], [aria-haspopup="menu"]').length };
+ });
+ check(r.items.length === 5, "1 (C): 1440 shows five menu items (Create, Studios, Apps, Motions & effects, Canvas)", r.items.map((i) => i.id).join());
+ for (const i of r.items) {
+ check(i.tag === "BUTTON" && i.expanded === "false" && i.controls, `1 (C): ${i.id} is one button with aria-expanded and aria-controls`, JSON.stringify(i));
+ check(i.named && i.inner === 0 && i.siblingsFocusable === 0, `1 (C): ${i.id} is named by its words, with nothing else to press inside or beside it`, JSON.stringify(i));
+ check(i.chevHidden && i.chevHit, `1 (C): ${i.id}'s chevron is decoration (aria-hidden, the button takes a press on it)`);
+ }
+ check(r.roles === 0, "1 (C): no menu roles in the bar (a disclosure of links)");
+ // The open highlight: one filled box, the size of the open item.
+ await p.locator('[data-bar-menu="apps"]').click();
+ await sleep(400);
+ const ind = await p.evaluate(() => {
+ const i = document.querySelector("[data-bar-indicator]").getBoundingClientRect();
+ const b = document.querySelector('[data-bar-menu="apps"]').getBoundingClientRect();
+ return { d: Math.max(Math.abs(i.left - b.left), Math.abs(i.top - b.top), Math.abs(i.width - b.width), Math.abs(i.height - b.height)), on: document.querySelector("[data-bar-indicator]").hasAttribute("data-on") };
+ });
+ check(ind.on && ind.d <= 1, "1 (C): an open item has the one highlight behind it, the item's own size", JSON.stringify(ind));
+ await ctx.close();
+ }
+
+ // ---------- 2. Rest opens, every item, on its own page too (A, B) ----------
+ for (const size of [
+ { width: 1440, height: 900 },
+ { width: 1280, height: 720 },
+ ]) {
+ const ctx = await context({ viewport: size });
+ for (const path of ["/library", ...Object.values(HUBS)]) {
+ if (size.width < 1440 && path !== "/library") continue;
+ const p = await open(ctx, path);
+ cursor = { x: size.width / 2, y: size.height - 10 };
+ const ids = await visibleItems(p);
+ const only = path === "/library" ? ids : ids.filter((id) => HUBS[id] === path);
+ for (const id of only) {
+ await away(p);
+ const at = await item(p, id);
+ await mark(p);
+ await glide(p, { x: at.x, y: at.y }, Infinity);
+ await sleep(450);
+ const fs = await frames(p);
+ const a = (await arrive(p))[id];
+ const t = a == null ? null : firstAt(fs, a, (f) => f.open.includes(id));
+ check(t !== null && t >= 100 - SLACK && t <= 180 + SLACK, `2 (A,B): ${size.width} ${path}: resting on ${id} opens it at ~120 ms`, `${t?.toFixed(0)} ms`);
+ }
+ await p.close();
+ }
+ await ctx.close();
+ }
+
+ // ---------- 3. Switch and stay; 17. the scrim never drops during a switch (A) ----------
+ for (const [size, pairsOf] of [
+ [{ width: 1440, height: 900 }, ["create", "studios", "apps", "motions", "canvas"]],
+ [{ width: 1280, height: 720 }, ["create", "studios", "motions", "more"]],
+ ]) {
+ const ctx = await context({ viewport: size });
+ const p = await open(ctx);
+ for (const how of ["hover", "click"]) {
+ for (const a of pairsOf) {
+ for (const b of pairsOf) {
+ if (a === b) continue;
+ if (size.width === 1280 && how === "click" && !["motions", "more"].includes(a)) continue;
+ await away(p);
+ const ra = await item(p, a);
+ const rb = await item(p, b);
+ await glide(p, { x: ra.x, y: ra.y }, Infinity);
+ if (how === "click") await p.mouse.click(ra.x, ra.y);
+ await p.waitForFunction((id) => window.__bmState().open.includes(id), a, { timeout: 2000 }).catch(() => {});
+ await sleep(250);
+ const t0 = await mark(p);
+ await glide(p, { x: rb.x, y: rb.y }, 900);
+ await sleep(2000);
+ const fs = await frames(p);
+ const arr = (await arrive(p))[b];
+ const t = arr == null ? null : firstAt(fs, arr, (f) => f.open.includes(b));
+ const tail = fs.at(-1);
+ const none = fs.filter((f) => f.t >= t0 && f.open.length === 0).length;
+ const two = fs.filter((f) => f.open.length > 1).length;
+ const scrimDrop = Math.max(0, ...fs.map((f, i) => (i ? fs[i - 1].scrim - f.scrim : 0)));
+ const label = `3 (A): ${size.width} ${how}-opened ${a} → ${b}`;
+ check(t !== null && t <= 50 + SLACK, `${label}: switches at once`, `${t?.toFixed(0)} ms`);
+ check(tail.open.length === 1 && tail.open[0] === b, `${label}: still open 2 s later`, tail.open.join());
+ check(none === 0 && two === 0, `${label}: never a frame with none or two open`, `none ${none}, two ${two}`);
+ check(scrimDrop < 0.02, `17: ${size.width} ${a} → ${b}: the dimmed page never fades during the switch`, scrimDrop.toFixed(3));
+ }
+ }
+ }
+ await ctx.close();
+ }
+
+ // ---------- 4. Run along the bar (A) ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ await away(p);
+ const seq = ["studios", "apps", "motions", "canvas"];
+ const st = await item(p, "studios");
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("studios"), null, { timeout: 2000 });
+ const t0 = await mark(p);
+ for (const id of seq.slice(1)) {
+ await sleep(150);
+ const r = await item(p, id);
+ await glide(p, { x: r.x, y: r.y }, 1500);
+ }
+ await sleep(2000);
+ const fs = await frames(p);
+ const a = await arrive(p);
+ const late = seq.slice(1).map((id) => (a[id] == null ? 999 : firstAt(fs, a[id], (f) => f.open.includes(id)) ?? 999));
+ check(late.every((t) => t <= 50 + SLACK), "4 (A): 150 ms on each of Studios, Apps, Motions & effects, Canvas: each opens on arrival", late.map((t) => t.toFixed(0)).join());
+ check(fs.at(-1).open.join() === "canvas" && !fs.some((f) => f.t >= t0 && !f.open.length), "4 (A): the last stays open, never a frame with none");
+ await ctx.close();
+ }
+
+ // ---------- 5. Glide with nothing open; 6. glide away with a menu open ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ const wm = await rect(p, '[data-top-bar] a[aria-label="Fuobe home"]');
+ const search = await rect(p, "[data-top-bar] button[aria-keyshortcuts]");
+ for (const [speed, most] of [
+ [1500, 0],
+ [600, 0],
+ [300, 1],
+ ]) {
+ await away(p);
+ await glide(p, { x: wm.x, y: wm.y }, Infinity);
+ await sleep(300);
+ await mark(p);
+ await glide(p, { x: search.x, y: search.y }, speed);
+ await sleep(250);
+ const fs = await frames(p);
+ // Menus opened from nothing (once one is open, the next items switch to theirs: that is a menubar).
+ const opens = fs.filter((f, i) => i && f.open.length && !fs[i - 1].open.length).length;
+ check(opens <= most, `5: a glide from the wordmark to search at ${speed} px/s opens ${most ? "at most one menu" : "nothing"}`, `${opens}: ${[...new Set(fs.flatMap((f) => f.open))].join()}`);
+ }
+ // 6. With Studios open, away along the bar to search: one close, the dimmed page fades once.
+ await away(p);
+ const st = await item(p, "studios");
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("studios"), null, { timeout: 2000 });
+ await mark(p);
+ await glide(p, { x: search.x, y: search.y }, 900);
+ await sleep(900);
+ const fs = await frames(p);
+ let closes = 0;
+ let fades = 0;
+ for (let i = 1; i < fs.length; i++) {
+ if (fs[i - 1].open.length && !fs[i].open.length) closes++;
+ if (fs[i].scrim < fs[i - 1].scrim - 0.001 && !(fs[i - 1].scrim < fs[i - 2]?.scrim - 0.001)) fades++;
+ }
+ check(closes === 1 && !fs.at(-1).open.length, "6: gliding away from an open menu closes it exactly once", `closes ${closes}`);
+ check(fades <= 1, "6: the dimmed page fades out at most once", `fades ${fades}`);
+ await ctx.close();
+ }
+
+ // ---------- 7. Leave into the page; re-entering in time keeps it ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ for (const back of [false, true]) {
+ await away(p);
+ const cr = await item(p, "create");
+ await glide(p, { x: cr.x, y: cr.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("create"), null, { timeout: 2000 });
+ await sleep(200);
+ await mark(p);
+ await glide(p, { x: 1200, y: 700 }, Infinity);
+ const left = await p.evaluate(() => window.__bm.lastMove);
+ if (back) {
+ await sleep(200);
+ await glide(p, { x: cr.x, y: cr.y }, Infinity);
+ }
+ await sleep(700);
+ const fs = await frames(p);
+ if (!back) {
+ const startClose = firstAt(fs, left, (f) => !f.open.includes("create"));
+ const gone = firstAt(fs, left, (f) => !f.painted.includes("create"));
+ check(startClose !== null && Math.abs(startClose - 300) <= SLACK && gone !== null && gone <= 460 + SLACK, "7: a menu the pointer opened starts to close 300 ms after the pointer left, gone by 460", `${startClose?.toFixed(0)} / ${gone?.toFixed(0)}`);
+ } else check(fs.every((f) => f.open.includes("create")), "7: coming back within 250 ms keeps it open");
+ }
+ await ctx.close();
+ }
+
+ // ---------- 8. Diagonals ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ await away(p);
+ const st = await item(p, "studios");
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("studios"), null, { timeout: 2000 });
+ await mark(p);
+ await glide(p, { x: 1330, y: 420 }, 700);
+ await sleep(600);
+ let fs = await frames(p);
+ check(fs.every((f) => f.open.join() === "studios"), "8: Studios → its far-right column: no switch, no close");
+ await away(p);
+ const cr = await item(p, "create");
+ await glide(p, { x: cr.x, y: cr.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("create"), null, { timeout: 2000 });
+ await sleep(150);
+ await mark(p);
+ // A shallow line from Create into its right column, across the bottom of the Studios item.
+ const right = await rect(p, '[data-bar-card="create"] [data-col="1"][data-row="1"]');
+ await glide(p, { x: right.x, y: right.y }, 600);
+ await sleep(600);
+ fs = await frames(p);
+ const crossed = await arrive(p);
+ check(fs.every((f) => f.open.join() === "create"), "8: Create → its right column across the Studios item: no switch, no close", `crossed Studios: ${crossed.studios != null}; ${[...new Set(fs.map((f) => f.open.join()))].join(" / ")}`);
+ await ctx.close();
+ }
+
+ // ---------- 9. Clicks (A) ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ for (const id of ["create", "studios", "apps"]) {
+ await away(p);
+ const r = await item(p, id);
+ await glide(p, { x: r.x, y: r.y }, Infinity);
+ await mark(p);
+ const t0 = await pageNow(p);
+ await p.mouse.click(r.x, r.y);
+ await sleep(300);
+ let fs = await frames(p);
+ const t = firstAt(fs, t0, (f) => f.open.includes(id));
+ check(t !== null && t <= 50 + SLACK, `9 (A): a click on ${id} opens it at once`, `${t?.toFixed(0)} ms`);
+ check(new URL(p.url()).pathname === "/library", `9 (A): a click on ${id} never leaves the page`);
+ await p.mouse.click(r.x, r.y);
+ await sleep(250);
+ check(!(await now(p)).open.length, `9 (A): a second click on ${id} closes it`);
+ }
+ for (const delay of [30, 500, 2000]) {
+ await away(p);
+ const r = await item(p, "studios");
+ await glide(p, { x: r.x, y: r.y }, Infinity);
+ await p.waitForFunction(() => window.__bmState().open.includes("studios"), null, { timeout: 2000 });
+ await sleep(delay);
+ await mark(p);
+ await p.mouse.click(r.x, r.y);
+ await glide(p, { x: 700, y: 895 }, Infinity);
+ await sleep(800);
+ const fs = await frames(p);
+ check(fs.every((f) => f.open.includes("studios")), `9 (A): a click ${delay} ms after a hover open pins it (never closes); leaving keeps it`);
+ await p.mouse.click(r.x, r.y);
+ await sleep(200);
+ }
+ // A click during the rest wait opens it, pinned.
+ await away(p);
+ const ap = await item(p, "apps");
+ await glide(p, { x: ap.x, y: ap.y }, Infinity);
+ await p.mouse.click(ap.x, ap.y);
+ await glide(p, { x: 700, y: 895 }, Infinity);
+ await sleep(800);
+ check((await now(p)).open.join() === "apps", "9 (A): a click during the rest wait opens it pinned");
+ await p.keyboard.press("Escape");
+ await sleep(200);
+ // Ctrl-click: the area's page in a new tab; the menu state does not change (here: Studios, opened by resting on it).
+ await away(p);
+ const sr = await item(p, "studios");
+ await glide(p, { x: sr.x, y: sr.y }, Infinity);
+ await sleep(400);
+ const before = (await now(p)).open.join();
+ const tab = ctx.waitForEvent("page", { timeout: 5000 }).catch(() => null);
+ await p.keyboard.down("Control");
+ await p.mouse.click(sr.x, sr.y);
+ await p.keyboard.up("Control");
+ const np = await tab;
+ if (np) await np.waitForLoadState("domcontentloaded").catch(() => {});
+ check(!!np && new URL(np.url()).pathname === "/studios", "9: Ctrl-click on an item opens its page in a new tab", np?.url());
+ await sleep(300);
+ check(before === "studios" && (await now(p)).open.join() === before, "9: Ctrl-click leaves the menus as they were", before);
+ await ctx.close();
+ }
+
+ // ---------- 10. Touch laptop with a mouse (B) ----------
+ {
+ const ctx = await context({ hasTouch: true });
+ const p = await open(ctx);
+ for (const id of await visibleItems(p)) {
+ await away(p);
+ const r = await item(p, id);
+ await glide(p, { x: r.x, y: r.y }, Infinity);
+ await sleep(400);
+ check((await now(p)).open.includes(id), `10 (B): on a touch laptop, resting the mouse on ${id} opens it`);
+ }
+ await ctx.close();
+ }
+
+ // ---------- 11. Cold load (A) ----------
+ for (const id of ["apps", "motions", "canvas"]) {
+ const ctx = await context();
+ const p = await ctx.newPage();
+ await p.addInitScript(SAMPLER);
+ await p.goto(`${app}/library`, { waitUntil: "load" });
+ await sleep(1500);
+ const r = await item(p, id);
+ cursor = { x: 700, y: 880 };
+ await mark(p);
+ await glide(p, { x: r.x, y: r.y }, Infinity);
+ await sleep(900);
+ const fs = await frames(p);
+ const opened = fs.some((f) => f.open.includes(id));
+ check(opened && !fs.some((f) => f.skel), `11 (A): cold load, the first hover on ${id} 1.5 s after load shows its links, never a skeleton`);
+ await ctx.close();
+ }
+ {
+ const ctx = await context();
+ const p = await ctx.newPage();
+ await p.addInitScript(SAMPLER);
+ await p.goto(`${app}/library`, { waitUntil: "commit" });
+ // The first Studios item that shows (while the page streams in, its first paint's copy).
+ const btn = p.locator('[data-bar-menu="studios"]:visible').first();
+ await btn.waitFor({ state: "visible", timeout: 30_000 });
+ const r = await btn.boundingBox();
+ await p.mouse.move(r.x + r.width / 2, r.y + r.height / 2);
+ await p.mouse.down();
+ await p.mouse.up();
+ const ok = await p.waitForFunction(() => window.__bmState?.().open.includes("studios"), null, { timeout: 6000 }).then(
+ () => true,
+ () => false,
+ );
+ check(ok, "11 (A): a press on an item right after the first paint opens its menu once the page is ready");
+ await ctx.close();
+ }
+
+ // ---------- 12. Keyboard; 13. hub pages ----------
+ for (const who of ["guest", ...(process.env.E2E_OWNER_PASSWORD ? ["owner"] : [])]) {
+ const ctx = await context({}, who);
+ const p = await open(ctx, "/library");
+ const focused = () => p.evaluate(() => ({ menu: document.activeElement?.dataset?.barMenu, col: document.activeElement?.dataset?.col, row: document.activeElement?.dataset?.row, label: document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.textContent?.trim(), seeAll: document.activeElement?.hasAttribute("data-see-all") }));
+ if (who === "guest") {
+ await p.locator('[data-bar-menu="studios"]').focus();
+ await p.keyboard.press("Enter");
+ await sleep(250);
+ check((await now(p)).open.join() === "studios" && (await focused()).menu === "studios", "12: Enter opens the panel and focus stays on the item");
+ await p.keyboard.press("Tab");
+ const f = await focused();
+ check(/^See all/.test(f.label ?? ""), "12, 13: the next Tab lands on See all", f.label);
+ await p.keyboard.press("Shift+Tab");
+ check((await focused()).menu === "studios" && (await now(p)).open.join() === "studios", "12: Shift+Tab from See all goes back to the item, the panel stays open");
+ await p.keyboard.press(" ");
+ await sleep(250);
+ check(!(await now(p)).open.length, "12: Space closes it");
+ await p.keyboard.press("ArrowDown");
+ await sleep(400);
+ const d = await focused();
+ check((await now(p)).open.join() === "studios" && d.col === "0" && d.row === "0", "12: ArrowDown opens it and focuses the first lead row", JSON.stringify(d));
+ await p.locator('[data-bar-menu="studios"]').focus();
+ await p.keyboard.press("ArrowRight");
+ await sleep(250);
+ check((await focused()).menu === "apps" && (await now(p)).open.join() === "apps", "12: ArrowRight moves to the next item and the open panel follows");
+ await p.keyboard.press("ArrowLeft");
+ await sleep(250);
+ check((await focused()).menu === "studios" && (await now(p)).open.join() === "studios", "12: ArrowLeft moves back");
+ await p.keyboard.press("Escape");
+ await sleep(250);
+ check(!(await now(p)).open.length && (await focused()).menu === "studios", "12: Esc closes and gives focus back to the item");
+ // Tab past the last link of Create's card: it closes and focus goes on to the next item.
+ await p.locator('[data-bar-menu="create"]').focus();
+ await p.keyboard.press("Enter");
+ await sleep(250);
+ for (let i = 0; i < 20; i++) {
+ await p.keyboard.press("Tab");
+ if ((await focused()).menu) break;
+ }
+ await sleep(250);
+ check((await focused()).menu === "studios" && !(await now(p)).open.length, "12: Tab past the last link closes the menu and focuses the next item");
+ // Esc after a hover open while typing elsewhere leaves focus there.
+ await p.evaluate(() => {
+ const i = document.createElement("input");
+ i.id = "bm-field";
+ i.style.cssText = "position:fixed;left:20px;bottom:20px;z-index:100";
+ document.body.append(i);
+ i.focus();
+ });
+ cursor = { x: 700, y: 600 };
+ const st = await item(p, "studios");
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await sleep(400);
+ await p.keyboard.press("Escape");
+ await sleep(200);
+ check(!(await now(p)).open.length && (await p.evaluate(() => document.activeElement?.id)) === "bm-field", "12: Esc after a hover open while typing closes it and leaves focus in the field");
+ await away(p);
+ // 13. See all is the first Tab stop in every panel, and marks its own page.
+ for (const [id, href] of Object.entries(HUBS)) {
+ const q = await open(ctx, href);
+ await q.locator(`[data-bar-menu="${id}"]`).focus();
+ await q.keyboard.press("Enter");
+ await sleep(400);
+ await q.keyboard.press("Tab");
+ const f = await q.evaluate(() => ({ href: document.activeElement?.getAttribute("href"), cur: document.activeElement?.getAttribute("aria-current"), see: document.activeElement?.hasAttribute("data-see-all") }));
+ check(f.href === href && f.see && f.cur === "page", `13: ${id}: See all is the first Tab stop and is marked on ${href}`, JSON.stringify(f));
+ await q.close();
+ }
+ } else {
+ await p.locator('[data-bar-menu="canvas"]').focus();
+ await p.keyboard.press("ArrowDown");
+ await sleep(1500);
+ const t = await p.evaluate(() => document.activeElement?.textContent?.trim() ?? "");
+ check(/New board/.test(t), "12: owner: ArrowDown on Canvas focuses New board", t.slice(0, 40));
+ }
+ await ctx.close();
+ }
+
+ // ---------- 14. Touch tablet ----------
+ {
+ const ctx = await context({ viewport: { width: 1180, height: 820 }, hasTouch: true, isMobile: false });
+ const p = await open(ctx);
+ const coarse = await p.evaluate(() => matchMedia("(pointer: coarse)").matches);
+ const ids = await visibleItems(p);
+ for (const id of ids) {
+ const r = await item(p, id);
+ check(!coarse || (r.w >= 44 && r.h >= 44), `14: ${id} is at least 44x44 on a touch screen`, `${r.w}x${r.h}`);
+ }
+ const a = await item(p, ids[0]);
+ const b = await item(p, ids[1]);
+ await p.touchscreen.tap(a.x, a.y);
+ await sleep(300);
+ check((await now(p)).open.join() === ids[0], `14: a tap opens ${ids[0]}`);
+ await p.touchscreen.tap(b.x, b.y);
+ await sleep(300);
+ check((await now(p)).open.join() === ids[1], `14: a tap on ${ids[1]} switches at once`);
+ await p.touchscreen.tap(b.x, b.y);
+ await sleep(300);
+ check(!(await now(p)).open.length, "14: tapping it again closes it");
+ await p.touchscreen.tap(a.x, a.y);
+ await sleep(300);
+ // A tap outside on a link of the page: it only closes the menu.
+ const link = await p.evaluate(() => {
+ const l = [...document.querySelectorAll("main a[href]")].find((x) => {
+ const r = x.getBoundingClientRect();
+ return x.checkVisibility() && r.top > 450 && r.bottom < innerHeight - 10 && r.width > 20;
+ });
+ if (!l) return null;
+ const r = l.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, href: l.getAttribute("href") };
+ });
+ const at = p.url();
+ if (link) {
+ await p.touchscreen.tap(link.x, link.y);
+ await sleep(900);
+ check(!(await now(p)).open.length && p.url() === at, "14: a tap outside closes the menu and does not follow the link under it", `${link.href} → ${p.url()}`);
+ } else check(false, "14: a link to tap under the menu", "none found");
+ // A tap's own pointer moves never count as hovering: after the tap that closes it, nothing opens again.
+ await p.touchscreen.tap(b.x, b.y);
+ await sleep(300);
+ await p.touchscreen.tap(b.x, b.y);
+ await mark(p);
+ await sleep(600);
+ check(!(await now(p)).open.length && !(await frames(p)).some((f) => f.open.length), "14: no hover opens on a touch tablet (a tap that closes stays closed)");
+ await ctx.close();
+ }
+
+ // ---------- 15. Fit ----------
+ for (const size of [
+ { width: 1280, height: 720 },
+ { width: 1366, height: 768 },
+ { width: 1440, height: 900 },
+ { width: 1920, height: 1080 },
+ ]) {
+ const ctx = await context({ viewport: size });
+ const p = await open(ctx);
+ const ids = await visibleItems(p);
+ for (const id of ids) {
+ await p.locator(`[data-bar-menu="${id}"]`).click();
+ await sleep(500);
+ const m = await p.evaluate((id) => {
+ const s = document.querySelector(`[data-mega-panel="${id}"], [data-bar-card="${id}"]`);
+ const box = s.matches("[data-bar-card]") ? s.firstElementChild : s;
+ const r = box.getBoundingClientRect();
+ const see = s.querySelector("[data-see-all]");
+ return { bottom: r.bottom, scroll: box.scrollHeight - box.clientHeight, see: id === "more" || (!!see && see.checkVisibility() && see.getBoundingClientRect().bottom <= innerHeight) };
+ }, id);
+ check(m.bottom <= size.height + 0.5 && m.scroll <= 1 && m.see, `15: ${size.width}x${size.height} ${id}: fits the window, no scrolling inside, See all shows`, JSON.stringify(m));
+ await p.keyboard.press("Escape");
+ await sleep(200);
+ }
+ // During a switch too (every frame).
+ if (ids.includes("apps")) {
+ await away(p);
+ const st = await item(p, "studios");
+ const ap = await item(p, "apps");
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await sleep(500);
+ const over = await p.evaluate(async () => {
+ let worst = 0;
+ const end = performance.now() + 600;
+ while (performance.now() < end) {
+ for (const s of document.querySelectorAll("[data-mega-panel]:not([hidden])")) worst = Math.max(worst, s.getBoundingClientRect().bottom - innerHeight);
+ await new Promise(requestAnimationFrame);
+ }
+ return worst;
+ }).then(async (v) => v);
+ await glide(p, { x: ap.x, y: ap.y }, 900);
+ check(over <= 0.5, `15: ${size.width}x${size.height}: nothing passes the window bottom during a switch`, over.toFixed(1));
+ }
+ await ctx.close();
+ }
+
+ // ---------- 16. Reduced motion ----------
+ {
+ const ctx = await context({ reducedMotion: "reduce" });
+ const p = await open(ctx);
+ await away(p);
+ const st = await item(p, "studios");
+ const ap = await item(p, "apps");
+ await mark(p);
+ await glide(p, { x: st.x, y: st.y }, Infinity);
+ await sleep(400);
+ await glide(p, { x: ap.x, y: ap.y }, 900);
+ await sleep(400);
+ await away(p);
+ const fs = await frames(p);
+ const a = await arrive(p);
+ const t = a.studios == null ? null : firstAt(fs, a.studios, (f) => f.open.includes("studios"));
+ check(t !== null && t >= 100 - SLACK && t <= 180 + SLACK, "16: reduced motion keeps the rest timing", `${t?.toFixed(0)} ms`);
+ const op = await p.evaluate(async () => {
+ const out = [];
+ document.querySelector('[data-bar-menu="canvas"]').click();
+ for (let i = 0; i < 4; i++) {
+ await new Promise(requestAnimationFrame);
+ const s = document.querySelector('[data-mega-panel="canvas"]');
+ out.push([s.dataset.phase, Number(getComputedStyle(s).opacity), Number(getComputedStyle(document.querySelector("[data-mega-sheet]")).opacity)]);
+ }
+ return out;
+ });
+ check(op.every(([ph, o, sh]) => ph !== "open" || (o === 1 && sh === 1)), "16: reduced motion: an opening panel is whole in its first frame", JSON.stringify(op));
+ await ctx.close();
+ }
+
+ // ---------- 18. Public sign-up: a guest never sees owner-only rows ----------
+ {
+ const ctx = await context();
+ const p = await open(ctx);
+ for (const id of await visibleItems(p)) {
+ await p.locator(`[data-bar-menu="${id}"]`).click();
+ await sleep(600);
+ const text = await p.evaluate((id) => document.querySelector(`[data-mega-panel="${id}"], [data-bar-card="${id}"]`).innerText, id);
+ const bad = OWNER_WORDS.filter((w) => text.includes(w));
+ check(!bad.length, `18: a guest's ${id} menu has no owner-only rows or words`, bad.join());
+ await p.keyboard.press("Escape");
+ await sleep(150);
+ }
+ await ctx.close();
+ }
+
+ // ---------- 19. Phone ----------
+ {
+ const ctx = await context({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
+ const p = await open(ctx);
+ const shown = await p.evaluate(() => [...document.querySelectorAll("[data-bar-menu]")].filter((e) => e.checkVisibility()).length);
+ check(shown === 0, "19: a phone shows no top-bar menu item (its tabs and sheets stay as they were)");
+ await ctx.close();
+ }
+} catch (e) {
+ check(false, "the run finished", e.stack?.split("\n").slice(0, 3).join(" | "));
+} finally {
+ await browser.close();
+}
+console.log(failures.length ? `\n${failures.length} check(s) failed` : "\nAll bar menu checks passed");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/e2e/mega-menus.mjs b/tests/e2e/mega-menus.mjs
index 4efe6104..babf1873 100644
--- a/tests/e2e/mega-menus.mjs
+++ b/tests/e2e/mega-menus.mjs
@@ -29,10 +29,10 @@ const publicSignup = !!(await fetch(`${app}/api/auth/me`).then((r) => r.json()).
const OWNER_WORDS = ["No cover yet", "Fuobe DoP", "free on your GPU", "Qwen", "Wan 2", "LTX", "Kling", "ComfyUI"];
const MENUS = {
- studios: { chevron: "Studios menu", line: /^\d+ studios, grouped by what you want to make$/, groups: 6, seeAll: "/studios", from: 0 },
- apps: { chevron: "Apps menu", line: /^\d+ apps, grouped by what they change$/, groups: 6, seeAll: "/apps", from: 1280 },
- motions: { chevron: "Motions & effects menu", line: /^\d+ camera motions and \d+ effects, for any photo$/, groups: 6, seeAll: "/motions-and-effects", from: 1280 },
- canvas: { chevron: "Canvas menu", line: /^\d+ ready boards that run as they are$/, groups: 2, seeAll: "/canvas", from: 1440 },
+ studios: { line: /^\d+ studios, grouped by what you want to make$/, groups: 6, seeAll: "/studios", from: 0 },
+ apps: { line: /^\d+ apps, grouped by what they change$/, groups: 6, seeAll: "/apps", from: 1280 },
+ motions: { line: /^\d+ camera motions and \d+ effects, for any photo$/, groups: 6, seeAll: "/motions-and-effects", from: 1280 },
+ canvas: { line: /^\d+ ready boards that run as they are$/, groups: 2, seeAll: "/canvas", from: 1440 },
};
const SIZES = [
{ width: 1280, height: 720 },
@@ -78,14 +78,16 @@ async function page(ctx) {
return p;
}
const bar = (p) => p.locator("[data-top-bar]");
+/** A menu's item in the bar: one button (bar-menus.tsx). */
+const trig = (p, id) => bar(p).locator(`[data-bar-menu="${id}"]`);
const panelOf = (p, id) => p.locator(`#${id}-launcher`);
const pathOf = (p) => new URL(p.url()).pathname;
const at = (p) => p.evaluate(() => [document.activeElement?.getAttribute("data-col"), document.activeElement?.getAttribute("data-row")].join(","));
const waitPath = (p, want) => p.waitForURL((u) => new URL(u).pathname === want, { timeout: 20_000 }).then(() => true, () => false);
-/** Opens a menu with its chevron and waits for its links and pictures. */
+/** Opens a menu with its item and waits for its links and pictures. */
async function openMenu(p, id) {
- await bar(p).getByRole("button", { name: MENUS[id].chevron, exact: true }).click();
+ await trig(p, id).click();
const panel = panelOf(p, id);
await panel.waitFor({ state: "visible" });
// Its first column's first item (the owner's Canvas column comes a moment after the rest).
@@ -123,7 +125,7 @@ const measure = (panel) =>
// Lines cut with "…" (a row's or a lead's line wider than its box).
cut: [...el.querySelectorAll("[data-col] span.truncate.text-muted-foreground")].filter((s) => s.checkVisibility() && s.scrollWidth > s.clientWidth + 1).map((s) => s.textContent),
rowsMax: Math.max(0, ...[...el.querySelectorAll("[data-group] > ul")].map((u) => [...u.querySelectorAll(':scope > li > a[data-row]:not([data-row="0"])')].filter((a) => a.checkVisibility()).length)),
- lit: document.querySelectorAll("[data-top-bar] [data-bar-split][data-open]").length,
+ lit: document.querySelectorAll("[data-top-bar] [data-bar-menu][data-open]").length,
panels: [...document.querySelectorAll("[data-mega-panel]")].filter((x) => !x.hidden).length,
};
});
@@ -138,7 +140,7 @@ try {
const label = `${who} ${size.width}x${size.height}`;
for (const [id, m] of Object.entries(MENUS)) {
if (size.width < m.from) {
- check(!(await bar(p).getByRole("button", { name: m.chevron, exact: true }).isVisible()), `${label} ${id}: in More at this width`);
+ check(!(await trig(p, id).isVisible()), `${label} ${id}: in More at this width`);
continue;
}
const panel = await openMenu(p, id);
@@ -161,8 +163,8 @@ try {
if (shots && who !== "account" && SHOT_WIDTHS.includes(size.width)) await shot(p, `${id}-${size.width}-${who}-light`);
await p.keyboard.press("Escape");
await panel.waitFor({ state: "hidden" });
- const back = await bar(p).getByRole("button", { name: m.chevron, exact: true }).evaluate((b) => b === document.activeElement);
- check(back, `${label} ${id}: Esc closes it and focus goes back to the chevron`);
+ const back = await trig(p, id).evaluate((b) => b === document.activeElement);
+ check(back, `${label} ${id}: Esc closes it and focus goes back to the item`);
}
check(ctx.errors.length === 0, `${label}: no console errors`, ctx.errors.join(" | "));
await ctx.close();
@@ -195,13 +197,18 @@ try {
const p = await page(ctx);
await openRoute(p, `${app}/image`, { settleMs: 300 });
for (const id of ["apps", "motions", "canvas"]) {
- const chev = bar(p).getByRole("button", { name: MENUS[id].chevron, exact: true });
- await chev.focus();
+ const item = trig(p, id);
+ await item.focus();
await p.keyboard.press("Enter");
const panel = panelOf(p, id);
await panel.waitFor({ state: "visible" });
+ check(await item.evaluate((b) => b === document.activeElement), `${id}: Enter on the item opens it, focus stays on the item`);
+ await p.keyboard.press("Enter");
+ await panel.waitFor({ state: "hidden" });
+ await p.keyboard.press("ArrowDown");
+ await panel.waitFor({ state: "visible" });
await p.waitForFunction(() => document.activeElement?.closest("[data-mega-panel]"), null, { timeout: 10_000 }).catch(() => {});
- check((await at(p)) === "0,0", `${id}: Enter on the chevron opens it on the first lead`, await at(p));
+ check((await at(p)) === "0,0", `${id}: ArrowDown on the item opens it on the first lead`, await at(p));
await p.keyboard.press("ArrowRight");
check((await at(p)) === "1,0", `${id}: Right goes to the next column's first item`, await at(p));
await p.keyboard.press("ArrowDown");
@@ -234,34 +241,35 @@ try {
await p.waitForTimeout(150);
check(!(await panel.isVisible()), `${id}: Tab past its last link closes it`);
}
- // ArrowDown on the name opens; Esc gives focus back to the name.
- for (const [id, name] of [["apps", "Apps"], ["canvas", "Canvas"]]) {
- const link = bar(p).getByRole("link", { name, exact: true });
- await link.focus();
+ // ArrowDown on the item opens; Esc gives focus back to the item.
+ for (const id of ["apps", "canvas"]) {
+ const item = trig(p, id);
+ await item.focus();
await p.keyboard.press("ArrowDown");
await p.waitForFunction(() => document.activeElement?.closest("[data-mega-panel]"), null, { timeout: 10_000 }).catch(() => {});
- check((await at(p)) === "0,0", `${id}: ArrowDown on the name opens it on the first lead`);
+ check((await at(p)) === "0,0", `${id}: ArrowDown on the item opens it on the first lead`);
await p.keyboard.press("Escape");
await p.waitForTimeout(150);
- check(await link.evaluate((a) => a === document.activeElement), `${id}: Esc gives focus back to the name`);
+ check(await item.evaluate((a) => a === document.activeElement), `${id}: Esc gives focus back to the item`);
}
// One at a time: a grouped menu replaces another, and Create's menu and a grouped menu close each other.
await openMenu(p, "apps");
await openMenu(p, "motions");
check(!(await panelOf(p, "apps").isVisible()) && (await panelOf(p, "motions").isVisible()), "opening Motions & effects closes Apps");
- await bar(p).getByRole("button", { name: "Create menu", exact: true }).click();
- await p.getByRole("menu").waitFor({ timeout: 5_000 }).catch(() => {});
- check(!(await panelOf(p, "motions").isVisible()) && (await p.getByRole("menu").count()) === 1, "opening Create closes Motions & effects");
+ await trig(p, "create").click();
+ await p.locator("#create-menu").waitFor({ timeout: 5_000 }).catch(() => {});
+ await p.waitForTimeout(200);
+ check(!(await panelOf(p, "motions").isVisible()) && (await p.locator("#create-menu").isVisible()), "opening Create closes Motions & effects");
await p.keyboard.press("Escape");
await p.waitForTimeout(200);
// Resting the mouse: every grouped menu opens after a moment (not at once), keeps focus where it was, and closes
// once the pointer leaves the item and the panel. While one is open, moving onto another item switches at once.
- for (const [id, name] of [["studios", /^Studios, \d+ studios$/], ["apps", "Apps"], ["canvas", "Canvas"]]) {
+ for (const id of ["studios", "apps", "canvas"]) {
await p.mouse.move(6, 28);
await p.waitForTimeout(400);
- const box = await bar(p).getByRole("link", { name, exact: typeof name === "string" }).boundingBox();
+ const box = await trig(p, id).boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- await p.waitForTimeout(120);
+ await p.waitForTimeout(30);
const early = await panelOf(p, id).isVisible();
await p.waitForTimeout(500);
check(!early && (await panelOf(p, id).isVisible()), `resting on ${id} opens its menu after a moment, not at once`);
@@ -271,10 +279,11 @@ try {
}
{
await openMenu(p, "apps");
- const box = await bar(p).getByRole("link", { name: "Canvas", exact: true }).boundingBox();
+ const box = await trig(p, "canvas").boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await p.waitForTimeout(80);
- check((await panelOf(p, "canvas").isVisible()) && !(await panelOf(p, "apps").isVisible()), "with Apps open, moving onto Canvas switches to it at once");
+ // (Apps may still be fading out under it for a moment: inert, no longer open.)
+ check((await panelOf(p, "canvas").getAttribute("data-phase")) === "open" && (await panelOf(p, "apps").getAttribute("data-phase")) !== "open", "with Apps open, moving onto Canvas switches to it at once");
await p.keyboard.press("Escape");
await p.mouse.move(6, 28);
await p.waitForTimeout(600);
@@ -282,7 +291,7 @@ try {
{
await p.mouse.move(700, 700);
const focusWas = await p.evaluate(() => document.activeElement?.tagName ?? "");
- const box = await bar(p).getByRole("link", { name: "Motions & effects", exact: true }).boundingBox();
+ const box = await trig(p, "motions").boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await p.waitForTimeout(700);
check(await panelOf(p, "motions").isVisible(), "resting on Motions & effects opens its menu");
@@ -295,10 +304,10 @@ try {
await p.mouse.move(6, 28, { steps: 4 }); // the bar's far left: off the item and the panel
await p.waitForTimeout(600);
check(!(await panelOf(p, "motions").isVisible()), "and closes once the pointer leaves it");
- // A click on its chevron while hover-open keeps it open (pinned), with focus inside.
+ // A click on the item while hover-open keeps it open (pinned).
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await p.waitForTimeout(700);
- await bar(p).getByRole("button", { name: MENUS.motions.chevron, exact: true }).click();
+ await trig(p, "motions").click();
await p.mouse.move(700, 800);
await p.waitForTimeout(600);
check(await panelOf(p, "motions").isVisible(), "a click pins Motions & effects open after hovering");
@@ -369,8 +378,8 @@ try {
// Warm, then open: the panel shows within a frame of the click; pictures within budget; nothing moves.
for (const id of ["apps", "motions", "canvas"]) {
const since = Date.now();
- const chev = bar(p).getByRole("button", { name: MENUS[id].chevron, exact: true });
- await chev.hover();
+ const item = trig(p, id);
+ await item.hover();
await p.waitForTimeout(1200);
await p.evaluate(() => (window.__cls = 0));
const ms = await p.evaluate(async (sel) => {
diff --git a/tests/e2e/motion.mjs b/tests/e2e/motion.mjs
index f25a8348..2cd938e3 100644
--- a/tests/e2e/motion.mjs
+++ b/tests/e2e/motion.mjs
@@ -163,13 +163,13 @@ for (const phone of [false, true]) {
// 1. A page link fades the new page in; Back is instant.
if (!only || only.includes("route")) {
await settle(page, "/");
- const link = phone ? nav().getByRole("link", { name: "Library" }) : nav().getByRole("link", { name: "Apps", exact: true });
+ const link = nav().getByRole("link", { name: "Library" }).first();
// The pinned bar at the top of a phone's page (the app bar) stays put and opaque through the change.
if (phone) await page.evaluate(TRACK_TOP);
const t0 = await now(page);
const click = Date.now();
await link.click();
- await page.waitForURL(phone ? /\/library/ : /\/apps/, { timeout: 15_000 });
+ await page.waitForURL(/\/library/, { timeout: 15_000 });
const urlMs = Date.now() - click;
await page.waitForTimeout(900);
const r = await since(page, t0);
@@ -242,44 +242,45 @@ for (const phone of [false, true]) {
if (!only || only.includes("menu") || only.includes("sheet")) {
await settle(page, "/");
if (!phone) {
- const btn = page.getByRole("button", { name: "Create menu" }).first();
+ // The bar's menus move by transitions (bar-menus.tsx, motion.css): in over the base token, out over the fast one.
+ const btn = page.locator('[data-top-bar] [data-bar-menu="create"]');
+ const opacityOf = (r, id) => r.anims.find((a) => a.id === id && a.name === "transition:opacity");
let t0 = await now(page);
await btn.click();
await page.waitForTimeout(400);
let r = await since(page, t0);
- const open = r.anims.find((a) => a.slot === "dropdown-menu-content" && a.name === "enter");
+ const open = opacityOf(r, "create-menu");
check(reduce ? !open || open.dur < 1 : !!open && near(open.dur, 200), open ? `menu opens in ${open.dur} ms` : "menu opens at once (no animation)");
longs.push({ tag, what: "menu open", ms: r.longs.reduce((s, l) => s + l.d, 0) });
t0 = await now(page);
await page.keyboard.press("Escape");
await page.waitForTimeout(400);
r = await since(page, t0);
- const close = r.anims.find((a) => a.slot === "dropdown-menu-content" && a.name === "exit");
+ const close = opacityOf(r, "create-menu");
check(!close || (reduce ? close.dur < 1 : near(close.dur, 120)), `menu closes in ${close?.dur ?? "no"} ms`);
- // A menu opened by resting on it stays open when its chevron is then clicked (the click pins it).
+ // A menu opened by resting on it stays open when the item is then clicked (the click pins it).
await page.mouse.move(5, 500);
- await page.waitForTimeout(300);
+ await page.waitForTimeout(400);
await btn.hover();
- await page.waitForTimeout(700);
- const byHover = await page.locator('[data-slot="dropdown-menu-content"]').count();
- if (byHover) {
- await btn.click();
- await page.waitForTimeout(400);
- check((await page.locator('[data-slot="dropdown-menu-content"][data-state="open"]').count()) > 0, "menu: opened by hover, a click on its chevron keeps it open");
- await page.keyboard.press("Escape");
- await page.waitForTimeout(300);
- } else console.log(" skip hover-then-click: this menu doesn't open on hover");
+ await page.waitForTimeout(400);
+ check((await page.locator('#create-menu[data-phase="open"]').count()) === 1, "menu: resting on the item opens it");
+ await btn.click();
+ await page.waitForTimeout(400);
+ check((await page.locator('#create-menu[data-phase="open"]').count()) === 1, "menu: opened by hover, a click on the item keeps it open");
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(300);
await page.mouse.move(5, 500);
- // The Studios launcher goes at once when it closes (a grouped menu that replaces it never overlaps it).
- const studios = page.getByRole("button", { name: "Studios menu" }).first();
+ await page.waitForTimeout(400);
+ // The Studios panel leaves quickly (the fast token), and is gone after.
+ const studios = page.locator('[data-top-bar] [data-bar-menu="studios"]');
await studios.click();
await page.waitForTimeout(400);
t0 = await now(page);
await page.keyboard.press("Escape");
await page.waitForTimeout(400);
r = await since(page, t0);
- const fadeOut = r.anims.some((a) => a.id === "studios-launcher" && a.name.startsWith("transition:opacity"));
- check(!fadeOut, `launcher closes at once (faded: ${fadeOut})`);
+ const fadeOut = opacityOf(r, "studios-launcher");
+ check(reduce ? !fadeOut || fadeOut.dur < 1 : !!fadeOut && near(fadeOut.dur, 120), `launcher closes over the fast token (${fadeOut?.dur ?? "no"} ms)`);
check(await page.locator("#studios-launcher").isHidden(), "launcher is gone after it closes");
} else {
for (const s of ["Create", "You"]) {
diff --git a/tests/e2e/nav-hubs.mjs b/tests/e2e/nav-hubs.mjs
index 813e2191..323b3c00 100644
--- a/tests/e2e/nav-hubs.mjs
+++ b/tests/e2e/nav-hubs.mjs
@@ -1,7 +1,7 @@
-// The area pages (/create, /studios, /apps, /motions-and-effects) and the bar's split items in a real browser: a name goes
-// to its page, a chevron (or ArrowDown, or a mouse resting on Create or Motions & effects) opens the menu, every menu and
-// phone sheet has "See all", section tabs stay under the bar, the bar keeps its width, taps are 44 px, nothing shifts,
-// nothing scrolls sideways, no console errors.
+// The area pages (/create, /studios, /apps, /motions-and-effects, /canvas) and the bar's menu items in a real browser:
+// each item is one button that opens its menu (a click, a tap, ArrowDown, or a mouse resting on it) and never leaves the
+// page, every menu and phone sheet has "See all" to its area's page, section tabs stay under the bar, the bar keeps its
+// width, taps are 44 px, nothing shifts, nothing scrolls sideways, no console errors.
// Usage: node tests/e2e/nav-hubs.mjs [appUrl] [shotsDir]
// E2E_OWNER_PASSWORD: the studio's password, when it has one. With public sign-up on, the account checks sign up a
// throwaway qa account (deleted at the end); without it the visitor is the owner and the guest/account checks are skipped.
@@ -54,142 +54,110 @@ async function page(ctx) {
const bar = (p) => p.locator("[data-top-bar]");
const pathOf = (p) => new URL(p.url()).pathname;
const activeName = (p) => p.evaluate(() => (document.activeElement?.getAttribute("aria-label") || document.activeElement?.textContent || "").replace(/\s+/g, " ").trim());
-const activeRole = (p) => p.evaluate(() => document.activeElement?.getAttribute("role") ?? document.activeElement?.tagName.toLowerCase());
const waitPath = (p, want) => p.waitForURL((u) => new URL(u).pathname === want, { timeout: 20_000 }).then(() => true, () => false);
try {
- // 1. Desktop: names go to their pages, chevrons open menus, keys, hover, See all.
+ // 1. Desktop: each item is one button that opens its menu (never leaves the page), keys, hover, See all.
{
const ctx = await as("visitor");
const p = await page(ctx);
await openRoute(p, `${app}/image`);
const items = [
- { name: "Create", href: "/create", chevron: "Create menu", seeAll: "See all of Create" },
- { name: /^Studios, \d+ studios$/, href: "/studios", chevron: "Studios menu", seeAll: "See all studios", panel: "#studios-launcher", hover: true },
- { name: "Apps", href: "/apps", chevron: "Apps menu", seeAll: "See all apps", panel: "#apps-launcher", hover: true },
- { name: "Motions & effects", href: "/motions-and-effects", chevron: "Motions & effects menu", seeAll: "See all motions and effects", panel: "#motions-launcher", hover: true },
- { name: "Canvas", href: "/canvas", chevron: "Canvas menu", seeAll: "See all of Canvas", panel: "#canvas-launcher", hover: true },
+ { id: "create", href: "/create", seeAll: "See all of Create" },
+ { id: "studios", href: "/studios", seeAll: "See all studios" },
+ { id: "apps", href: "/apps", seeAll: "See all apps" },
+ { id: "motions", href: "/motions-and-effects", seeAll: "See all motions and effects" },
+ { id: "canvas", href: "/canvas", seeAll: "See all of Canvas" },
];
- // The grouped menus (a panel under the bar) and Create (a menu).
- const seeAllIn = (it) =>
- (it.panel ? p.locator(it.panel).getByRole("link", { name: it.seeAll, exact: true }) : p.getByRole("menu").getByRole("menuitem", { name: it.seeAll, exact: true }));
- const anyPanel = () => p.locator("[data-mega-panel]:visible").count().then((n) => n > 0);
+ const trig = (id) => bar(p).locator(`[data-bar-menu="${id}"]`);
+ const surf = (id) => p.locator(id === "create" ? "#create-menu" : `#${id}-launcher`);
+ const seeAllIn = (it) => surf(it.id).getByRole("link", { name: it.seeAll, exact: true });
+ const anyOpen = () => p.locator('[data-top-bar] [data-phase="open"]').count().then((n) => n > 0);
+ const isOpen = (id) => surf(id).getAttribute("data-phase").then((v) => v === "open");
+
+ // A click opens the menu and stays on the page; Esc closes it and gives focus back to the item.
for (const it of items) {
await openRoute(p, `${app}/image`, { settleMs: 300 });
- await bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" }).click();
- const went = await waitPath(p, it.href);
- await p.locator("main h1").first().waitFor();
- check(went, `${it.href}: clicking the bar's name opens it`, pathOf(p));
- const current = await bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" }).getAttribute("aria-current");
- const others = await bar(p).locator('[data-bar-split] a[aria-current="page"]').count();
- check(current === "page" && others === 1, `${it.href}: its name is aria-current=page, and no other split item's`, `${current}, ${others}`);
- check((await p.getByRole("menu").count()) === 0 && !(await anyPanel()), `${it.href}: following the name opens no menu`);
- }
-
- // The chevron: click opens, Esc closes and gives focus back to it.
- await openRoute(p, `${app}/image`, { settleMs: 300 });
- for (const name of ["Create menu"]) {
- const chev = bar(p).getByRole("button", { name, exact: true });
- await chev.click();
- const menu = p.getByRole("menu");
- const opened = await menu.waitFor({ timeout: 5_000 }).then(() => true, () => false);
- check(opened && (await chev.getAttribute("data-state")) === "open", `${name}: the chevron opens it`);
- check(pathOf(p) === "/image", `${name}: opening it stays on the page`);
+ await trig(it.id).click();
+ await surf(it.id).waitFor({ state: "visible" });
+ check(pathOf(p) === "/image" && (await trig(it.id).getAttribute("aria-expanded")) === "true", `${it.href}: a click on the item opens its menu and stays on the page`);
await p.keyboard.press("Escape");
- await menu.waitFor({ state: "detached" }).catch(() => {});
- check(await chev.evaluate((b) => b === document.activeElement), `${name}: Esc closes it and focus goes back to the chevron`);
+ await surf(it.id).waitFor({ state: "hidden" });
+ check(await trig(it.id).evaluate((b) => b === document.activeElement), `${it.href}: Esc closes it and focus goes back to the item`);
}
- for (const it of items.filter((x) => x.panel)) {
- const chev = bar(p).getByRole("button", { name: it.chevron, exact: true });
- const panel = p.locator(it.panel);
- await chev.click();
- await panel.waitFor({ state: "visible" });
- await p.waitForFunction(() => document.activeElement?.closest("[data-mega-panel]"), null, { timeout: 5_000 }).catch(() => {});
- const at = await p.evaluate(() => [document.activeElement?.getAttribute("data-col"), document.activeElement?.getAttribute("data-row")].join(","));
- const first = it.href === "/studios" ? /^Cinema Studio/.test(await activeName(p)) : at === "0,0";
- check(first && pathOf(p) === "/image", `${it.chevron}: the chevron opens the panel on its first lead card`, `${at} ${await activeName(p)}`);
- await p.keyboard.press("Escape");
- await panel.waitFor({ state: "hidden" });
- check(await chev.evaluate((b) => b === document.activeElement), `${it.chevron}: Esc closes it and focus goes back to the chevron`);
+
+ // Each area page marks its own item, and no other.
+ for (const it of items) {
+ await openRoute(p, app + it.href, { settleMs: 300 });
+ const marked = await bar(p).locator("[data-bar-menu][data-active]").evaluateAll((els) => els.filter((e) => e.checkVisibility()).map((e) => e.dataset.barMenu));
+ check(marked.join() === it.id, `${it.href}: its item is marked, no other`, marked.join());
+ check(!(await anyOpen()), `${it.href}: arriving opens no menu`);
}
- // ArrowDown on a name opens its menu on the first row.
+ // ArrowDown on an item opens its menu on the first row; Esc gives focus back to the item.
for (const it of items) {
await openRoute(p, `${app}/image`, { settleMs: 300 });
- await bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" }).focus();
+ await trig(it.id).focus();
await p.keyboard.press("ArrowDown");
- await p.waitForTimeout(250);
// A fetched menu's links may come a moment later: focus moves in once they are there.
- if (it.panel) await p.waitForFunction(() => document.activeElement?.closest("[data-mega-panel]"), null, { timeout: 5_000 }).catch(() => {});
- const role = await activeRole(p);
- const name = await activeName(p);
+ await p.waitForFunction((sel) => document.activeElement?.closest(sel), it.id === "create" ? "#create-menu" : "[data-mega-panel]", { timeout: 5_000 }).catch(() => {});
const at = await p.evaluate(() => [document.activeElement?.getAttribute("data-col"), document.activeElement?.getAttribute("data-row")].join(","));
- const ok = it.panel ? at === "0,0" : role === "menuitem";
- check(ok && pathOf(p) === "/image", `${it.href}: ArrowDown on the name opens the menu on its first row`, `${role} ${name}`);
+ check(at === "0,0" && pathOf(p) === "/image", `${it.href}: ArrowDown on the item opens the menu on its first row`, `${at} ${await activeName(p)}`);
await p.keyboard.press("Escape");
await p.waitForTimeout(150);
- const back = await bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" }).evaluate((a) => a === document.activeElement);
- check(back, `${it.href}: Esc after ArrowDown on the name gives focus back to the name`);
+ check(await trig(it.id).evaluate((a) => a === document.activeElement), `${it.href}: Esc after ArrowDown gives focus back to the item`);
}
- // A mouse resting on any item with a menu opens it after a moment, leaves focus in the prompt being typed, and
- // leaving closes it.
+ // A mouse resting on any item opens its menu after a moment, leaves focus in the prompt being typed, and leaving
+ // closes it.
await openRoute(p, `${app}/image`, { settleMs: 300 });
const prompt = p.locator("main textarea").first();
for (const it of items) {
await prompt.focus();
- const label = bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" });
- const box = await label.boundingBox();
+ const box = await trig(it.id).boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- await p.waitForTimeout(120);
- const early = it.panel ? await anyPanel() : (await p.getByRole("menu").count()) > 0;
+ await p.waitForTimeout(40);
+ const early = await anyOpen();
await p.waitForTimeout(450);
- const late = it.panel ? await anyPanel() : (await p.getByRole("menu").count()) > 0;
- if (it.panel && !it.hover) {
- check(!early && !late, `${it.href}: resting the mouse on it opens nothing (its panel opens by a click or a key)`, `${early} → ${late}`);
- } else {
- check(!early && late, `${it.href}: resting the mouse on it opens its menu after a moment, not at once`, `${early} → ${late}`);
- check((await seeAllIn(it).count()) === 1, `${it.href}: the menu has its See all`);
- }
- const kept = await prompt.evaluate((el) => el === document.activeElement);
- check(kept, `${it.href}: resting on it leaves focus in the prompt`, await activeName(p));
- await p.mouse.move(700, 800);
- await p.waitForTimeout(600);
- // Away from the item and its panel (a full-width panel reaches down the page): the bar's far left.
- if (it.hover && it.panel) await p.mouse.move(6, 28);
- await p.waitForTimeout(it.hover ? 400 : 0);
- const gone = it.panel ? !(await anyPanel()) : (await p.getByRole("menu").count()) === 0;
- check(gone, `${it.href}: moving the mouse away closes it`);
+ const late = await isOpen(it.id);
+ check(!early && late, `${it.href}: resting the mouse on it opens its menu after a moment, not at once`, `${early} → ${late}`);
+ check((await seeAllIn(it).count()) === 1, `${it.href}: the menu has its See all`);
+ check(await prompt.evaluate((el) => el === document.activeElement), `${it.href}: resting on it leaves focus in the prompt`, await activeName(p));
+ // Away from the item and its menu (a full-width panel reaches down the page): the bar's far left.
+ await p.mouse.move(6, 28);
+ await p.waitForTimeout(700);
+ check(!(await anyOpen()), `${it.href}: moving the mouse away closes it`);
}
- // Resting on a pinned launcher's neighbour: one panel at a time.
+ // With Studios pinned open, resting on Create: one menu at a time.
{
await openRoute(p, `${app}/image`, { settleMs: 300 });
- await bar(p).getByRole("button", { name: "Studios menu", exact: true }).click();
- await p.locator("#studios-launcher").waitFor({ state: "visible" });
- const box = await bar(p).getByRole("link", { name: "Create", exact: true }).boundingBox();
+ await trig("studios").click();
+ await surf("studios").waitFor({ state: "visible" });
+ const box = await trig("create").boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- await p.waitForTimeout(600);
- const launcher = await p.locator("#studios-launcher").isVisible().catch(() => false);
- check(!launcher && (await p.getByRole("menu").count()) === 1, "resting on Create while the launcher is open swaps one for the other", `launcher ${launcher}`);
- await p.mouse.move(700, 800);
+ await p.waitForTimeout(400);
+ check(!(await isOpen("studios")) && (await isOpen("create")), "moving onto Create while Studios is open swaps one for the other");
+ await p.keyboard.press("Escape");
+ await p.mouse.move(6, 28);
await p.waitForTimeout(600);
}
- // On an area's own page, resting on its name opens nothing over it.
- for (const it of items.filter((x) => !x.panel || x.hover)) {
+ // On an area's own page, resting on its item opens its menu too (the same on every page).
+ for (const it of items) {
await openRoute(p, app + it.href, { settleMs: 300 });
- const box = await bar(p).getByRole("link", { name: it.name, exact: typeof it.name === "string" }).boundingBox();
+ const box = await trig(it.id).boundingBox();
await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- await p.waitForTimeout(700);
- check((await p.getByRole("menu").count()) === 0 && !(await anyPanel()), `${it.href}: resting on its own name there opens nothing`);
- await p.mouse.move(700, 800);
+ await p.waitForTimeout(500);
+ check(await isOpen(it.id), `${it.href}: resting on its own item there opens its menu`);
+ await p.mouse.move(6, 28);
+ await p.waitForTimeout(600);
}
// See all goes to the page.
for (const it of items) {
await openRoute(p, `${app}/image`, { settleMs: 300 });
- await bar(p).getByRole("button", { name: it.chevron, exact: true }).click();
+ await trig(it.id).click();
await seeAllIn(it).click();
check(await waitPath(p, it.href), `${it.href}: See all in the menu opens it`, pathOf(p));
}
@@ -197,21 +165,20 @@ try {
await ctx.close();
}
- // 2. A touch screen never opens a menu by hovering: a tap on the name goes to the page.
+ // 2. A touch screen: a tap on an item opens its menu (it stays on the page), a second tap closes it; 44 px to tap.
{
const ctx = await as("visitor", { viewport: { width: 1024, height: 768 }, hasTouch: true, isMobile: true });
const p = await page(ctx);
await openRoute(p, `${app}/image`);
- const fine = await p.evaluate(() => matchMedia("(hover: hover) and (pointer: fine)").matches);
- const label = bar(p).getByRole("link", { name: "Create", exact: true });
- const box = await label.boundingBox();
- await p.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- await p.waitForTimeout(500);
- check(!fine && (await p.getByRole("menu").count()) === 0, "touch: resting on Create opens nothing");
- const chev = await bar(p).getByRole("button", { name: "Create menu" }).boundingBox();
- check(chev.width >= 44 && chev.height >= 44, "touch: the chevron is 44x44", `${chev.width}x${chev.height}`);
- await label.tap();
- check((await waitPath(p, "/create")) && (await p.getByRole("menu").count()) === 0, "touch: a tap on Create goes to /create");
+ const item = bar(p).locator('[data-bar-menu="create"]');
+ const box = await item.boundingBox();
+ check(box.width >= 44 && box.height >= 44, "touch: the Create item is at least 44x44", `${box.width}x${box.height}`);
+ await item.tap();
+ await p.waitForTimeout(300);
+ check(pathOf(p) === "/image" && (await p.locator("#create-menu").getAttribute("data-phase")) === "open", "touch: a tap on Create opens its menu and stays on the page");
+ await item.tap();
+ await p.waitForTimeout(300);
+ check((await p.locator("#create-menu").getAttribute("data-phase")) !== "open", "touch: a second tap closes it");
await ctx.close();
}
@@ -236,26 +203,27 @@ try {
return { spare: Math.round(spacer.getBoundingClientRect().width), clipped: nav.scrollWidth - nav.clientWidth > 1 || h.scrollWidth - h.clientWidth > 1, hidden: nav.scrollWidth - nav.clientWidth };
});
rows.push(`${as_}${coarse ? " (touch)" : ""} @${w}: ${m.spare}px spare`);
- // With a mouse, each split item is exactly as wide as the plain item it replaced: its name, then 40 px (48 from
- // 1440) for the padding, the gap and the chevron.
+ // With a mouse, each menu item is no wider than the split item it replaced (its words, then 40 px, 48 from
+ // 1440, for the padding, the gap and the chevron), so the bar never grows.
if (!coarse) {
const off = await bar(p).evaluate((h, pad) => {
const bad = [];
- for (const s of h.querySelectorAll("[data-bar-split]")) {
+ for (const s of h.querySelectorAll("[data-bar-menu]:not([data-bar-menu=more])")) {
const r = s.getBoundingClientRect();
if (!r.width) continue;
const range = document.createRange();
- range.selectNodeContents(s.querySelector("a"));
+ range.setStartBefore(s.firstChild);
+ range.setEndBefore(s.querySelector("[data-bar-chevron]"));
const text = range.getBoundingClientRect().width;
- if (Math.abs(r.width - (text + pad)) > 1) bad.push(`${s.textContent.trim()} ${Math.round(r.width)} vs ${Math.round(text + pad)}`);
+ if (r.width > text + pad + 1) bad.push(`${s.textContent.trim()} ${Math.round(r.width)} vs ${Math.round(text + pad)}`);
}
return bad;
}, w >= 1440 ? 48 : 40);
- check(off.length === 0, `bar width: ${as_} at ${w}, each split item is as wide as the item it replaced`, off.join("; "));
+ check(off.length === 0, `bar width: ${as_} at ${w}, each menu item is no wider than the split item it replaced`, off.join("; "));
}
- // Nothing cut off. With a mouse, the split items are the old items' width (checked above), so a cut there is the
+ // Nothing cut off. With a mouse, the menu items are no wider than before (checked above), so a cut there is the
// bar's own (a guest's Log in and Sign up at 1440 cut 15 px before the split items too): reported, not failed.
- // On a touch screen the chevrons are wider (44 px), so there the bar must still fit.
+ // On a touch screen the items are 44 px tall and at least 44 wide, so there the bar must still fit.
if (coarse || !m.clipped) check(!m.clipped, `bar width: ${as_}${coarse ? " on touch" : ""} at ${w}, everything fits`, `${m.spare}px spare, ${m.hidden}px cut`);
else console.log(`note: bar width: ${as_} at ${w}: the bar's items are cut by ${m.hidden}px (as before the split items)`);
}
diff --git a/tests/e2e/nav-subfeatures.mjs b/tests/e2e/nav-subfeatures.mjs
index e74f8276..240a3320 100644
--- a/tests/e2e/nav-subfeatures.mjs
+++ b/tests/e2e/nav-subfeatures.mjs
@@ -90,13 +90,8 @@ async function openSearch(p) {
}
async function openStudios(p) {
- const chev = bar(p).getByRole("button", { name: "Studios menu", exact: true });
- await chev.click();
- // A click that met a menu the resting mouse had just opened closes it: open it again from the keyboard.
- if (!(await panel(p).waitFor({ state: "visible", timeout: 2_000 }).then(() => true, () => false))) {
- await chev.focus();
- await p.keyboard.press("Enter");
- }
+ // A click opens it, or pins it when the resting mouse opened it first: it never closes it.
+ await bar(p).locator('[data-bar-menu="studios"]').click();
await panel(p).waitFor({ state: "visible" });
await panel(p).locator('[data-col="0"][data-row="0"]').first().waitFor({ timeout: 10_000 });
await p.waitForFunction(() => [...document.querySelectorAll("#studios-launcher img")].filter((i) => i.checkVisibility()).every((i) => i.complete), null, { timeout: 10_000 }).catch(() => {});
@@ -250,9 +245,9 @@ try {
const ctx = await as("guest");
const p = await page(ctx);
await openRoute(p, `${app}/image`, { settleMs: 300 });
- const chev = bar(p).getByRole("button", { name: "Studios menu", exact: true });
+ const chev = bar(p).locator('[data-bar-menu="studios"]');
await chev.focus();
- await p.keyboard.press("Enter");
+ await p.keyboard.press("ArrowDown");
await panel(p).waitFor({ state: "visible" });
await p.waitForFunction(() => document.activeElement?.closest("[data-mega-panel]"), null, { timeout: 10_000 }).catch(() => {});
await p.keyboard.press("ArrowRight");
@@ -290,7 +285,7 @@ try {
// Enter on a link opens its page.
await p.keyboard.press("Enter");
check(await waitUrl(p, (u) => u.pathname === "/marketing/click-to-ad"), "Enter on Click to Ad opens /marketing/click-to-ad", p.url());
- check(!(await panel(p).isVisible()), "the menu closes when a link is followed");
+ check(await panel(p).waitFor({ state: "hidden", timeout: 2_000 }).then(() => true, () => false), "the menu closes when a link is followed");
await p.waitForTimeout(800);
// On a studio's feature, its link is the one marked.
await openRoute(p, `${app}/ads/multiplier`, { settleMs: 300 });
@@ -519,7 +514,7 @@ try {
const ctx = await as(who);
const p = await page(ctx);
await openRoute(p, `${app}/image`, { settleMs: 300 });
- await bar(p).getByRole("button", { name: "Canvas menu", exact: true }).click();
+ await bar(p).locator('[data-bar-menu="canvas"]').click();
const cp = p.locator("#canvas-launcher");
await cp.waitFor({ state: "visible" });
await cp.locator('[data-col="0"][data-row="0"]').first().waitFor({ timeout: 10_000 });
diff --git a/tests/e2e/nav.mjs b/tests/e2e/nav.mjs
index 915146fd..b0fa184e 100644
--- a/tests/e2e/nav.mjs
+++ b/tests/e2e/nav.mjs
@@ -79,14 +79,14 @@ try {
order.push(f?.name ?? "");
if (i > 0 && !f?.ring) rings = false;
}
- // Create, Studios, Apps, Motions & effects and Canvas are a link to their page, then their menu's chevron.
- const want = ["Skip to content", "Fuobe home", "Create", "Create menu", /^Studios, [0-9]+ studios$/, "Studios menu", "Apps", "Apps menu", "Motions & effects", "Motions & effects menu", "Canvas", "Canvas menu", "Assist", "Library", /^Search/, "New creation"];
+ // Create, Studios, Apps, Motions & effects and Canvas are one button each (their page is the menu's See all).
+ const want = ["Skip to content", "Fuobe home", "Create", /^Studios, [0-9]+ studios$/, "Apps", "Motions & effects", "Canvas", "Assist", "Library", /^Search/, "New creation"];
for (let i = order.length; i < want.length; i++) {
await p.keyboard.press("Tab");
order.push((await focused(p))?.name ?? "");
}
const ok = want.every((w, i) => (typeof w === "string" ? order[i] === w : w.test(order[i])));
- check(ok, "Tab order: Skip, wordmark, Create, Studios, Apps, Motions & effects, Canvas (each + menu), Assist, Library, Search, New creation", order.join(" › "));
+ check(ok, "Tab order: Skip, wordmark, Create, Studios, Apps, Motions & effects, Canvas, Assist, Library, Search, New creation", order.join(" › "));
check(rings, "every bar stop shows a focus ring");
// The search field is 220 px from 1440 (280 from 1600; an lg rule must not win over it), says "Search Fuobe" on one line
// until 1600, and its name is the words it shows.
@@ -117,9 +117,9 @@ try {
const heading = p.locator("main h1").first();
const before = await heading.boundingBox();
await trigger.focus();
- await p.keyboard.press("Enter");
+ await p.keyboard.press("ArrowDown");
await panel.waitFor({ state: "visible" });
- check((await trigger.getAttribute("aria-expanded")) === "true", "launcher: Enter opens it (aria-expanded)");
+ check((await trigger.getAttribute("aria-expanded")) === "true", "launcher: ArrowDown opens it (aria-expanded)");
// The panel's body is a chunk of its own: on a page this fresh it may still be on its way, and focus moves in when
// its links arrive (within a second; a warmed or idle page has it already).
const t0 = Date.now();
@@ -189,7 +189,7 @@ try {
await panel.getByRole("link", { name: /^Marketing Studio/ }).click();
const landed = await (p.waitForURL((u) => new URL(u).pathname === "/marketing", { timeout: 20_000 }).then(() => panel.waitFor({ state: "hidden" }))).then(() => true, () => false);
check(landed, "launcher: Marketing Studio lands on /marketing and the launcher closes");
- check((await trigger.locator("xpath=ancestor::*[@data-bar-split][1]").getAttribute("data-active")) !== null, "on /marketing the Studios item is marked");
+ check((await trigger.getAttribute("data-active")) !== null, "on /marketing the Studios item is marked");
await trigger.click();
check((await panel.getByRole("link", { name: /^Marketing Studio/ }).getAttribute("aria-current")) === "page", "…and Marketing Studio has aria-current=page");
await p.keyboard.press("Escape");
@@ -197,12 +197,26 @@ try {
await ctx.close();
}
- // 3. Create and the guest menu are real menus.
+ // 3. Create is a disclosure of links (like every bar menu); the guest menu is a real menu.
{
const ctx = await as("guest");
const p = await page(ctx);
await openRoute(p, `${app}/`);
- for (const name of ["Create menu", "Menu"]) {
+ {
+ const button = p.locator('[data-top-bar] [data-bar-menu="create"]');
+ await button.focus();
+ await p.keyboard.press("ArrowDown");
+ const card = p.locator("#create-menu");
+ await card.waitFor();
+ await p.waitForFunction(() => document.activeElement?.closest("#create-menu"), null, { timeout: 3000 }).catch(() => {});
+ const at = await p.evaluate(() => [document.activeElement?.tagName, document.activeElement?.dataset.col, document.activeElement?.dataset.row].join(","));
+ await p.keyboard.press("ArrowDown");
+ const down = await p.evaluate(() => document.activeElement?.dataset.row);
+ await p.keyboard.press("Escape");
+ await card.waitFor({ state: "hidden" });
+ check(at === "A,0,0" && down === "1" && (await button.evaluate((b) => b === document.activeElement)), "Create: ArrowDown opens it on its first link, arrows move, Esc gives focus back", `${at} → ${down}`);
+ }
+ for (const name of ["Menu"]) {
const button = p.locator("[data-top-bar]").getByRole("button", { name, exact: true });
await button.focus();
await p.keyboard.press("Enter");
@@ -626,11 +640,12 @@ try {
const p = await page(ctx);
await openRoute(p, `${app}/edit`);
const bar = p.locator("[data-top-bar]");
- const menu = p.getByRole("menu");
- const ITEMS = "[role=menuitem]";
+ const menu = p.locator("#create-menu");
+ const ITEMS = "[data-col]";
+ const MENU = "#create-menu";
- // On /edit the Create pill (a name and a chevron) carries the pip under it, and no fill.
- const pill = await bar.locator("[data-bar-split]").first().evaluate((e) => ({
+ // On /edit the Create item carries the pip under it, and no fill.
+ const pill = await bar.locator('[data-bar-menu="create"]').evaluate((e) => ({
pip: getComputedStyle(e, "::before").content !== "none",
fill: getComputedStyle(e).backgroundColor,
active: e.hasAttribute("data-active"),
@@ -638,12 +653,12 @@ try {
check(pill.active && pill.pip && /rgba\(0, 0, 0, 0\)|transparent/.test(pill.fill), "bar: Create (a Create page is open) has the pip under the pill, no fill", JSON.stringify(pill));
// The owner's case: on /edit, Create opened by the mouse, the mouse on Live edit.
- await bar.getByRole("button", { name: "Create menu", exact: true }).click();
+ await bar.locator('[data-bar-menu="create"]').click();
await menu.waitFor();
- const live = menu.getByRole("menuitem", { name: /^Live edit/ });
+ const live = menu.getByRole("link", { name: /^Live edit/ });
const box = await live.boundingBox();
await p.mouse.move(box.x + 30, box.y + box.height / 2, { steps: 4 });
- let rows = await states(p, "[role=menu]", ITEMS);
+ let rows = await states(p, MENU, ITEMS);
one(rows, "Create on /edit, mouse on Live edit", "Live edit");
const edit = rows.find((r) => r.name.startsWith("Edit"));
check(!!edit && edit.current && edit.pip && !edit.lit, "current page: Edit carries the pip, not the highlight fill", JSON.stringify(edit));
@@ -652,54 +667,49 @@ try {
// Keys go on from where the mouse is: Down to Inpaint, Right across to the Make column, each with the ring.
await p.keyboard.press("ArrowDown");
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
one(rows, "ArrowDown after the mouse", "Inpaint");
check(rows.find((r) => r.lit)?.ring === true, "keyboard: the highlighted row shows the 2 px ring");
await p.keyboard.press("ArrowLeft");
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
one(rows, "ArrowLeft moves across the two columns");
await p.keyboard.press("ArrowRight");
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
one(rows, "ArrowRight comes back", "Inpaint");
// The mouse takes the highlight back, without the ring; then a press shows the pressed fill.
- const image = menu.getByRole("menuitem", { name: /^Image/ });
+ const image = menu.getByRole("link", { name: /^Image/ });
const ib = await image.boundingBox();
await p.mouse.move(ib.x + 40, ib.y + ib.height / 2, { steps: 4 });
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
one(rows, "the mouse back on Image after the keys", "Image");
check(!rows.some((r) => r.ring), "mouse again: the ring steps aside");
await p.mouse.down();
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
check(rows.find((r) => r.name.startsWith("Image"))?.pressed === true, "pressed: mouse-down shows the pressed fill", JSON.stringify(rows.find((r) => r.name.startsWith("Image"))));
await p.mouse.move(ib.x + ib.width + 200, ib.y + 300);
await p.mouse.up();
- // The open menu's trigger is not a second fill beside the hovered row.
+ // The open item's own fill steps aside for the bar's one open highlight (no second fill beside the hovered row).
await p.mouse.move(ib.x + 40, ib.y + ib.height / 2, { steps: 4 });
const trig = await states(p, "[data-top-bar] nav", ":scope > div > a, :scope > div > button");
- check(!trig.some((r) => r.name.startsWith("Create") && r.lit), "open trigger: Create keeps no fill while its menu is open", JSON.stringify(trig.find((r) => r.name.startsWith("Create"))));
+ check(!trig.some((r) => r.name.startsWith("Create") && r.lit), "open trigger: Create's own fill steps aside while its menu is open", JSON.stringify(trig.find((r) => r.name.startsWith("Create"))));
- // The mouse leaves the menu: the highlight stays on Image, and ArrowDown goes on from there.
- const before = (await states(p, "[role=menu]", ITEMS)).findIndex((r) => r.name.startsWith("Image"));
+ // The mouse leaves the card: the row it left keeps focus (no fill: the highlight follows the pointer), and ArrowDown
+ // goes on from there.
+ const before = (await states(p, MENU, ITEMS)).findIndex((r) => r.name.startsWith("Image"));
const mb = await menu.boundingBox();
const outX = mb.x + mb.width + 40 < p.viewportSize().width ? mb.x + mb.width + 40 : mb.x - 40;
await p.mouse.move(outX, ib.y + ib.height / 2, { steps: 1 });
- rows = await states(p, "[role=menu]", ITEMS);
- one(rows, "the mouse left the menu: the last row keeps the highlight", "Image");
+ rows = await states(p, MENU, ITEMS);
+ check(lit(rows).length <= 1, "the mouse left the menu: at most one row lit", lit(rows).join(" | "));
await p.keyboard.press("ArrowDown");
- rows = await states(p, "[role=menu]", ITEMS);
+ rows = await states(p, MENU, ITEMS);
one(rows, "ArrowDown after the mouse left the menu");
check(rows.findIndex((r) => r.lit) === before + 1, "ArrowDown goes on from the row the mouse left", lit(rows).join(" | "));
-
- // Typeahead after the mouse: the letter hands the lead to the keyboard, so the row it picks shows the ring.
- await p.mouse.move(ib.x + 40, ib.y + ib.height / 2, { steps: 4 });
- await p.keyboard.press("i");
- rows = await states(p, "[role=menu]", ITEMS);
- one(rows, "typeahead after the mouse");
- check(rows.find((r) => r.lit)?.ring === true, "typeahead: the picked row shows the ring", JSON.stringify(rows.find((r) => r.lit)));
+ check(rows.find((r) => r.lit)?.ring === true, "keyboard after the mouse: the row shows the ring", JSON.stringify(rows.find((r) => r.lit)));
await p.keyboard.press("Escape");
- await menu.waitFor({ state: "detached" }).catch(() => {});
+ await menu.waitFor({ state: "hidden" }).catch(() => {});
// A bar control outside the menus (search field) under a resting mouse drops its hover once the keyboard leads.
{
@@ -720,11 +730,11 @@ try {
// The bar on /library: the hovered item is the one highlight, Library keeps only its pip.
await openRoute(p, `${app}/library`);
- const create = bar.getByRole("link", { name: "Create", exact: true });
- const cb = await create.boundingBox();
+ const assist = bar.getByRole("link", { name: "Assist", exact: true });
+ const cb = await assist.boundingBox();
await p.mouse.move(cb.x + cb.width / 2, cb.y + cb.height / 2, { steps: 3 });
rows = await states(p, "[data-top-bar] nav", ":scope > a, :scope > button, :scope > div > a, :scope > div > button");
- one(rows, "bar on /library, mouse on Create", "Create");
+ one(rows, "bar on /library, mouse on Assist", "Assist");
const library = rows.find((r) => r.name === "Library");
check(!!library && library.current && library.pip && !library.lit, "bar: Library (current) has the pip, no fill", JSON.stringify(library));
diff --git a/tests/nav-bar.test.ts b/tests/nav-bar.test.ts
index 855e7b06..85feaa08 100644
--- a/tests/nav-bar.test.ts
+++ b/tests/nav-bar.test.ts
@@ -270,12 +270,14 @@ describe("the bar's shell", () => {
expect(html).toContain("<header");
expect(html).toContain('aria-label="Main"');
expect(html).toContain('aria-label="Fuobe home"');
- // The panel is not on the page until warmed, so nothing points at it yet.
- expect(html).not.toContain(`aria-controls="${LAUNCHER_ID}"`);
+ // Each menu's section is on the page from the first paint (hidden and empty until warmed), so aria-controls
+ // always points at something.
+ expect(html).toContain(`aria-controls="${LAUNCHER_ID}"`);
+ expect(html).toMatch(new RegExp(`<section[^>]*id="${LAUNCHER_ID}"[^>]*hidden`));
expect(html).toContain('aria-expanded="false"');
- expect(html).not.toContain(`id="${LAUNCHER_ID}"`);
expect(html).toContain(`>${studioCount()}<`);
- for (const h of ["/", "/apps", "/canvas", "/assist", "/library", "/?new=1"]) expect(hrefs(html), h).toContain(h);
+ for (const h of ["/", "/assist", "/library", "/?new=1"]) expect(hrefs(html), h).toContain(h);
+ for (const h of ["/create", "/studios", "/apps", "/motions-and-effects", "/canvas"]) expect(html, h).toContain(`data-href="${h}"`);
// Search's name is the words it shows (sr-only below lg).
expect(html).toContain(">Search Fuobe</span>");
expect(html).not.toContain('aria-label="Search Fuobe"');
@@ -297,8 +299,8 @@ describe("the bar's shell", () => {
expect(html).toContain('aria-label="Menu"');
for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&amp;", "&"));
expect(html).not.toContain("data-dot");
- // On a studio's page the Studios item is marked (the pill around its name and its chevron).
- expect(html).toMatch(/<div[^>]*data-bar-split[^>]*data-active="true"[^>]*>\s*<a[^>]*href="\/studios"/);
+ // On a studio's page the Studios item is marked.
+ expect(html).toMatch(/<button[^>]*data-bar-menu="studios"[^>]*data-active="true"/);
});
it("gives an account its avatar, with a dot only when its own GPU answers", () => {
@@ -426,33 +428,52 @@ describe("the avatar's dot", () => {
});
});
-describe("split items: the name goes to the area page, the chevron opens the menu", () => {
+describe("menu items: one button each, the area's page inside its menu", () => {
/** The opening tag of the link to `href` in the bar's markup. */
const linkTo = (html: string, href: string) => anchors(html).find((a) => a.href === href)?.tag ?? "";
+ /** The opening tag of a menu item's button. */
+ const item = (html: string, id: string) => new RegExp(`<button[^>]*data-bar-menu="${id}"[^>]*>`).exec(html)?.[0] ?? "";
- it("gives Create, Studios, Apps, Motions & effects and Canvas a link to their page and a named chevron, in one pill", () => {
+ it("gives Create, Studios, Apps, Motions & effects, Canvas and More one button each, named by its words", () => {
const html = render(createElement(TopBar));
- for (const href of ["/create", "/studios", "/apps", "/motions-and-effects", "/canvas"]) expect(linkTo(html, href), href).not.toBe("");
- expect(linkTo(html, "/studios")).toContain(`aria-label="Studios, ${studioCount()} studios"`);
- for (const name of ["Create menu", "Studios menu", "Apps menu", "Motions &amp; effects menu", "Canvas menu"]) expect(html, name).toContain(`aria-label="${name}"`);
- // The Studios chevron is still the launcher's disclosure button (search hands focus back to it).
- expect(html).toMatch(/<button[^>]*aria-label="Studios menu"[^>]*aria-expanded="false"[^>]*data-studios-trigger/);
- expect(count(html, "data-bar-split")).toBe(5);
- });
-
- it("marks the name on its own page and the pill inside its area, never both items", () => {
+ const hubs = [
+ ["create", "/create"],
+ ["studios", "/studios"],
+ ["apps", "/apps"],
+ ["motions", "/motions-and-effects"],
+ ["canvas", "/canvas"],
+ ] as const;
+ for (const [id, href] of hubs) {
+ expect(item(html, id), id).toContain('aria-expanded="false"');
+ expect(item(html, id), id).toMatch(/aria-controls="[^"]+"/);
+ // The area's page is the menu's "See all" (and Ctrl-click on the item): no separate link beside it.
+ expect(item(html, id), id).toContain(`data-href="${href}"`);
+ expect(linkTo(html, href), href).toBe("");
+ }
+ expect(item(html, "more")).toContain('aria-expanded="false"');
+ expect(item(html, "more")).not.toContain("data-href");
+ expect(item(html, "studios")).toContain(`aria-label="Studios, ${studioCount()} studios"`);
+ // The Studios item is still the launcher's disclosure button (search hands focus back to it).
+ expect(item(html, "studios")).toContain("data-studios-trigger");
+ for (const name of ["Create menu", "Studios menu", "Apps menu", "Motions &amp; effects menu", "Canvas menu"]) expect(html, name).not.toContain(`aria-label="${name}"`);
+ expect(html).not.toContain("data-bar-split");
+ expect(html).not.toMatch(/role="menu"|role="menuitem"|aria-haspopup="menu"/);
+ expect(count(html, "data-bar-menu=")).toBe(6);
+ });
+
+ it("marks the item anywhere in its area, its own page included, and only that item", () => {
state.path = "/create";
let html = render(createElement(TopBar));
- expect(linkTo(html, "/create")).toContain('aria-current="page"');
- expect(linkTo(html, "/studios")).not.toContain("aria-current");
+ expect(item(html, "create")).toContain('data-active="true"');
+ expect(item(html, "studios")).not.toContain("data-active");
state.path = "/image";
html = render(createElement(TopBar));
- expect(linkTo(html, "/create")).not.toContain("aria-current");
- expect(html).toMatch(/<div[^>]*data-bar-split[^>]*data-active="true"[^>]*>\s*<a[^>]*href="\/create"/);
+ expect(item(html, "create")).toContain('data-active="true"');
expect(count(html, 'data-active="true"')).toBe(1);
state.path = "/canvas";
html = render(createElement(TopBar));
- expect(html).not.toMatch(/<div[^>]*data-bar-split[^>]*data-active="true"[^>]*>\s*<a[^>]*href="\/create"/);
+ expect(item(html, "create")).not.toContain("data-active");
+ expect(item(html, "canvas")).toContain('data-active="true"');
});
it("links the launcher's header to every studio with previews", async () => {