enzostvs's picture
enzostvs HF Staff
Show preview + autosize textarea
c4ae44d
const DEFAULT_MIN_ROWS = 1;
export function autosize(
node: HTMLTextAreaElement,
options?: { minRows?: number; maxRows?: number; value?: string }
) {
const minRows = options?.minRows ?? DEFAULT_MIN_ROWS;
const maxRows = options?.maxRows;
function resize() {
node.style.height = 'auto';
const lineHeight = parseInt(getComputedStyle(node).lineHeight, 10) || 24;
const minHeight = lineHeight * minRows;
let height = Math.max(minHeight, node.scrollHeight);
if (maxRows != null) {
const maxHeight = lineHeight * maxRows;
height = Math.min(height, maxHeight);
node.style.overflowY = height >= maxHeight ? 'auto' : 'hidden';
} else {
node.style.overflowY = '';
}
node.style.height = `${height}px`;
}
node.addEventListener('input', resize);
resize();
return {
update() {
resize();
},
destroy() {
node.removeEventListener('input', resize);
node.style.height = 'auto';
}
};
}