Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/giant-rats-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@digdir/designsystemet-react": patch
---

**Dialog**: If the browser supports `closedBy` on `<dialog>`, we let the browser handle it
18 changes: 12 additions & 6 deletions packages/react/src/components/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export type DialogProps = MergeRight<
/**
* Light dismiss behavior, allowing to close on backdrop click by setting `closedby="any"`.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/closedBy
*
* @default 'closerequest'
*/
closedby?: 'none' | 'closerequest' | 'any';
Expand Down Expand Up @@ -99,6 +101,15 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
const handleClosedby = (event: Event) => {
if (event.defaultPrevented) return; // Skip if default action is prevented
const { clientY: y, clientX: x, target } = event as MouseEvent;
/* Check if clicked element or its closest parent has data-command='close' */
if (target instanceof Element && event.type === 'click') {
const closeElement = target.closest('[data-command="close"]');
if (closeElement) return dialog?.close();
}

// if the browser supports closedBy, we let the browser handle it
// see https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/closedBy
if (dialog && 'closedBy' in dialog) return;

if (event instanceof KeyboardEvent)
return (
Expand All @@ -107,12 +118,6 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
event.preventDefault()
); // Skip ESC-key if closedby="none"

/* Check if clicked element or its closest parent has data-command='close' */
if (target instanceof Element) {
const closeElement = target.closest('[data-command="close"]');
if (closeElement) return dialog?.close();
}

if (window.getSelection()?.toString()) return; // Fix bug where if you select text spanning two divs it thinks you clicked outside
if (dialog && target === dialog && closedby === 'any') {
const { top, left, right, bottom } = dialog.getBoundingClientRect();
Expand Down Expand Up @@ -151,6 +156,7 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
className={cl('ds-dialog', className)}
ref={mergedRefs}
data-modal={modal}
closedby={closedby}
{...rest}
>
{closeButton !== false && (
Expand Down
Loading