Collapsible.svelte 820 B

12345678910111213141516171819202122232425262728293031323334
  1. <script lang="ts">
  2. export let open = false;
  3. export let className = '';
  4. // Manage the max-height of the collapsible content for snappy transitions
  5. let contentElement: HTMLElement;
  6. let maxHeight = '0px'; // Initial max-height
  7. $: if (contentElement?.scrollHeight) {
  8. if (open) {
  9. // Ensure the element is visible before measuring
  10. maxHeight = `${contentElement.scrollHeight}px`;
  11. } else {
  12. maxHeight = '0px';
  13. }
  14. }
  15. </script>
  16. <div class={className}>
  17. <button on:click={() => (open = !open)}>
  18. <slot name="head" />
  19. </button>
  20. <div bind:this={contentElement} class={`collapsible-content ${open ? 'mt-1' : '!mt-0'}`} style="max-height: {maxHeight};">
  21. <slot name="content" />
  22. </div>
  23. </div>
  24. <style>
  25. .collapsible-content {
  26. overflow: hidden;
  27. transition: all 0.3s ease-out;
  28. max-height: 0;
  29. }
  30. </style>