import { effect, h } from '@ui-arch/frame'; import { spinner } from './spinner.js'; import type { LoadingProps } from './types.js'; // 缺省延迟:120ms 内的请求不闪遮罩,否则「点了就闪一下」比不显示更闹 const DELAY = 120; /*** 区域加载遮罩:包住一块内容,active 为真时盖上层遮罩 + 转圈 + 文案;带延迟出场,快请求不闪、慢请求必有反馈 ***/ export function loading(props: LoadingProps, ...children: unknown[]): HTMLElement { const delay = props.delay ?? DELAY; // 延迟毫秒 let timer = 0; // 延迟计时器 const read = (): boolean => (typeof props.active === 'function' ? Boolean(props.active()) : props.active === true); // 布尔与信号同一口径 const mask = h( 'div', { class: 'ua-loading-mask' }, spinner({ size: props.spinnerSize ?? 20, label: props.text ?? '内容加载中' }), // 转圈自带 role=status,这里只用它的可访问名 props.text ? h('span', { class: 'ua-loading-text' }, props.text) : null, ); const wrap = h( 'div', { class: 'ua-loading' }, h('div', { class: 'ua-loading-body' }, ...children), // 内容层:遮罩出现时整体降透明度,但仍留在原位不塌陷 mask, ); if (props.minHeight !== undefined) wrap.style.minHeight = `${props.minHeight}px`; // 内容为空时也要撑出高度,遮罩才盖得住 /*** 状态落点:is-active 控制遮罩显隐,aria-busy 让读屏知道这块在等数据 ***/ const paint = (on: boolean): void => { wrap.classList.toggle('is-active', on); wrap.setAttribute('aria-busy', String(on)); }; effect(() => { window.clearTimeout(timer); if (!read()) { paint(false); return; } // 关得快:立刻收,不等延迟 timer = window.setTimeout(() => paint(true), delay); // 开得慢:先等一会儿,避免快速请求闪一下 }); paint(read()); // 首帧:初值为真时直接亮(延迟只管后续变化) return wrap; }