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); }; // 写回信号并回调 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), }, '★')); } return h('div', { class: 'ua-rate', role: 'slider', 'aria-label': '评分', 'aria-valuemin': 1, 'aria-valuemax': max, 'aria-valuenow': value(), onMouseLeave: () => hover(0) }, ...stars); }; 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); return el as HTMLDivElement; }