Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/run-browser-suite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
];

Expand Down
70 changes: 68 additions & 2 deletions src/canvas/NodeSelectionToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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][] =
Expand Down Expand Up @@ -159,6 +161,27 @@ export function NodeSelectionToolbar({
const [openMenu, setOpenMenu] = useState<OpenMenu | null>(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<number | null>(null);
const closeTimer = useRef<number | null>(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;

Expand Down Expand Up @@ -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<HTMLDivElement>) => {
Expand Down Expand Up @@ -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 ||
Expand All @@ -590,6 +645,7 @@ export function NodeSelectionToolbar({
return;
event.preventDefault();
event.stopPropagation();
cancelOpen();
showMenu(
action,
event.currentTarget,
Expand Down Expand Up @@ -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 ? (
Expand Down
29 changes: 20 additions & 9 deletions src/canvas/SelectionToolbarMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,22 @@ export function SelectionToolbarMenu({
label,
role = "menu",
initialFocus = "first",
focusOnMount = true,
onClose,
onPointerEnter,
onPointerLeave,
children,
}: {
anchor: HTMLButtonElement;
id: string;
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<HTMLDivElement>(null);
Expand Down Expand Up @@ -78,14 +85,16 @@ export function SelectionToolbarMenu({
frame = requestAnimationFrame(place);
};
place();
const items = panel.querySelectorAll<HTMLElement>(
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<HTMLElement>(
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 &&
Expand Down Expand Up @@ -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(
<div
Expand All @@ -130,6 +139,8 @@ export function SelectionToolbarMenu({
className="cw-selection-menu nodrag nopan nowheel"
style={{ visibility: "hidden" }}
onPointerDown={(event) => event.stopPropagation()}
onPointerEnter={onPointerEnter}
onPointerLeave={onPointerLeave}
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
onWheel={(event) => event.stopPropagation()}
Expand Down
5 changes: 5 additions & 0 deletions tests/browser/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
101 changes: 101 additions & 0 deletions tests/browser/selection_toolbar_hover.mjs
Original file line number Diff line number Diff line change
@@ -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: "<html><body></body></html>" }));
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();
}
Loading