Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

Commit

Permalink
fix(Modal): Throw error when modal is missing params
Browse files Browse the repository at this point in the history
ModalManager used to fail silently when a modal was opened
& attempted to register with incomplete parameters.
Now an error will be thrown to prevent this.
  • Loading branch information
diondiondion committed Jun 3, 2020
1 parent b6c85f1 commit a51b130
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/Modal/ModalManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,23 @@ const defaultState = {
const ModalContext = createContext(defaultState);
const ModalStackContext = createContext([]);

function validateObjectShape(modalObject) {
const missingFields = [
!modalObject.name && 'name',
!modalObject.focusAnchor && 'focusAnchor',
!modalObject.ref && 'ref',
!modalObject.onClose && 'onClose',
].filter(Boolean);

if (missingFields.length !== 0) {
throw new Error(
`ModalManager couldn't register modal. Missing parameter(s): ${missingFields.join(
', '
)}.`
);
}
}

function ModalManager({children}) {
const [modalStack, setModalStack] = useState([]);
const elementToFocus = useRef(null);
Expand All @@ -32,19 +49,17 @@ function ModalManager({children}) {
* ModalManager does not _own_ the open/close state of a modal,
* it just needs to track it in order to handle focus restoration.
*/
const register = useCallback(({name, focusAnchor, ref, onClose}) => {
if (!name || !focusAnchor || !ref || !onClose) {
return;
}
const register = useCallback(newModalObject => {
validateObjectShape(newModalObject);

setModalStack(prevModalStack => {
const isModalAlreadyRegistered = Boolean(
prevModalStack.find(modal => modal.name === name)
prevModalStack.find(modal => modal.name === newModalObject.name)
);
if (isModalAlreadyRegistered) {
return prevModalStack;
}
return [...prevModalStack, {name, focusAnchor, ref, onClose}];
return [...prevModalStack, newModalObject];
});
}, []);

Expand Down

0 comments on commit a51b130

Please sign in to comment.