Files
UI/packages/skin/ui/src/menu.ts
T

107 lines
4.7 KiB
TypeScript

import { effect, h, signal } from '@ui-arch/frame';
import type { MenuItem, MenuProps } from './types.js';
import { flip } from './position.js';
/*** 下拉菜单:触发器 + 自绘弹层,项支持禁用 / 危险 / 分隔线;点项 / 点外部 / Esc 关闭,↑↓ 环形导航 + Home/End 跳转 + 键入快跳 ***/
export function menu(props: MenuProps): HTMLElement {
// —— 状态集中声明 ——
const open = signal(false); // 弹层开合
const place = signal<'top' | 'bottom'>('bottom'); // 实际生效方位:打开时按视口空间自动翻转
const focusables: HTMLButtonElement[] = []; // 可聚焦项(跳过分隔线与禁用项),供键盘导航
const labels: string[] = []; // 与 focusables 平行的条目文案,供键入快跳
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); labels.push(item.label); } // 禁用项不参与导航
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' : ''}${place() === 'top' ? ' is-flip' : ''}${props.align === 'end' ? ' is-end' : ''}`,
role: 'menu',
},
...rows,
);
const root = h('div', { class: () => `ua-menu${open() ? ' ua-open' : ''}` }, trigger, pop);
// —— 键入快跳缓冲:与 select 的行为保持一致 ——
let typed = ''; // 最近键入的字母串
let typedAt = 0; // 最近键入时间戳,超 1 秒重置
const jumpByTyped = (ch: string): void => {
const now = Date.now();
typed = now - typedAt > 1000 ? ch : typed + ch; // 超时重新起词,否则追加
typedAt = now;
const at = focusables.indexOf(document.activeElement as HTMLButtonElement); // 当前焦点序号
const order = focusables.map((_, i) => (at + 1 + i) % focusables.length); // 从下一项开始环形排列
const hit = order.find((i) => labels[i].toLowerCase().startsWith(typed.toLowerCase())); // 前缀匹配
if (hit != null) focusables[hit]?.focus(); // 命中即聚焦;无命中留在原地
};
root.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation(); // 只关本层:不再冒泡去关外层的弹窗/抽屉
open(false);
trigger.focus(); // 收起后焦点回到触发器,键盘流不断
return;
}
if (e.key === 'Home' && open()) { e.preventDefault(); focusables[0]?.focus(); return; } // Home 跳首项
if (e.key === 'End' && open()) { e.preventDefault(); focusables[focusables.length - 1]?.focus(); return; } // End 跳末项
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') {
if (open() && e.key.length === 1) jumpByTyped(e.key); // 可打印字符:键入快跳
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()); // 建立依赖,保证开合信号生效
effect(() => { if (open()) place(flip(trigger, pop, 'bottom')); }); // 每次打开重算方位:空间不足自动翻转
return root;
}