Collapsible.svelte 820 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>
23
	<div bind:this={contentElement} class={`collapsible-content ${open ? 'mt-1' : '!mt-0'}`} style="max-height: {maxHeight};">
24
25
26
27
		<slot name="content" />
	</div>
</div>

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