Files
UI/packages/skin/ui/src/textarea.ts
T
2026-10-27 02:09:25 +08:00

46 lines
3.0 KiB
TypeScript

import { effect, h } from '@ui-arch/frame';
import { addonWrap } from './addons.js';
import type { TextareaProps } from './types.js';
/*** 多行输入:value 信号双向绑定,disabled 支持布尔或信号禁用,onInput 为输入回调;prefix/suffix 包纵向附加组,maxCount 显示字数统计 ***/
export function textarea(props: TextareaProps): HTMLElement {
const el = h('textarea', { class: 'ua-textarea', rows: props.rows ?? 3, placeholder: props.placeholder ?? '', disabled: props.disabled, 'aria-label': props.ariaLabel ?? '多行文本' }) as HTMLTextAreaElement; // false/undefined 移除属性,Signal 走响应式
if (props.value) {
const signal = props.value;
el.addEventListener('input', () => signal(el.value)); // 用户输入写回信号
effect(() => {
if (el.value !== signal()) el.value = signal(); // 外部变化写回输入框
});
}
if (props.onInput) el.addEventListener('input', () => props.onInput!(el.value));
let counter: HTMLElement | null = null; // 字数统计块;maxCount 未传不创建
if (props.maxCount) {
el.setAttribute('maxlength', String(props.maxCount)); // 原生拦截超限输入
counter = h('span', { class: 'ua-textarea-count' });
const syncCount = (): void => { counter!.textContent = `${el.value.length}/${props.maxCount}`; }; // 实时 n/limit
el.addEventListener('input', syncCount); // 用户输入时同步
effect(() => { if (props.value) props.value(); syncCount(); }); // 初始与外部写回时同步(读信号建依赖)
}
const suffix = counter ? h('span', { class: 'ua-textarea-count-group' }, counter, props.suffix ?? null) : props.suffix; // 计数并入下方附加组
if (props.autosize) {
const cfg = props.autosize === true ? {} : props.autosize; // 对象态带行数钳制
const frame = (): void => { // 量高与钳制共用一帧:行高/内距从 computed style 推导,零硬编码
const cs = getComputedStyle(el);
const lh = parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.5; // line-height 为 normal 时按 1.5 倍字号退化
const extra = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth); // 盒模型补偿:scrollHeight 不含边框
if (cfg.minRows) el.style.minHeight = `${lh * cfg.minRows + extra}px`;
if (cfg.maxRows) {
el.style.maxHeight = `${lh * cfg.maxRows + extra}px`;
el.style.overflowY = 'auto'; // 超 maxRows 转内部滚动
}
el.style.height = 'auto'; // 先复位再量,scrollHeight 才是内容真实高度
el.style.height = `${el.scrollHeight}px`;
};
el.style.resize = 'none'; // 高度交给自适应,手动拖拽失去意义
el.addEventListener('input', frame); // 输入即重算
effect(() => { if (props.value) props.value(); frame(); }); // 外部写回信号也重算
frame(); // 初始按当前内容定高
}
return addonWrap(el, props.prefix, suffix, true);
}