Created
January 15, 2025 07:25
-
-
Save orefalo/0ee91702bcce38f144415bd4a209cb5b to your computer and use it in GitHub Desktop.
shadcn-svelte TextareaAutosize.svelte
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import type { WithElementRef, WithoutChildren } from 'bits-ui'; | |
import type { HTMLTextareaAttributes } from 'svelte/elements'; | |
import { Textarea } from '$lib/components/ui/textarea/index.js'; | |
import { cn } from '$lib/utils.js'; | |
import { nanoid } from '$lib/nanoid'; | |
let { | |
value = $bindable(), | |
class: className, | |
...restProps | |
}: WithoutChildren<WithElementRef<HTMLTextareaAttributes>> = $props(); | |
let height: number = $state(0); | |
const mirrorId = nanoid(); | |
const scrollTolerance = 15; | |
$effect(() => { | |
//IMPORTANT: Do nor remove, or reactivity will not trigger | |
value; | |
const clientHeight = document?.getElementById(mirrorId)?.clientHeight ?? 0; | |
height = clientHeight + scrollTolerance; | |
}); | |
</script> | |
<div class="relative w-full"> | |
<Textarea | |
bind:value | |
class={cn('overflow-hidden', className)} | |
style={`height: ${height}px`} | |
{...restProps} /> | |
<div id={mirrorId} class={cn('invisible absolute left-0 top-0 whitespace-pre-wrap', className)}> | |
{value} | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment