Collapsible.svelte 828 Bytes
Newer Older
1
2
<script lang="ts">
	export let open = false;
3
	export let className = '';
4
5
6

	// Manage the max-height of the collapsible content for snappy transitions
	let contentElement: HTMLElement;
7
	let maxHeight = '0px'; // Initial max-height
rdavis's avatar
rdavis committed
8
9

	$: if (contentElement?.scrollHeight) {
10
11
12
13
14
15
		if (open) {
			// Ensure the element is visible before measuring
			maxHeight = `${contentElement.scrollHeight}px`;
		} else {
			maxHeight = '0px';
		}
rdavis's avatar
rdavis committed
16
	}
17
18
</script>

19
20
21
22
<div class={className}>
	<button on:click={() => (open = !open)}>
		<slot name="head" />
	</button>
rdavis's avatar
rdavis committed
23
24
25
26
27
	<div
		bind:this={contentElement}
		class={`collapsible-content ${open ? 'mt-1' : '!mt-0'}`}
		style="max-height: {maxHeight};"
	>
28
29
30
31
		<slot name="content" />
	</div>
</div>

32
33
<style>
	.collapsible-content {
34
		overflow: hidden;
35
		transition: all 0.3s ease-out;
36
		max-height: 0;
37
38
	}
</style>