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

48 lines
2.3 KiB
TypeScript

import { effect, h, signal } from '@ui-arch/frame';
import type { RateProps } from './types.js';
/*** 评分:星标点选,hover 预览移出还原,键盘 ←→/↑↓ 调节,value 信号双向绑定 ***/
export function rate(props: RateProps): HTMLDivElement {
const value = props.value;
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 = [];
for (let i = 1; i <= max; i++) {
stars.push(h('button', {
class: `ua-rate-star${i <= shown ? ' is-on' : ''}`,
type: 'button',
disabled: props.disabled,
'aria-label': `${i} 星`,
onClick: () => emit(i),
onMouseEnter: () => hover(i),
}, '★'));
}
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) {
const hadFocus = el.contains(document.activeElement); // 重渲染前焦点是否在本组内
el.replaceWith(next);
if (hadFocus) (next as HTMLElement).focus(); // 归还焦点,方向键可继续连按
}
el = next;
}); // value/hover 变化整条重渲染(星标少,开销可忽略)
return el as HTMLDivElement;
}