From 35f4d477e3cb9020ef2acae699493eed814a81f4 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:17:11 +0800 Subject: [PATCH] feat(canvas): open selection toolbar menus on hover The node action bar required a click on every labelled menu (presets, marketing tools, layout). Open it when the pointer rests on the label, keep it open while the pointer travels into the menu, and close it when both are left. A pointer-opened menu leaves focus on the label, so hovering never moves the keyboard focus; a click still opens and focuses the first item as before. The delays make a quick pass along the bar open only the label under the pointer. Refs #571 --- scripts/run-browser-suite.mjs | 1 + src/canvas/NodeSelectionToolbar.tsx | 70 ++++++++++++++- src/canvas/SelectionToolbarMenu.tsx | 29 +++++-- tests/browser/manifest.json | 5 ++ tests/browser/selection_toolbar_hover.mjs | 101 ++++++++++++++++++++++ 5 files changed, 195 insertions(+), 11 deletions(-) create mode 100644 tests/browser/selection_toolbar_hover.mjs diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 46ba6ca0b..93e8ee130 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -81,6 +81,7 @@ const workflows = [ env: { PYTHON: "python" }, }, { name: "first-run setup", script: "tests/browser/first_run.mjs" }, + { name: "selection toolbar hover", script: "tests/browser/selection_toolbar_hover.mjs" }, { name: "model editor hosts", script: "tests/browser/model_editor_hosts.mjs" }, ]; diff --git a/src/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index d4504f27a..b91bfd48d 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -99,6 +99,8 @@ type OpenMenu = { anchor: HTMLButtonElement; initialFocus: "first" | "last"; grid?: boolean; + /** Opened by pointing at the label, so the menu must not take focus. */ + hover?: boolean; }; const imageTools: readonly [CanvasToolId, MessageKey, string, ToolGlyphName][] = @@ -159,6 +161,27 @@ export function NodeSelectionToolbar({ const [openMenu, setOpenMenu] = useState(null); const hasMedia = Boolean(node.data.src) && node.data.assetState !== "missing"; useEffect(() => setOpenMenu(null), [node.id, node.type, locked, hasMedia]); + // Pointing at a labelled action opens its menu; moving away closes it. The + // delay keeps a pointer passing over the bar from opening every menu, and the + // menu itself cancels the close so a diagonal move still reaches it. + const openTimer = useRef(null); + const closeTimer = useRef(null); + const cancelOpen = () => { + if (openTimer.current !== null) { + window.clearTimeout(openTimer.current); + openTimer.current = null; + } + }; + const cancelClose = () => { + if (closeTimer.current !== null) { + window.clearTimeout(closeTimer.current); + closeTimer.current = null; + } + }; + useEffect(() => () => { + cancelOpen(); + cancelClose(); + }, []); const mediaKind = ["image", "video", "audio", "file"].includes(node.type); if (mediaKind && !hasMedia) return null; @@ -491,9 +514,16 @@ export function NodeSelectionToolbar({ action: Action, anchor: HTMLButtonElement, initialFocus: "first" | "last" = "first", + hover = false, ) => { if (action.disabled) return; - setOpenMenu({ nodeId: node.id, actionId: action.id, anchor, initialFocus }); + setOpenMenu({ + nodeId: node.id, + actionId: action.id, + anchor, + initialFocus, + hover, + }); }; const navigate = (event: KeyboardEvent) => { @@ -574,14 +604,39 @@ export function NodeSelectionToolbar({ className={`${action.iconOnly ? "is-icon-only" : ""}${action.destructive ? " is-destructive" : ""}`} disabled={action.disabled} onClick={(event) => { + cancelOpen(); + cancelClose(); if (action.options) { - if (menuAction?.id === action.id) setOpenMenu(null); + if (menuAction?.id === action.id && !openMenu?.hover) + setOpenMenu(null); else showMenu(action, event.currentTarget); } else { setOpenMenu(null); action.run?.(); } }} + onMouseEnter={(event) => { + if (!action.options || action.disabled || locked) return; + cancelClose(); + cancelOpen(); + const anchor = event.currentTarget; + if (openMenu?.actionId === action.id) return; + openTimer.current = window.setTimeout(() => { + openTimer.current = null; + showMenu(action, anchor, "first", true); + }, 120); + }} + onMouseLeave={() => { + cancelOpen(); + if (openMenu?.hover && openMenu.actionId === action.id) { + cancelClose(); + closeTimer.current = window.setTimeout(() => { + closeTimer.current = null; + setOpenMenu(null); + }, 180); + } + }} + onFocus={() => cancelOpen()} onKeyDown={(event) => { if ( !action.options || @@ -590,6 +645,7 @@ export function NodeSelectionToolbar({ return; event.preventDefault(); event.stopPropagation(); + cancelOpen(); showMenu( action, event.currentTarget, @@ -641,6 +697,16 @@ export function NodeSelectionToolbar({ } role={openMenu.grid ? "dialog" : "menu"} initialFocus={openMenu.initialFocus} + focusOnMount={!openMenu.hover} + onPointerEnter={cancelClose} + onPointerLeave={() => { + if (!openMenu.hover) return; + cancelClose(); + closeTimer.current = window.setTimeout(() => { + closeTimer.current = null; + setOpenMenu(null); + }, 180); + }} onClose={() => setOpenMenu(null)} > {openMenu.grid ? ( diff --git a/src/canvas/SelectionToolbarMenu.tsx b/src/canvas/SelectionToolbarMenu.tsx index 0235021fe..759944827 100644 --- a/src/canvas/SelectionToolbarMenu.tsx +++ b/src/canvas/SelectionToolbarMenu.tsx @@ -10,7 +10,10 @@ export function SelectionToolbarMenu({ label, role = "menu", initialFocus = "first", + focusOnMount = true, onClose, + onPointerEnter, + onPointerLeave, children, }: { anchor: HTMLButtonElement; @@ -18,7 +21,11 @@ export function SelectionToolbarMenu({ label: string; role?: "menu" | "dialog"; initialFocus?: "first" | "last"; + /** Pointer-opened menus leave focus on the toolbar label. */ + focusOnMount?: boolean; onClose: () => void; + onPointerEnter?: () => void; + onPointerLeave?: () => void; children: ReactNode; }) { const root = useRef(null); @@ -78,14 +85,16 @@ export function SelectionToolbarMenu({ frame = requestAnimationFrame(place); }; place(); - const items = panel.querySelectorAll( - role === "menu" - ? '[role="menuitem"]:not(:disabled),[role="menuitemradio"]:not(:disabled)' - : 'input:not(:disabled),button:not(:disabled):not([tabindex="-1"])', - ); - (items[initialFocus === "last" ? items.length - 1 : 0] ?? panel).focus({ - preventScroll: true, - }); + if (focusOnMount) { + const items = panel.querySelectorAll( + role === "menu" + ? '[role="menuitem"]:not(:disabled),[role="menuitemradio"]:not(:disabled)' + : 'input:not(:disabled),button:not(:disabled):not([tabindex="-1"])', + ); + (items[initialFocus === "last" ? items.length - 1 : 0] ?? panel).focus({ + preventScroll: true, + }); + } const dismiss = (event: PointerEvent) => { if ( event.target instanceof Node && @@ -118,7 +127,7 @@ export function SelectionToolbarMenu({ window.removeEventListener("focusin", dismissOnFocus, true); window.removeEventListener("keydown", escape, true); }; - }, [anchor, initialFocus, role]); + }, [anchor, focusOnMount, initialFocus, role]); return createPortal(
event.stopPropagation()} + onPointerEnter={onPointerEnter} + onPointerLeave={onPointerLeave} onClick={(event) => event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()} onWheel={(event) => event.stopPropagation()} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 97021655d..adf969d48 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -127,6 +127,11 @@ "lanes": ["gate"], "note": "First launch: assistant prerequisite, task-specific model setup and direct access to examples." }, + { + "file": "selection_toolbar_hover.mjs", + "lanes": ["gate"], + "note": "Pointing at a labelled action opens its menu without a click, keeps it open across the pointer gap, and never steals focus." + }, { "file": "model_editor_hosts.mjs", "previewSafe": true, diff --git a/tests/browser/selection_toolbar_hover.mjs b/tests/browser/selection_toolbar_hover.mjs new file mode 100644 index 000000000..5a410fa11 --- /dev/null +++ b/tests/browser/selection_toolbar_hover.mjs @@ -0,0 +1,101 @@ +/** Isolated fixture only: pointing at a labelled toolbar action opens its menu without a click. */ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const headers = { "X-OpenDirector-Request": "1" }; +const health = await fetch(`${base}/api/creation-test-health`, { headers }); +assert.ok(health.ok && (await health.json()).isolated, "Requires an isolated creation API"); + +const browser = await launchBrowser(); +try { + const page = await browser.newPage({ locale: "en-US", viewport: { width: 1440, height: 900 } }); + await page.addInitScript(() => { + try { localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); } catch {} + }); + page.setDefaultTimeout(20000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + + const seed = await browser.newPage({ locale: "en-US" }); + await seed.route((url) => url.pathname === "/", (route) => + route.fulfill({ contentType: "text/html", body: "" })); + await seed.goto(`${base}/`); + const fixture = await seed.evaluate(async () => { + const { createDocument, createNode } = await import("/src/canvas/model.ts"); + const { importWorkspaceDocument } = await import("/src/backend/workspace.ts"); + const { releaseBackendProject } = await import("/src/backend/projects.ts"); + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 96; + const context = canvas.getContext("2d"); + context.fillStyle = "hsl(210,60%,45%)"; + context.fillRect(0, 0, 96, 96); + const doc = createDocument(`Hover ${crypto.randomUUID().slice(0, 8)}`); + const node = createNode("image", { x: 200, y: 160 }, { + title: "Hover target", mediaRole: "asset", src: canvas.toDataURL("image/png"), + mimeType: "image/png", assetState: "ready", + }); + doc.nodes = [node]; + const saved = await importWorkspaceDocument(doc); + await releaseBackendProject(); + return { id: saved.id, node: node.id }; + }); + await seed.close(); + + await page.goto(`${base}/ai-tool/ai-canvas/${fixture.id}`); + await page.waitForFunction(() => { + const workspace = document.querySelector(".cw-workspace"); + return workspace?.getAttribute("aria-busy") === "false" && !workspace.inert; + }); + const node = page.locator(`.react-flow__node[data-id="${fixture.node}"]`); + await node.waitFor(); + await node.click(); + + const toolbar = page.getByRole("toolbar", { name: "Node actions" }); + await toolbar.waitFor(); + const label = toolbar.getByRole("button", { name: "Marketing tools", exact: true }); + await label.waitFor(); + const menu = page.getByRole("menu"); + assert.equal(await menu.count(), 0, "the menu must start closed"); + + // Pointing at the label opens it; the toolbar keeps focus so hover never steals it. + await label.hover(); + await menu.waitFor({ timeout: 4000 }); + await menu.getByRole("menuitem").first().waitFor(); + assert.equal( + await label.evaluate((element) => document.activeElement === element), + false, + "a hover-opened menu must not focus the label", + ); + assert.equal( + await menu.evaluate((element) => element.contains(document.activeElement)), + false, + "a hover-opened menu must not steal focus into its first item", + ); + + // Moving the pointer from the label into the menu keeps it open. + const first = menu.getByRole("menuitem").first(); + const box = await first.boundingBox(); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 12 }); + await page.waitForTimeout(400); + assert.equal(await menu.count(), 1, "moving into the menu must not close it"); + + // Leaving both closes it again. + await page.mouse.move(60, 700, { steps: 12 }); + await menu.waitFor({ state: "detached", timeout: 4000 }); + + // A click still opens it and focuses the first item, as before. + await label.click(); + await menu.waitFor(); + assert.equal( + await menu.evaluate((element) => element.contains(document.activeElement)), + true, + "a clicked menu keeps focusing its first item", + ); + await page.keyboard.press("Escape"); + await menu.waitFor({ state: "detached", timeout: 4000 }); + assert.deepEqual(errors, []); + console.log("Selection toolbar opens on hover without stealing focus and still opens on click"); +} finally { + await browser.close(); +}