Skip to content

Instantly share code, notes, and snippets.

@orefalo
Created January 15, 2025 07:25
Show Gist options
  • Save orefalo/0ee91702bcce38f144415bd4a209cb5b to your computer and use it in GitHub Desktop.
Save orefalo/0ee91702bcce38f144415bd4a209cb5b to your computer and use it in GitHub Desktop.
shadcn-svelte TextareaAutosize.svelte
<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}&nbsp;
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment