fix: textarea auto height issue

This commit is contained in:
Timothy Jaeryang Baek 2024-11-23 23:10:12 -08:00
parent f5bda4bc27
commit c465a37597

View File

@ -3,30 +3,27 @@
export let value = ''; export let value = '';
export let placeholder = ''; export let placeholder = '';
export let rows = 1; export let rows = 1;
export let required = false; export let required = false;
export let className = export let className =
'w-full rounded-lg px-3 py-2 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-none resize-none h-full'; 'w-full rounded-lg px-3 py-2 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-none resize-none h-full';
let textareaElement; let textareaElement;
// Adjust height on mount and after setting the element.
onMount(async () => { onMount(async () => {
await tick(); await tick();
if (textareaElement) { adjustHeight();
await tick();
setTimeout(adjustHeight, 0);
}
}); });
$: if (value) { // This reactive statement runs whenever `value` changes
setTimeout(adjustHeight, 0); $: adjustHeight();
}
// Adjust height to match content
const adjustHeight = () => { const adjustHeight = () => {
if (textareaElement) { if (textareaElement) {
textareaElement.style.height = ''; // Reset height to calculate the correct scroll height
textareaElement.style.height = 'auto';
textareaElement.style.height = `${textareaElement.scrollHeight}px`; textareaElement.style.height = `${textareaElement.scrollHeight}px`;
} }
}; };
@ -37,7 +34,6 @@
bind:value bind:value
{placeholder} {placeholder}
on:input={adjustHeight} on:input={adjustHeight}
on:focus={adjustHeight}
class={className} class={className}
{rows} {rows}
{required} {required}