Skip to content

Commit 17c4a75

Browse files
cnaples79danielroe
andauthored
fix: prevent modal closing on inner clicks (#685)
Co-authored-by: Daniel Roe <daniel@roe.dev>
1 parent 779b239 commit 17c4a75

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

app/app.vue

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,20 +79,37 @@ function handleGlobalKeyup() {
7979
showKbdHints.value = false
8080
}
8181
82-
/* A hack to get light dismiss to work in safari because it does not support closedby="any" yet */
82+
// Light dismiss fallback for browsers that don't support closedby="any" (Safari + old Chrome/Firefox)
8383
// https://codepen.io/paramagicdev/pen/gbYompq
8484
// see: https://github.com/npmx-dev/npmx.dev/pull/522#discussion_r2749978022
8585
function handleModalLightDismiss(e: MouseEvent) {
8686
const target = e.target as HTMLElement
8787
if (target.tagName === 'DIALOG' && target.hasAttribute('open')) {
88+
const rect = target.getBoundingClientRect()
89+
const isOutside =
90+
e.clientX < rect.left ||
91+
e.clientX > rect.right ||
92+
e.clientY < rect.top ||
93+
e.clientY > rect.bottom
94+
95+
if (!isOutside) return
8896
;(target as HTMLDialogElement).close()
8997
}
9098
}
9199
92100
if (import.meta.client) {
93101
useEventListener(document, 'keydown', handleGlobalKeydown)
94102
useEventListener(document, 'keyup', handleGlobalKeyup)
95-
useEventListener(document, 'click', handleModalLightDismiss)
103+
104+
// Feature check for native light dismiss support via closedby="any"
105+
// https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/dialog#closedby
106+
const supportsClosedBy =
107+
typeof HTMLDialogElement !== 'undefined' &&
108+
typeof HTMLDialogElement.prototype === 'object' &&
109+
'closedBy' in HTMLDialogElement.prototype
110+
if (!supportsClosedBy) {
111+
useEventListener(document, 'click', handleModalLightDismiss)
112+
}
96113
}
97114
</script>
98115

0 commit comments

Comments
 (0)