|
| 1 | +import { $, type PropsOf, Slot, component$, useContext, useSignal } from "@qwik.dev/core"; |
| 2 | +import { modalContextId } from "./modal-root"; |
| 3 | + |
| 4 | +export const ModalContent = component$((props: PropsOf<"dialog">) => { |
| 5 | + const context = useContext(modalContextId); |
| 6 | + const isDownOnBackdrop = useSignal(false); |
| 7 | + const descriptionId = `${context.localId}-description`; |
| 8 | + const titleId = `${context.localId}-title`; |
| 9 | + |
| 10 | + /** |
| 11 | + * Determines if the backdrop of the Modal has been clicked. |
| 12 | + */ |
| 13 | + const isBackdropEvent$ = $( |
| 14 | + (dialogEl: HTMLDialogElement | undefined, event: PointerEvent): boolean => { |
| 15 | + if (!dialogEl) return false; |
| 16 | + if (event.pointerId === -1) return false; |
| 17 | + |
| 18 | + const modal = dialogEl.getBoundingClientRect(); |
| 19 | + |
| 20 | + const { clientX: x, clientY: y } = event; |
| 21 | + |
| 22 | + const isInsideModal = |
| 23 | + x >= modal.left && x <= modal.right && y >= modal.top && y <= modal.bottom; |
| 24 | + |
| 25 | + if (isInsideModal) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + return true; |
| 30 | + } |
| 31 | + ); |
| 32 | + |
| 33 | + const handleBackdropDown$ = $(async (e: PointerEvent) => { |
| 34 | + e.stopPropagation(); |
| 35 | + if (!context.contentRef.value) { |
| 36 | + isDownOnBackdrop.value = false; |
| 37 | + return; |
| 38 | + } |
| 39 | + isDownOnBackdrop.value = await isBackdropEvent$(context.contentRef.value, e); |
| 40 | + }); |
| 41 | + |
| 42 | + const handleBackdropSlide$ = $(async (e: PointerEvent) => { |
| 43 | + e.stopPropagation(); |
| 44 | + if (!isDownOnBackdrop.value) { |
| 45 | + isDownOnBackdrop.value = false; |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + if (!context.closeOnOutsideClick) { |
| 50 | + isDownOnBackdrop.value = false; |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + if (!context.contentRef.value) { |
| 55 | + isDownOnBackdrop.value = false; |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + const isBackdrop = await isBackdropEvent$(context.contentRef.value, e); |
| 60 | + |
| 61 | + if (isBackdrop) { |
| 62 | + context.isOpen.value = false; |
| 63 | + } |
| 64 | + |
| 65 | + isDownOnBackdrop.value = false; |
| 66 | + }); |
| 67 | + |
| 68 | + const handleClose$ = $(() => { |
| 69 | + context.isOpen.value = false; |
| 70 | + }); |
| 71 | + |
| 72 | + return ( |
| 73 | + <dialog |
| 74 | + {...props} |
| 75 | + ref={context.contentRef} |
| 76 | + onPointerDown$={[handleBackdropDown$, props.onPointerDown$]} |
| 77 | + onPointerUp$={[handleBackdropSlide$, props.onPointerUp$]} |
| 78 | + onClose$={[handleClose$, props.onClose$]} |
| 79 | + aria-labelledby={context.isTitle.value ? titleId : undefined} |
| 80 | + aria-describedby={context.isDescription.value ? descriptionId : undefined} |
| 81 | + > |
| 82 | + <Slot /> |
| 83 | + </dialog> |
| 84 | + ); |
| 85 | +}); |
0 commit comments