Collapsible.svelte 798 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
23
24
25
26
27
<div class={className}>
	<button on:click={() => (open = !open)}>
		<slot name="head" />
	</button>
	<div bind:this={contentElement} class="collapsible-content" style="max-height: {maxHeight};">
		<slot name="content" />
	</div>
</div>

28
29
<style>
	.collapsible-content {
30
31
32
		overflow: hidden;
		transition: max-height 0.3s ease-out;
		max-height: 0;
33
34
	}
</style>