Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dispatch an event to a modal being closed before closing it, so that the modal can prevent it based on its state #466

Merged
merged 4 commits into from
Oct 7, 2024
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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,29 @@ By default, the modal will close when you click outside the modal. If you want t
}
```

## Preventing closing the modal on Escape or on click away based on the modal state

When a modal is closed on Escape or click away, `closingModalOnEscape` and `closingModalOnClickAway` are issued. Handle these events to prevent closing a modal based on its state, for example, if there are uncommitted changes.

For example, if a modal has a `isDirty` property, it could have the following handler:

```
@script
<script>
$wire.on('closingModalOnEscape', data => {
if ($wire.isDirty && !confirm('{{ __('You have unsaved changes. Are you sure you want to close this dialog?') }}')) {
data.closing = false;
}
});
$wire.on('closingModalOnClickAway', data => {
if ($wire.isDirty && !confirm('{{ __('You have unsaved changes. Are you sure you want to close this dialog?') }}')) {
data.closing = false;
}
});
</script>
@endscript
```

## Skipping previous modals
In some cases you might want to skip previous modals. For example:
1. Team overview modal
Expand Down
20 changes: 20 additions & 0 deletions resources/js/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ window.LivewireUIModal = () => {
return;
}

if (!this.closingModal('closingModalOnEscape')) {
return;
}

let force = this.getActiveComponentModalAttribute('closeOnEscapeIsForceful') === true;
this.closeModal(force);
},
Expand All @@ -24,8 +28,24 @@ window.LivewireUIModal = () => {
return;
}

if (!this.closingModal('closingModalOnClickAway')) {
return;
}

this.closeModal(true);
},
closingModal(eventName) {
const componentName = this.$wire.get('components')[this.activeComponent].name;

var params = {
id: this.activeComponent,
closing: true,
};

Livewire.dispatchTo(componentName, eventName, params);

return params.closing;
},
closeModal(force = false, skipPreviousModals = 0, destroySkipped = false) {
if(this.show === false) {
return;
Expand Down
Loading