Skip to content
Draft
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
13 changes: 8 additions & 5 deletions packages/components/src/modal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ function UnforwardedModal(
describedby: undefined,
},
onRequestClose,
onValidateClose = () => true,
icon,
closeButtonLabel,
children,
Expand Down Expand Up @@ -341,11 +342,13 @@ function UnforwardedModal(
size="compact"
onClick={ (
event: React.MouseEvent< HTMLButtonElement >
) =>
closeModal().then( () =>
onRequestClose( event )
)
}
) => {
if ( onValidateClose() ) {
closeModal().then( () =>
onRequestClose( event )
);
}
} }
icon={ close }
label={
closeButtonLabel ||
Expand Down
36 changes: 35 additions & 1 deletion packages/components/src/modal/stories/index.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { StoryFn, Meta } from '@storybook/react';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useRef, useState } from '@wordpress/element';
import { fullscreen } from '@wordpress/icons';

/**
Expand Down Expand Up @@ -118,3 +118,37 @@ WithHeaderActions.args = {
WithHeaderActions.parameters = {
...Default.parameters,
};

export const PreventCloseRequest = {
render: function Render() {
const [ isOpen, setOpen ] = useState( false );
const closableCbxRef = useRef< HTMLInputElement >( null );
const openModal = () => setOpen( true );
const closeModal = () => setOpen( false );

return (
<>
<Button variant="secondary" onClick={ openModal }>
Open Modal
</Button>
{ isOpen && (
<Modal
title="This is my modal"
onRequestClose={ closeModal }
onValidateClose={ () =>
closableCbxRef.current?.checked
}
>
<input
type="checkbox"
// eslint-disable-next-line no-restricted-syntax
id="allow-close"
ref={ closableCbxRef }
/>{ ' ' }
<label htmlFor="allow-close">Allow close</label>
</Modal>
) }
</>
);
},
};
1 change: 1 addition & 0 deletions packages/components/src/modal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export type ModalProps = {
onRequestClose: (
event?: React.KeyboardEvent< HTMLDivElement > | React.SyntheticEvent
) => void;
onValidateClose?: () => boolean | void;
/**
* If this property is added, it will an additional class name to the modal
* overlay `div`.
Expand Down