Skip to content

Commit 5030657

Browse files
committed
docs(modal): add "Prevent default close behavior" example
1 parent da534b8 commit 5030657

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

docs/src/pages/components/Modal.svx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ Use the large size for complex content by setting `size` to `"lg"`. This provide
6666

6767
<FileSource src="/framed/Modal/ModalLarge" />
6868

69+
## Prevent default close behavior
70+
71+
The modal dispatches a cancelable `close` event, allowing you to prevent the modal from closing using `e.preventDefault()`. The event includes a `trigger` property indicating what triggered the close attempt: `"escape-key"`, `"outside-click"`, or `"close-button"`.
72+
73+
<FileSource src="/framed/Modal/ModalPreventClose" />
74+
6975
## Prevent close on outside click
7076

7177
Disable closing the modal when clicking outside by setting `preventCloseOnClickOutside` to `true`. This is useful for transactional modals where explicit user action is required.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<script>
2+
import { Button, Modal, InlineNotification } from "carbon-components-svelte";
3+
4+
let open = false;
5+
let hasUnsavedChanges = true;
6+
let showWarning = false;
7+
</script>
8+
9+
<Button
10+
on:click={() => {
11+
open = true;
12+
hasUnsavedChanges = true;
13+
showWarning = false;
14+
}}>Open modal with unsaved changes</Button
15+
>
16+
17+
<Modal
18+
bind:open
19+
modalHeading="Edit profile"
20+
primaryButtonText="Save"
21+
secondaryButtonText="Discard changes"
22+
on:click:button--secondary={() => {
23+
hasUnsavedChanges = false;
24+
open = false;
25+
}}
26+
on:close={(e) => {
27+
console.log("Close triggered by:", e.detail.trigger);
28+
if (hasUnsavedChanges) {
29+
e.preventDefault();
30+
showWarning = true;
31+
}
32+
}}
33+
on:submit={() => {
34+
hasUnsavedChanges = false;
35+
open = false;
36+
}}
37+
>
38+
{#if showWarning}
39+
<InlineNotification
40+
kind="warning"
41+
title="Unsaved changes"
42+
subtitle="Please save or discard your changes before closing."
43+
hideCloseButton
44+
/>
45+
{/if}
46+
<p>You have unsaved changes. Click "Save" to apply them.</p>
47+
</Modal>

0 commit comments

Comments
 (0)