26 lines
1.3 KiB
TypeScript
26 lines
1.3 KiB
TypeScript
import { effect, h } from '@ui-arch/frame';
|
|
import type { SwitchProps } from './types.js';
|
|
|
|
/*** 开关:checked 信号双向绑定,disabled 支持布尔或信号禁用,轨道 + 滑块的纯 CSS 实现 ***/
|
|
export function switchButton(props: SwitchProps): HTMLElement {
|
|
const input = h('input', {
|
|
type: 'checkbox',
|
|
class: 'ua-switch-input',
|
|
role: 'switch', // 用开关语义而非复选框:读屏播报「开关」并跟随选中态
|
|
'aria-label': props.ariaLabel ?? props.label, // 无可见文案时也要有可访问名
|
|
disabled: props.disabled, // false/undefined 移除属性,Signal 走响应式
|
|
}) as HTMLInputElement;
|
|
if (props.checked) {
|
|
const checked = props.checked;
|
|
input.addEventListener('change', () => checked(input.checked)); // 用户切换写回信号
|
|
effect(() => {
|
|
if (input.checked !== checked()) input.checked = checked(); // 外部变化写回开关
|
|
});
|
|
}
|
|
if (props.onChange) input.addEventListener('change', () => props.onChange!(input.checked));
|
|
const track = h('span', { class: 'ua-switch-track' }, h('span', { class: 'ua-switch-thumb' }));
|
|
const el = h('label', { class: 'ua-switch' }, input, track);
|
|
if (props.label) el.append(h('span', { class: 'ua-switch-label' }, props.label));
|
|
return el;
|
|
}
|