Files
UI/packages/skin/ui/src/menu.ts
T
2026-10-23 17:06:17 +08:00

84 lines
3.0 KiB
TypeScript

import { effect, h, signal } from '@ui-arch/frame';
import type { MenuItem, MenuProps } from './types.js';
/*** 下拉菜单:触发器 + 自绘弹层,项支持禁用 / 危险 / 分隔线;点项 / 点外部 / Esc 关闭,↑↓ 环形导航 ***/
export function menu(props: MenuProps): HTMLElement {
// —— 状态集中声明 ——
const open = signal(false); // 弹层开合
const focusables: HTMLButtonElement[] = []; // 可聚焦项(跳过分隔线与禁用项),供键盘导航
const pick = (item: MenuItem): void => {
open(false); // 选中即收起
props.onSelect?.(item.value);
};
// —— 菜单项:分隔线走独立分支,其余为原生 button 保证键盘可达 ——
const rows = props.items.map((item) => {
if (item.divider) return h('div', { class: 'ua-menu-divider', role: 'separator' });
const btn = h(
'button',
{
type: 'button',
class: `ua-menu-item${item.danger ? ' is-danger' : ''}`,
role: 'menuitem',
disabled: item.disabled ? true : undefined,
onClick: () => pick(item),
},
h('span', { class: 'ua-menu-label' }, item.label),
item.shortcut ? h('kbd', { class: 'ua-menu-key' }, item.shortcut) : null, // 快捷键只做提示,不拦截按键
) as HTMLButtonElement;
if (!item.disabled) focusables.push(btn); // 禁用项不参与导航
return btn;
});
const trigger = h(
'button',
{
type: 'button',
class: `ua-btn ua-btn-${props.variant ?? 'ghost'} ua-menu-trigger`,
'aria-haspopup': 'menu',
'aria-expanded': () => String(open()),
onClick: () => open(!open()),
},
props.label,
h('span', { class: 'ua-menu-caret' }, '▾'),
);
const pop = h(
'div',
{
class: () => `ua-menu-pop${open() ? ' ua-open' : ''}${props.align === 'end' ? ' is-end' : ''}`,
role: 'menu',
},
...rows,
);
const root = h('div', { class: () => `ua-menu${open() ? ' ua-open' : ''}` }, trigger, pop);
root.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
open(false);
trigger.focus(); // 收起后焦点回到触发器,键盘流不断
return;
}
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return; // 卫语句:只接管上下键
e.preventDefault();
if (!open()) {
open(true);
focusables[0]?.focus(); // 首次按下即展开并进首项
return;
}
const at = focusables.indexOf(document.activeElement as HTMLButtonElement);
const step = e.key === 'ArrowDown' ? 1 : -1;
focusables[(at + step + focusables.length) % focusables.length]?.focus(); // 环形移动
});
document.addEventListener('click', (e) => {
if (root.contains(e.target as Node)) return; // 卫语句:组件内点击不处理
open(false); // 点外部收起
});
effect(() => open()); // 建立依赖,保证开合信号生效
return root;
}