Files
heroui-vue/packages/vue/src/components/menu-item/MenuItem.vue
T
maoyingjie 53b4639b0e fix: portal dropdown surfaces and close the review capability gaps
- Root and submenu surfaces render through the dropdown portal with the overlay
  z-index, so clipping/isolation ancestors no longer cut the menu; panel height
  is capped by the floating available height and the animation origin maps the
  real transform origin.
- Standalone Menu is a static in-flow list: no scroll lock, no outside pointer
  blocking, no floating placement and no focus stealing.
- Selection ownership is isolated per level: section disabled keys add to the
  menu list, and a nested Menu resets the section owner.
- closeOnSelect resolves item > menu policy > per-mode default for selection
  items; actions and radio items close, checkboxes stay open.
- Business keys no longer become DOM ids (instance ids + data-key), and submenu
  surfaces label themselves from the real trigger.
- Long-press keydown runs the caller's handlers first and only opens when not
  cancelled; submenu panels merge caller keydown with the internal Escape.
- Link items render a real anchor, aria labels land on the role=menu node,
  submenu panels forward placement/offset/collision props and caller attrs, and
  the popover provides the default Surface variant.
- Wrapper parts declare real props/emits, plus the missing official capability
  props (disallowEmptySelection, escapeKeyBehavior, shouldFocusWrap, autoFocus,
  shouldCloseOnSelect, close, empty slot, isKeyboardDismissDisabled,
  shouldCloseOnInteractOutside, placement/offset family, scoped slots).
- Ship an independent consumer fixture for browser-level verification.
2026-10-24 22:56:44 +08:00

284 lines
9.2 KiB
Vue

<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
onMounted,
onUnmounted,
provide,
ref,
useAttrs,
useId,
type PropType,
} from "vue";
import { DropdownMenuItem as RekaMenuItem } from "reka-ui";
import { menuItemVariants, type MenuItemVariants } from "@heroui-vue/styles";
import {
menuContextKey,
menuItemContextKey,
menuSectionContextKey,
type MenuKey,
} from "../menu/context";
type NativeClickHandler =
((e: MouseEvent) => void) | ((e: MouseEvent) => void)[] | undefined;
type NativeHandler<Ev> = ((e: Ev) => void) | ((e: Ev) => void)[] | undefined;
const LINK_ATTRS = [
"href",
"target",
"rel",
"download",
"hrefLang",
"referrerPolicy",
] as const;
export default defineComponent({
name: "MenuItem",
inheritAttrs: false,
props: {
/** Business key used by selection and actions. Never becomes a DOM id. */
id: { type: [String, Number] as PropType<MenuKey>, default: undefined },
textValue: { type: String, default: undefined },
isDisabled: { type: Boolean, default: false },
disabled: { type: Boolean, default: undefined },
variant: {
type: String as PropType<MenuItemVariants["variant"]>,
default: "default",
},
/** Explicit close policy for this item (official `shouldCloseOnSelect`). */
closeOnSelect: { type: Boolean, default: undefined },
/**
* Render this item as a submenu trigger. `DropdownSubmenuTrigger` sets it
* so the item no longer depends on a rendered indicator to know it has a
* submenu (upstream derives it from the collection structure).
*/
hasSubmenu: { type: Boolean, default: undefined },
/** Render a link menu item instead of a button-like item. */
href: { type: String, default: undefined },
target: { type: String, default: undefined },
rel: { type: String, default: undefined },
download: {
type: [String, Boolean] as PropType<string | boolean>,
default: undefined,
},
hrefLang: { type: String, default: undefined },
referrerPolicy: { type: String, default: undefined },
},
emits: {
select: (_key: MenuKey) => true,
},
setup(props, { slots, emit }) {
const attrs = useAttrs();
const menuCtx = inject(menuContextKey, null);
const sectionCtx = inject(menuSectionContextKey, null);
const owner = sectionCtx?.selection ?? menuCtx?.selection;
const indicatorSubmenu = ref(false);
const isFocused = ref(false);
const isHovered = ref(false);
const isPressed = ref(false);
const domId = useId();
const key = computed<MenuKey>(
() => props.id ?? (attrs.id as MenuKey | undefined) ?? "",
);
const hasSubmenu = computed(
() => props.hasSubmenu ?? indicatorSubmenu.value,
);
const isDisabled = computed(
() =>
props.isDisabled ||
props.disabled === true ||
(owner?.isItemDisabled(key.value) ?? false),
);
const isSelected = computed(
() => owner?.isItemSelected(key.value) ?? false,
);
const selectionMode = computed(() => owner?.selectionMode.value ?? "none");
const slotsComputed = computed(() =>
menuItemVariants({ variant: props.variant as never }),
);
const role = computed(() => {
if (selectionMode.value === "multiple") return "menuitemcheckbox";
if (selectionMode.value === "single") return "menuitemradio";
return "menuitem";
});
const linkProps = computed(() => {
if (!props.href) return null;
const out: Record<string, unknown> = { as: "a", href: props.href };
for (const name of LINK_ATTRS) {
if (name === "href") continue;
if (props[name] !== undefined) out[name] = props[name];
}
return out;
});
provide(menuItemContextKey, {
slots: slotsComputed,
isDisabled,
isSelected,
isFocused,
isPressed,
hasSubmenu,
setHasSubmenu(value: boolean) {
indicatorSubmenu.value = value;
},
});
let unregister: (() => void) | undefined;
onMounted(() => {
unregister = menuCtx?.registerItem();
});
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
function shouldClose() {
if (props.closeOnSelect !== undefined) return props.closeOnSelect;
const menuPolicy = menuCtx?.shouldCloseOnSelect.value;
if (typeof menuPolicy === "function") return menuPolicy(key.value);
// Default per mode: action and radio items close, checkboxes stay open.
if (selectionMode.value !== "none")
return selectionMode.value === "single";
return menuPolicy ?? true;
}
function activate() {
if (isDisabled.value) return;
emit("select", key.value);
if (hasSubmenu.value) return;
const mode = selectionMode.value;
if (mode !== "none") {
owner?.proposeSelection(key.value);
if (shouldClose()) menuCtx?.closeLevel();
return;
}
menuCtx?.emitAction(key.value);
if (shouldClose()) menuCtx?.closeLevel();
}
/** Keep the caller's own handler(s) in front of the internal tracker. */
function withOwn<Ev extends Event>(
name: string,
own: (event: Ev) => void,
): NativeHandler<Ev> {
const user = (attrs as Record<string, NativeHandler<Ev>>)[name];
if (!user) return own;
return Array.isArray(user) ? [...user, own] : [user, own];
}
return () => {
// Hand the user handlers and our activation to Vue as one DOM `onClick`
// array so browser/Vue listener semantics stay intact: capture order,
// preventDefault and stopImmediatePropagation all behave natively, and a
// cancelled event never reaches the activation entry. Reka's own
// `handleSelect` is prepended by its prop merge and is neutralised in
// `onSelect`, so it cannot emit an action or close the menu.
const userOnClick = (attrs as { onClick?: NativeClickHandler }).onClick;
const rest: Record<string, unknown> = {
...(attrs as Record<string, unknown>),
};
for (const name of [
"onClick",
"onFocus",
"onBlur",
"onPointerDown",
"onPointerUp",
"onPointerCancel",
"onPointerEnter",
"onPointerLeave",
]) {
delete rest[name];
}
const clickChain: Array<(e: MouseEvent) => void> = (
Array.isArray(userOnClick)
? [...userOnClick]
: userOnClick
? [userOnClick]
: []
) as Array<(e: MouseEvent) => void>;
clickChain.push((event: MouseEvent) => {
if (event.defaultPrevented) return;
if (isDisabled.value) {
// A disabled link must not navigate either.
event.preventDefault();
return;
}
activate();
});
const roleAttr = (attrs.role as string | undefined) ?? role.value;
return h(
RekaMenuItem as never,
{
...rest,
...linkProps.value,
id: domId,
class: slotsComputed.value.item({ class: attrs.class as never }),
role: roleAttr,
"aria-checked":
selectionMode.value === "none"
? undefined
: isSelected.value
? "true"
: "false",
"aria-disabled": isDisabled.value || undefined,
"data-slot": "menu-item",
"data-selected": isSelected.value || undefined,
// RAC's render-state hooks that the ported CSS and the official
// custom-styles demo rely on.
"data-focused": isFocused.value || undefined,
"data-hovered": isHovered.value || undefined,
"data-pressed": isPressed.value || undefined,
"data-has-submenu": hasSubmenu.value || undefined,
"data-selection-mode": selectionMode.value,
"data-key": String(key.value),
disabled: isDisabled.value,
textValue: props.textValue,
onClick: clickChain,
onFocus: withOwn<FocusEvent>("onFocus", () => {
isFocused.value = true;
}),
onBlur: withOwn<FocusEvent>("onBlur", () => {
isFocused.value = false;
isPressed.value = false;
}),
onPointerDown: withOwn<PointerEvent>("onPointerDown", () => {
isPressed.value = true;
}),
onPointerUp: withOwn<PointerEvent>("onPointerUp", () => {
isPressed.value = false;
}),
onPointerCancel: withOwn<PointerEvent>("onPointerCancel", () => {
isPressed.value = false;
}),
onPointerEnter: withOwn<PointerEvent>("onPointerEnter", () => {
isHovered.value = true;
}),
onPointerLeave: withOwn<PointerEvent>("onPointerLeave", () => {
isHovered.value = false;
isPressed.value = false;
}),
onSelect: (itemSelectEvent?: { preventDefault?: () => void }) => {
itemSelectEvent?.preventDefault?.();
},
},
{
default: () =>
slots.default?.({
isSelected: isSelected.value,
isFocused: isFocused.value,
isDisabled: isDisabled.value,
isPressed: isPressed.value,
}),
},
);
};
},
});
</script>