diff --git a/packages/skin/ui/src/rate.ts b/packages/skin/ui/src/rate.ts index 5619af6..6cbcfa7 100644 --- a/packages/skin/ui/src/rate.ts +++ b/packages/skin/ui/src/rate.ts @@ -7,6 +7,14 @@ export function rate(props: RateProps): HTMLDivElement { const max = props.max ?? 5; // 星标总数缺省 5 const hover = signal(0); // 预览索引(1 基,0 表示无预览) const emit = (v: number): void => { const n = Math.min(max, Math.max(1, v)); value(n); if (props.onChange) props.onChange(n); }; // 写回信号并回调 + + /*** 键盘调节:focus 在整组上,方向键步进一分(重渲染后仍生效) ***/ + const keyNav = (e: KeyboardEvent): void => { + if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; // 卫语句:只拦截方向键 + e.preventDefault(); + emit(value() + (e.key === 'ArrowRight' || e.key === 'ArrowUp' ? 1 : -1)); // →/↑ 加一分,←/↓ 减一分 + }; + const render = (): HTMLElement => { const shown = hover() || value(); // 预览优先,无预览显示当前值 const stars = []; @@ -20,15 +28,20 @@ export function rate(props: RateProps): HTMLDivElement { onMouseEnter: () => hover(i), }, '★')); } - return h('div', { class: 'ua-rate', role: 'slider', 'aria-label': '评分', 'aria-valuemin': 1, 'aria-valuemax': max, 'aria-valuenow': value(), onMouseLeave: () => hover(0) }, ...stars); + const node = h('div', { class: 'ua-rate', role: 'slider', tabindex: '0', 'aria-label': '评分', 'aria-valuemin': 1, 'aria-valuemax': max, 'aria-valuenow': value(), onMouseLeave: () => hover(0) }, ...stars) as HTMLDivElement; + node.addEventListener('keydown', keyNav); // 每次渲染都挂:节点被替换后键盘仍可用 + return node; }; + let el!: HTMLElement; // 当前渲染产物(effect 首跑赋值) - effect(() => { const next = render(); if (el) el.replaceWith(next); el = next; }); // value/hover 变化整条重渲染(星标少,开销可忽略) - const keyNav = (e: KeyboardEvent): void => { - if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; // 卫语句:只拦截方向键 - e.preventDefault(); - emit(value() + (e.key === 'ArrowRight' || e.key === 'ArrowUp' ? 1 : -1)); // →/↑ 加一分,←/↓ 减一分 - }; - el.addEventListener('keydown', keyNav); + effect(() => { + const next = render(); + if (el) { + const hadFocus = el.contains(document.activeElement); // 重渲染前焦点是否在本组内 + el.replaceWith(next); + if (hadFocus) (next as HTMLElement).focus(); // 归还焦点,方向键可继续连按 + } + el = next; + }); // value/hover 变化整条重渲染(星标少,开销可忽略) return el as HTMLDivElement; } diff --git a/packages/skin/ui/ui.css b/packages/skin/ui/ui.css index a94ef95..cfa832e 100644 --- a/packages/skin/ui/ui.css +++ b/packages/skin/ui/ui.css @@ -898,6 +898,11 @@ button.ua-step-dot:hover { display: inline-flex; gap: 2px; } +.ua-rate:focus-visible { + outline: 2px solid color-mix(in srgb, var(--ua-color-accent) 45%, transparent); + outline-offset: 3px; + border-radius: var(--ua-radius-sm); +} .ua-rate-star { padding: 0; border: none;