import { afterEach, expect, it, vi } from "vitest"; import { mount, flushPromises } from "@vue/test-utils"; import { defineComponent, h, ref, nextTick } from "vue"; import { Button, DropdownRoot, DropdownTrigger, DropdownPopover, DropdownMenu, DropdownItem, DropdownItemIndicator, DropdownSection, DropdownSubmenuTrigger, DropdownSubmenuIndicator, Avatar, AvatarFallback, Header, Label, Menu, MenuItem, MenuSection, } from "../packages/vue/src"; import type { MenuKey } from "../packages/vue/src"; const cleanup: (() => void)[] = []; afterEach(() => { cleanup .splice(0) .reverse() .forEach((fn) => fn()); vi.useRealTimers(); document.body.innerHTML = ""; }); function mountApp(setup: () => unknown, render?: () => unknown) { const w = mount( defineComponent( render ? { setup: setup as never, render: render as never } : { setup: setup as never }, ), { attachTo: document.body }, ); cleanup.push(() => w.unmount()); return w; } it("Dropdown opens and action item fires once", async () => { const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "操作"), h(DropdownPopover, {}, () => h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => [ h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () => h(Label, () => "新建文件"), ), h( DropdownItem, { id: "delete-file", textValue: "删除文件", variant: "danger" }, () => h(Label, () => "删除文件"), ), ]), ), ]), ); await flushPromises(); await nextTick(); const items = document.querySelectorAll('[data-slot="menu-item"]'); expect(items.length).toBe(2); expect((items[1] as HTMLElement).className).toContain("hv-menu-item--danger"); expect((items[0] as HTMLElement).getAttribute("role")).toBe("menuitem"); (items[0] as HTMLElement).click(); await flushPromises(); expect(actions).toEqual(["new-file"]); }); it("Menu multiple selection toggles keys", async () => { const selected = ref(["apple"]); mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "水果"), h(DropdownPopover, {}, () => h( DropdownMenu, { selectionMode: "multiple", selectedKeys: selected.value, "onUpdate:selectedKeys": (k: (string | number)[]) => { selected.value = k as string[]; }, }, () => [ h(DropdownItem, { id: "apple", textValue: "苹果" }, () => [ h(DropdownItemIndicator), h(Label, () => "苹果"), ]), h(DropdownItem, { id: "banana", textValue: "香蕉" }, () => [ h(DropdownItemIndicator), h(Label, () => "香蕉"), ]), ], ), ), ]), ); await flushPromises(); await nextTick(); const items = document.querySelectorAll('[data-slot="menu-item"]'); expect(items.length).toBe(2); (items[1] as HTMLElement).click(); await flushPromises(); await nextTick(); expect(selected.value).toContain("banana"); expect(selected.value).toContain("apple"); }); it("MenuSection can own section-level selection", async () => { const styles = ref(["bold"]); mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "样式"), h(DropdownPopover, {}, () => h(Menu, {}, () => h( MenuSection, { selectionMode: "multiple", selectedKeys: styles.value, "onUpdate:selectedKeys": (k: (string | number)[]) => { styles.value = k as string[]; }, }, () => [ h(MenuItem, { id: "bold", textValue: "粗体" }, () => h(Label, () => "粗体"), ), h(MenuItem, { id: "italic", textValue: "斜体" }, () => h(Label, () => "斜体"), ), ], ), ), ), ]), ); await flushPromises(); await nextTick(); const items = document.querySelectorAll('[data-slot="menu-item"]'); expect(items.length).toBe(2); (items[1] as HTMLElement).click(); await flushPromises(); await nextTick(); expect(styles.value).toEqual(expect.arrayContaining(["bold", "italic"])); }); it("disabled item is marked disabled", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "操作"), h(DropdownPopover, {}, () => h(Menu, { disabledKeys: ["x"] }, () => h(MenuItem, { id: "x", textValue: "X" }, () => h(Label, () => "X")), ), ), ]), ); await flushPromises(); await nextTick(); const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; expect(item).toBeTruthy(); const disabled = item.hasAttribute("disabled") || item.getAttribute("aria-disabled") === "true" || item.getAttribute("data-disabled") === "true" || (item as HTMLInputElement).disabled === true; expect(disabled).toBe(true); }); it("indicator uses checkmark svg and data-visible when selected", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "水果"), h(DropdownPopover, {}, () => h( DropdownMenu, { selectionMode: "multiple", selectedKeys: ["apple"] }, () => [ h(DropdownItem, { id: "apple", textValue: "苹果" }, () => [ h(DropdownItemIndicator), h(Label, () => "苹果"), ]), ], ), ), ]), ); await flushPromises(); await nextTick(); const ind = document.querySelector('[data-slot="menu-item-indicator"]'); expect(ind).toBeTruthy(); expect(ind!.getAttribute("data-type")).toBe("checkmark"); expect( ind!.querySelector('[data-slot="menu-item-indicator--checkmark"]'), ).not.toBeNull(); }); it("submenu trigger opens nested items", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "分享"), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => [ h(DropdownItem, { id: "copy-link", textValue: "复制链接" }, () => h(Label, () => "复制链接"), ), h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "share", textValue: "分享" }, () => [ h(Label, () => "其他"), h(DropdownSubmenuIndicator), ]), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h( DropdownItem, { id: "whatsapp", textValue: "WhatsApp" }, () => h(Label, () => "WhatsApp"), ), ), ), ]), ]), ), ]), ); await flushPromises(); await nextTick(); const triggers = document.querySelectorAll( '[data-slot="menu-item"][data-has-submenu="true"], [data-slot="dropdown-submenu-trigger"]', ); expect(triggers.length).toBeGreaterThanOrEqual(1); // Open submenu via pointer (Reka SubTrigger) (triggers[0] as HTMLElement).dispatchEvent( new MouseEvent("pointerenter", { bubbles: true }), ); (triggers[0] as HTMLElement).click(); await flushPromises(); await nextTick(); const html = document.body.innerHTML; expect(html).toContain("WhatsApp"); expect(html).toContain("其他"); }); it("long-press trigger opens on hold and suppresses click", async () => { vi.useFakeTimers(); const w = mountApp( () => () => h(DropdownRoot, { trigger: "longPress", longPressDuration: 300 }, () => [ h(DropdownTrigger, {}, () => h(Button, { "aria-label": "菜单" }, () => "长按"), ), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "x", textValue: "X" }, () => h(Label, () => "X"), ), ), ), ]), ); await flushPromises(); const btn = w.get("button"); btn.trigger("pointerdown", { button: 0, clientX: 10, clientY: 10 }); await vi.advanceTimersByTimeAsync(350); await nextTick(); expect( document .querySelector('[data-slot="dropdown-popover"]') ?.getAttribute("data-state"), ).toBe("open"); vi.useRealTimers(); }); it("long-press cancel on move threshold", async () => { vi.useFakeTimers(); mountApp( () => () => h(DropdownRoot, { trigger: "longPress", longPressDuration: 300 }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "长按")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "x", textValue: "X" }, () => h(Label, () => "X"), ), ), ), ]), ); await flushPromises(); const btn = document.querySelector("button") as HTMLElement; btn.dispatchEvent( new MouseEvent("pointerdown", { bubbles: true, button: 0, clientX: 0, clientY: 0, }), ); btn.dispatchEvent( new MouseEvent("pointermove", { bubbles: true, clientX: 40, clientY: 0 }), ); await vi.advanceTimersByTimeAsync(400); await nextTick(); expect( document .querySelector('[data-slot="dropdown-popover"]') ?.getAttribute("data-state"), ).not.toBe("open"); vi.useRealTimers(); }); function pointer( type: string, props: Record = {}, ): MouseEvent { const event = new MouseEvent(type, { bubbles: true, cancelable: true, ...(props as MouseEventInit), }); for (const key of ["pointerType", "isPrimary"]) { if (key in props) { Object.defineProperty(event, key, { value: props[key] }); } } return event; } function mountLongPress(duration = 300) { const actions: MenuKey[] = []; const w = mountApp( () => () => h( DropdownRoot, { trigger: "longPress", longPressDuration: duration }, () => [ h(DropdownTrigger, {}, () => h(Button, { "aria-label": "菜单" }, () => "长按"), ), h(DropdownPopover, {}, () => h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h(DropdownItem, { id: "x", textValue: "X" }, () => h(Label, () => "X"), ), ), ), ], ), ); return { w, actions, button: () => w.get("button").element as HTMLElement }; } function menuState() { return ( document .querySelector('[data-slot="dropdown-popover"]') ?.getAttribute("data-state") ?? null ); } it("longPress: short click on the real trigger does not open", async () => { vi.useFakeTimers(); const { button } = mountLongPress(); await flushPromises(); button().click(); await flushPromises(); await vi.advanceTimersByTimeAsync(600); await nextTick(); expect(menuState()).toBeNull(); vi.useRealTimers(); }); it("longPress: opens at the threshold and stays open after release", async () => { vi.useFakeTimers(); const { button } = mountLongPress(); await flushPromises(); const el = button(); el.dispatchEvent(pointer("pointerdown", { button: 0, pointerType: "mouse" })); await vi.advanceTimersByTimeAsync(200); await nextTick(); expect(menuState()).toBeNull(); await vi.advanceTimersByTimeAsync(150); await nextTick(); expect(menuState()).toBe("open"); el.dispatchEvent(pointer("pointerup", { button: 0, pointerType: "mouse" })); el.click(); await flushPromises(); await nextTick(); expect(menuState()).toBe("open"); vi.useRealTimers(); }); it("longPress: pointercancel and out-of-range movement cancel the pending open", async () => { vi.useFakeTimers(); const { button } = mountLongPress(); await flushPromises(); const el = button(); el.dispatchEvent(pointer("pointerdown", { button: 0, pointerType: "mouse" })); el.dispatchEvent(pointer("pointermove", { clientX: 40, clientY: 0 })); await vi.advanceTimersByTimeAsync(400); await nextTick(); expect(menuState()).toBeNull(); el.dispatchEvent( pointer("pointerdown", { button: 0, clientX: 0, clientY: 0 }), ); el.dispatchEvent(pointer("pointercancel", {})); await vi.advanceTimersByTimeAsync(400); await nextTick(); expect(menuState()).toBeNull(); vi.useRealTimers(); }); it("longPress: non-primary button and non-primary pointer are ignored", async () => { vi.useFakeTimers(); const { button } = mountLongPress(); await flushPromises(); const el = button(); el.dispatchEvent(pointer("pointerdown", { button: 2, pointerType: "mouse" })); await vi.advanceTimersByTimeAsync(400); await nextTick(); expect(menuState()).toBeNull(); el.dispatchEvent(pointer("pointerdown", { button: 0, isPrimary: false })); await vi.advanceTimersByTimeAsync(400); await nextTick(); expect(menuState()).toBeNull(); vi.useRealTimers(); }); it("longPress: Enter and Space open once from the keyboard", async () => { const { w } = mountLongPress(); await flushPromises(); await w.get("button").trigger("keydown", { key: "Enter" }); await flushPromises(); expect(menuState()).toBe("open"); await w.get("button").trigger("keydown", { key: " " }); await flushPromises(); expect(menuState()).toBeNull(); await w.get("button").trigger("keydown", { key: " " }); await flushPromises(); expect(menuState()).toBe("open"); }); it("longPress: unmount clears the pending long-press timer", async () => { vi.useFakeTimers(); const { w } = mountLongPress(); await flushPromises(); (w.get("button").element as HTMLElement).dispatchEvent( pointer("pointerdown", { button: 0 }), ); expect(vi.getTimerCount()).toBeGreaterThan(0); w.unmount(); cleanup.pop(); await nextTick(); expect(vi.getTimerCount()).toBe(0); vi.useRealTimers(); }); function mountSubmenu() { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => [ h(DropdownItem, { id: "copy-link", textValue: "复制链接" }, () => h(Label, () => "复制链接"), ), h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "share", textValue: "分享" }, () => [ h(Label, () => "分享"), h(DropdownSubmenuIndicator), ]), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h( DropdownItem, { id: "whatsapp", textValue: "WhatsApp" }, () => h(Label, () => "WhatsApp"), ), ), ), ]), ]), ), ]), ); } function escapeKey(node: Element) { return node.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); } async function settle() { await flushPromises(); await nextTick(); await new Promise((resolve) => setTimeout(resolve, 30)); await flushPromises(); } async function openSubmenu() { const subTrigger = document.querySelector( '[data-slot="menu-item"][data-has-submenu="true"]', ) as HTMLElement; expect(subTrigger).toBeTruthy(); subTrigger.click(); await flushPromises(); await nextTick(); const subContent = document.querySelector( "[data-submenu-content]", ) as HTMLElement; expect(subContent).toBeTruthy(); return { subTrigger, subContent }; } it("Escape closes the submenu level first, then the root menu", async () => { mountSubmenu(); await flushPromises(); await nextTick(); const { subTrigger, subContent } = await openSubmenu(); const child = subContent.querySelector( '[data-slot="menu-item"]', ) as HTMLElement; child.focus(); expect(document.activeElement).toBe(child); escapeKey(child); await settle(); expect(document.querySelector("[data-submenu-content]")).toBeNull(); expect( document.querySelectorAll('[data-slot="dropdown-popover"]').length, ).toBe(1); expect(document.activeElement).toBe(subTrigger); escapeKey(subTrigger); await settle(); expect(document.querySelector('[data-slot="dropdown-popover"]')).toBeNull(); }); it("Escape on a pointer-opened submenu trigger closes only that level", async () => { mountSubmenu(); await flushPromises(); await nextTick(); const { subTrigger } = await openSubmenu(); // Pointer opening leaves focus on the trigger, outside the sub content. subTrigger.focus(); expect(document.activeElement).toBe(subTrigger); escapeKey(subTrigger); await settle(); expect(document.querySelector("[data-submenu-content]")).toBeNull(); expect( document.querySelectorAll('[data-slot="dropdown-popover"]').length, ).toBe(1); expect(document.activeElement).toBe(subTrigger); escapeKey(subTrigger); await settle(); expect(document.querySelector('[data-slot="dropdown-popover"]')).toBeNull(); }); it("keyboard activation on a focused item fires the action once", async () => { const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () => h(Label, () => "新建文件"), ), ), ), ]), ); await flushPromises(); await nextTick(); const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; item.focus(); expect(document.activeElement).toBe(item); item.dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, }), ); await flushPromises(); await nextTick(); expect(actions).toEqual(["new-file"]); }); it("keyboard activation is cancelled when the item click is prevented", async () => { const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h( DropdownItem, { id: "new-file", textValue: "新建文件", onClick: (e: MouseEvent) => e.preventDefault(), }, () => h(Label, () => "新建文件"), ), ), ), ]), ); await flushPromises(); await nextTick(); const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; item.focus(); item.dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, }), ); await flushPromises(); await nextTick(); expect(actions).toEqual([]); expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); }); it("the 17 baseline previews all mount without console warnings", async () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const error = vi.spyOn(console, "error").mockImplementation(() => {}); const demos = import.meta.glob("../apps/docs/demos/dropdown-*.vue", { eager: true, import: "default", }); const names = Object.keys(demos).map((path) => path.replace("../apps/docs/demos/", "").replace(".vue", ""), ); expect(names).toHaveLength(17); try { for (const name of names) { const w = mount(demos[`../apps/docs/demos/${name}.vue`] as never, { attachTo: document.body, }); await flushPromises(); w.unmount(); await flushPromises(); } expect(error.mock.calls).toEqual([]); expect(warn.mock.calls).toEqual([]); } finally { warn.mockRestore(); error.mockRestore(); document.body.innerHTML = ""; } }); it("menu items expose DOM ids and a single role=menu per popup", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => [ h(DropdownItem, { id: "first", textValue: "一" }, () => h(Label, () => "一"), ), h(DropdownItem, { id: "second", textValue: "二" }, () => h(Label, () => "二"), ), ]), ), ]), ); await flushPromises(); await nextTick(); const items = Array.from( document.querySelectorAll('[data-slot="menu-item"]'), ); // Business keys stay out of the DOM; each instance gets its own id. expect(new Set(items.map((item) => item.id)).size).toBe(items.length); expect(items.map((item) => item.getAttribute("data-key"))).toEqual([ "first", "second", ]); expect(document.querySelectorAll('[role="menu"]')).toHaveLength(1); }); it("disabled items match the ported CSS presence selector", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, { disabledKeys: ["x"] }, () => h(DropdownItem, { id: "x", textValue: "X" }, () => h(Label, () => "X"), ), ), ), ]), ); await flushPromises(); await nextTick(); const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; // `menu-item.css` styles `&[data-disabled]`, so presence is the contract. expect(item.matches("[data-disabled]")).toBe(true); }); it("submenu surface keeps a resolvable accessible name", async () => { mountSubmenu(); await flushPromises(); await nextTick(); const { subContent } = await openSubmenu(); await flushPromises(); const labelledBy = subContent.getAttribute("aria-labelledby"); expect(labelledBy).toBeTruthy(); expect(document.getElementById(labelledBy as string)).not.toBeNull(); }); it("Section names its group from a nested Header", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownSection, {}, () => [ h(Header, {}, () => "操作"), h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ]), ), ), ]), ); await flushPromises(); await nextTick(); const section = document.querySelector( '[data-slot="menu-section"]', ) as HTMLElement; const labelledBy = section.getAttribute("aria-labelledby"); expect(labelledBy).toBeTruthy(); const header = document.getElementById(labelledBy as string); expect(header?.textContent).toBe("操作"); }); it("a non-button custom trigger stays keyboard focusable", async () => { mountApp( () => () => h(DropdownRoot, {}, () => [ h(DropdownTrigger, {}, () => h(Avatar, {}, () => h(AvatarFallback, {}, () => "JD")), ), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ), ), ]), ); await flushPromises(); await nextTick(); const trigger = document.querySelector( '[data-slot="dropdown-trigger"]', ) as HTMLElement; expect(trigger.tagName).toBe("SPAN"); expect(trigger.getAttribute("role")).toBe("button"); expect(trigger.getAttribute("tabindex")).toBe("0"); }); it("item and indicator slots expose the upstream render state", async () => { const seen: Record[] = []; const indicatorState: Record[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h( DropdownMenu, { selectionMode: "single", selectedKeys: ["a"] }, { default: () => h( DropdownItem, { id: "a", textValue: "A" }, { default: (state: Record) => { seen.push(state); return [ h( DropdownItemIndicator, {}, { default: (indicator: Record) => { indicatorState.push(indicator); return null; }, }, ), h(Label, () => "A"), ]; }, }, ), }, ), ), ]), ); await flushPromises(); await nextTick(); expect(seen[0]).toMatchObject({ isSelected: true, isDisabled: false, isPressed: false, }); expect(seen[0]).toHaveProperty("isFocused"); expect(indicatorState[0]).toMatchObject({ isSelected: true, isIndeterminate: false, }); }); it("caller classes merge with tailwind-variants semantics", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "a", textValue: "A", class: "p-0" }, () => h(Label, () => "A"), ), ), ), ]), ); await flushPromises(); await nextTick(); const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; expect(item.className).toContain("hv-menu-item"); expect(item.className).toContain("p-0"); }); it("pressing the submenu trigger without an indicator still treats it as a submenu", async () => { const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h( DropdownMenu, { onAction: (key: MenuKey) => actions.push(key) }, () => h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "more", textValue: "更多" }, () => h(Label, () => "更多"), ), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "child", textValue: "子项" }, () => h(Label, () => "子项"), ), ), ), ]), ), ), ]), ); await flushPromises(); await nextTick(); const trigger = document.querySelector( '[data-slot="menu-item"][data-has-submenu="true"]', ) as HTMLElement; expect(trigger).not.toBeNull(); trigger.click(); await flushPromises(); await nextTick(); // A submenu trigger must not fire the menu action nor close the root menu. expect(actions).toEqual([]); expect(document.querySelector("[data-submenu-content]")).not.toBeNull(); expect( document.querySelectorAll('[data-slot="dropdown-popover"]').length, ).toBeGreaterThan(1); }); it("menu capability props are honoured", async () => { const close = vi.fn(); const selections: MenuKey[][] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h( DropdownMenu, { selectionMode: "multiple", selectedKeys: ["a"], disallowEmptySelection: true, escapeKeyBehavior: "clearSelection", shouldFocusWrap: true, autoFocus: false, onClose: close, "onUpdate:selectedKeys": (keys: MenuKey[]) => selections.push(keys), }, () => h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ), ), ]), ); await flushPromises(); await nextTick(); const menu = document.querySelector('[role="menu"]') as HTMLElement; const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; // disallowEmptySelection keeps the last key. item.click(); await flushPromises(); expect(selections).toEqual([]); // escapeKeyBehavior clears the selection instead of closing. menu.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(selections).toEqual([]); expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); // close fires when the level actually closes. menu.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); await flushPromises(); }); it("link items render an anchor and keep navigation semantics", async () => { const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h( DropdownMenu, { onAction: (key: MenuKey) => actions.push(key) }, () => h( DropdownItem, { id: "link", href: "/target", target: "_blank", rel: "noopener", }, () => h(Label, () => "Go"), ), ), ), ]), ); await flushPromises(); await nextTick(); const link = document.querySelector('[data-slot="menu-item"]') as HTMLElement; expect(link.tagName).toBe("A"); expect(link.getAttribute("href")).toBe("/target"); expect(link.getAttribute("target")).toBe("_blank"); expect(link.getAttribute("rel")).toBe("noopener"); expect(link.getAttribute("role")).toBe("menuitem"); link.click(); await flushPromises(); expect(actions).toEqual(["link"]); }); it("disabled link items do not navigate", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h( DropdownItem, { id: "link", href: "/target", isDisabled: true }, () => h(Label, () => "Go"), ), ), ), ]), ); await flushPromises(); await nextTick(); const link = document.querySelector('[data-slot="menu-item"]') as HTMLElement; const event = new MouseEvent("click", { bubbles: true, cancelable: true }); link.dispatchEvent(event); expect(event.defaultPrevented).toBe(true); }); it("empty slot renders when the menu has no items", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h( DropdownMenu, {}, { empty: () => h("p", { "data-test": "empty" }, "无结果"), }, ), ), ]), ); await flushPromises(); await nextTick(); expect(document.querySelector('[data-test="empty"]')).not.toBeNull(); }); it("submenu panel receives panel props and keeps caller handlers", async () => { const keydown = vi.fn(); mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "sub", textValue: "S" }, () => [ h(Label, () => "S"), h(DropdownSubmenuIndicator), ]), h( DropdownPopover, { sideOffset: 12, collisionPadding: 20, class: "panel-x", onKeydown: keydown, }, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "inner", textValue: "I" }, () => h(Label, () => "I"), ), ), ), ]), ), ), ]), ); await flushPromises(); await nextTick(); (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); await flushPromises(); await nextTick(); const panel = document.querySelector("[data-submenu-content]") as HTMLElement; expect(panel.className).toContain("panel-x"); // Portal keeps the panel outside the clipping ancestor. expect(panel.closest('[data-slot="dropdown-popover"]')).toBe(panel); panel.dispatchEvent( new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }), ); await flushPromises(); expect(keydown).toHaveBeenCalledTimes(1); }); it("dropdown popover is portaled out of clipping ancestors", async () => { const host = document.createElement("div"); host.style.overflow = "hidden"; host.style.isolation = "isolate"; document.body.append(host); const w = mount( defineComponent({ setup: () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ), ), ]), }), { attachTo: host }, ); cleanup.push(() => w.unmount()); await flushPromises(); await nextTick(); const popover = document.querySelector( '[data-slot="dropdown-popover"]', ) as HTMLElement; expect(popover).not.toBeNull(); expect(host.contains(popover)).toBe(false); expect(popover.closest("[data-reka-popper-content-wrapper]")).toBe( popover.parentElement, ); }); it("standalone Menu stays in flow without modal side effects", async () => { const outside = document.createElement("button"); document.body.append(outside); const w = mount(Menu, { slots: { default: () => h(MenuItem, { id: "x" }, () => "X") }, attachTo: document.body, }); cleanup.push(() => w.unmount()); await flushPromises(); await nextTick(); const surface = document.querySelector( "[data-reka-menu-content]", ) as HTMLElement; expect(surface.getAttribute("data-static")).toBe("true"); expect(document.body.style.overflow).not.toBe("hidden"); expect(outside.getAttribute("aria-hidden")).not.toBe("true"); // Focus is not stolen from the page. expect(document.activeElement).not.toBe(surface); }); it("root popover merges caller handlers for escape, outside, focus and animation", async () => { const calls = { focus: 0, escape: 0, outside: 0, animation: 0, keydown: 0 }; mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h( DropdownPopover, { onOpenAutoFocus: () => { calls.focus += 1; }, onEscapeKeyDown: () => { calls.escape += 1; }, onInteractOutside: () => { calls.outside += 1; }, onAnimationend: () => { calls.animation += 1; }, onKeydown: () => { calls.keydown += 1; }, }, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ), ), ]), ); await flushPromises(); await nextTick(); const menu = document.querySelector('[role="menu"]') as HTMLElement; menu.dispatchEvent( new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }), ); menu.dispatchEvent(new Event("animationend", { bubbles: true })); await flushPromises(); expect(calls.keydown).toBe(1); expect(calls.animation).toBe(1); expect(calls.focus).toBe(1); }); it("a cancelled caller keydown keeps the menu open for clearSelection menus", async () => { const selections: MenuKey[][] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h( DropdownPopover, { onKeydown: (event: KeyboardEvent) => { if (event.key === "Escape") event.preventDefault(); }, }, () => h( DropdownMenu, { selectionMode: "multiple", selectedKeys: ["a"], escapeKeyBehavior: "clearSelection", "onUpdate:selectedKeys": (keys: MenuKey[]) => selections.push(keys), }, () => h(DropdownItem, { id: "a", textValue: "A" }, () => h(Label, () => "A"), ), ), ), ]), ); await flushPromises(); await nextTick(); const menu = document.querySelector('[role="menu"]') as HTMLElement; menu.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); // The caller cancelled the escape, so the internal clear did not run. expect(selections).toEqual([]); expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); }); it("submenu keyboard dismissal can be disabled without closing the parent", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h(DropdownMenu, {}, () => h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "sub", textValue: "S" }, () => [ h(Label, () => "S"), h(DropdownSubmenuIndicator), ]), h(DropdownPopover, { isKeyboardDismissDisabled: true }, () => h(DropdownMenu, {}, () => h(DropdownItem, { id: "inner", textValue: "I" }, () => h(Label, () => "I"), ), ), ), ]), ), ), ]), ); await flushPromises(); await nextTick(); (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); await flushPromises(); await nextTick(); const panel = document.querySelector("[data-submenu-content]") as HTMLElement; const item = panel.querySelector('[data-slot="menu-item"]') as HTMLElement; item.focus(); item.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await settle(); expect(document.querySelector("[data-submenu-content]")).not.toBeNull(); expect( document.querySelectorAll('[data-slot="dropdown-popover"]').length, ).toBeGreaterThan(1); }); it("menu-level close policy wins over the section mode default", async () => { mountApp( () => () => h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ h(DropdownPopover, {}, () => h(DropdownMenu, { shouldCloseOnSelect: false }, () => h(DropdownSection, { selectionMode: "single" }, () => h(DropdownItem, { id: "s", textValue: "S" }, () => h(Label, () => "S"), ), ), ), ), ]), ); await flushPromises(); await nextTick(); (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); await flushPromises(); await nextTick(); expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); });