Drawer.svelte 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <script lang="ts">
  2. import { onDestroy, onMount } from 'svelte';
  3. import { flyAndScale } from '$lib/utils/transitions';
  4. import { fade, fly, slide } from 'svelte/transition';
  5. import { isApp } from '$lib/stores';
  6. export let show = false;
  7. export let className = '';
  8. export let onClose = () => {};
  9. let modalElement = null;
  10. let mounted = false;
  11. const handleKeyDown = (event: KeyboardEvent) => {
  12. if (event.key === 'Escape' && isTopModal()) {
  13. console.log('Escape');
  14. show = false;
  15. }
  16. };
  17. const isTopModal = () => {
  18. const modals = document.getElementsByClassName('modal');
  19. return modals.length && modals[modals.length - 1] === modalElement;
  20. };
  21. onMount(() => {
  22. mounted = true;
  23. });
  24. $: if (show && modalElement) {
  25. document.body.appendChild(modalElement);
  26. window.addEventListener('keydown', handleKeyDown);
  27. document.body.style.overflow = 'hidden';
  28. } else if (modalElement) {
  29. onClose();
  30. window.removeEventListener('keydown', handleKeyDown);
  31. if (document.body.contains(modalElement)) {
  32. document.body.removeChild(modalElement);
  33. document.body.style.overflow = 'unset';
  34. }
  35. }
  36. onDestroy(() => {
  37. show = false;
  38. if (modalElement) {
  39. if (document.body.contains(modalElement)) {
  40. document.body.removeChild(modalElement);
  41. document.body.style.overflow = 'unset';
  42. }
  43. }
  44. });
  45. </script>
  46. <!-- svelte-ignore a11y-click-events-have-key-events -->
  47. <!-- svelte-ignore a11y-no-static-element-interactions -->
  48. <div
  49. bind:this={modalElement}
  50. class="modal fixed right-0 {$isApp
  51. ? ' ml-[4.5rem] max-w-[calc(100%-4.5rem)]'
  52. : ''} left-0 bottom-0 bg-black/60 w-full h-screen max-h-[100dvh] flex justify-center z-999 overflow-hidden overscroll-contain"
  53. in:fly={{ y: 100, duration: 100 }}
  54. on:mousedown={() => {
  55. show = false;
  56. }}
  57. >
  58. <div
  59. class=" mt-auto w-full bg-gray-50 dark:bg-gray-900 dark:text-gray-100 {className} max-h-[100dvh] overflow-y-auto scrollbar-hidden"
  60. on:mousedown={(e) => {
  61. e.stopPropagation();
  62. }}
  63. >
  64. <slot />
  65. </div>
  66. </div>
  67. <style>
  68. .modal-content {
  69. animation: scaleUp 0.1s ease-out forwards;
  70. }
  71. @keyframes scaleUp {
  72. from {
  73. transform: scale(0.985);
  74. opacity: 0;
  75. }
  76. to {
  77. transform: scale(1);
  78. opacity: 1;
  79. }
  80. }
  81. </style>