iter(g22): menu 键入字母快跳菜单项
This commit is contained in:
@@ -2,12 +2,13 @@ import { effect, h, signal } from '@ui-arch/frame';
|
||||
import type { MenuItem, MenuProps } from './types.js';
|
||||
import { flip } from './position.js';
|
||||
|
||||
/*** 下拉菜单:触发器 + 自绘弹层,项支持禁用 / 危险 / 分隔线;点项 / 点外部 / Esc 关闭,↑↓ 环形导航 + Home/End 跳转 ***/
|
||||
/*** 下拉菜单:触发器 + 自绘弹层,项支持禁用 / 危险 / 分隔线;点项 / 点外部 / 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); // 选中即收起
|
||||
@@ -29,7 +30,7 @@ export function menu(props: MenuProps): HTMLElement {
|
||||
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); // 禁用项不参与导航
|
||||
if (!item.disabled) { focusables.push(btn); labels.push(item.label); } // 禁用项不参与导航
|
||||
return btn;
|
||||
});
|
||||
|
||||
@@ -57,6 +58,19 @@ export function menu(props: MenuProps): HTMLElement {
|
||||
|
||||
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') {
|
||||
open(false);
|
||||
@@ -65,7 +79,10 @@ export function menu(props: MenuProps): HTMLElement {
|
||||
}
|
||||
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') return; // 卫语句:只接管上下键
|
||||
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') {
|
||||
if (open() && e.key.length === 1) jumpByTyped(e.key); // 可打印字符:键入快跳
|
||||
return; // 卫语句:其余按键不接管
|
||||
}
|
||||
e.preventDefault();
|
||||
if (!open()) {
|
||||
open(true);
|
||||
|
||||
Reference in New Issue
Block a user