@toolpad/core
Version:
Dashboard framework powered by Material UI.
90 lines (89 loc) • 2.66 kB
JavaScript
'use client';
import invariant from 'invariant';
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import { DialogsContext } from "./DialogsContext.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
* Provider for Dialog stacks. The subtree of this component can use the `useDialogs` hook to
* access the dialogs API. The dialogs are rendered in the order they are requested.
*
* Demos:
*
* - [useDialogs](https://mui.com/toolpad/core/react-use-dialogs/)
*
* API:
*
* - [DialogsProvider API](https://mui.com/toolpad/core/api/dialogs-provider)
*/
function DialogsProvider(props) {
const {
children,
unmountAfter = 1000
} = props;
const [stack, setStack] = React.useState([]);
const keyPrefix = React.useId();
const nextId = React.useRef(0);
const requestDialog = useEventCallback(function open(Component, payload, options = {}) {
const {
onClose = async () => {}
} = options;
let resolve;
const promise = new Promise(resolveImpl => {
resolve = resolveImpl;
});
invariant(resolve, 'resolve not set');
const key = `${keyPrefix}-${nextId.current}`;
nextId.current += 1;
const newEntry = {
key,
open: true,
promise,
Component,
payload,
onClose,
resolve
};
setStack(prevStack => [...prevStack, newEntry]);
return promise;
});
const closeDialogUi = useEventCallback(function closeDialogUi(dialog) {
setStack(prevStack => prevStack.map(entry => entry.promise === dialog ? {
...entry,
open: false
} : entry));
setTimeout(() => {
// wait for closing animation
setStack(prevStack => prevStack.filter(entry => entry.promise !== dialog));
}, unmountAfter);
});
const closeDialog = useEventCallback(async function closeDialog(dialog, result) {
const entryToClose = stack.find(entry => entry.promise === dialog);
invariant(entryToClose, 'dialog not found');
await entryToClose.onClose(result);
entryToClose.resolve(result);
closeDialogUi(dialog);
return dialog;
});
const contextValue = React.useMemo(() => ({
open: requestDialog,
close: closeDialog
}), [requestDialog, closeDialog]);
return /*#__PURE__*/_jsxs(DialogsContext.Provider, {
value: contextValue,
children: [children, stack.map(({
key,
open,
Component,
payload,
promise
}) => /*#__PURE__*/_jsx(Component, {
payload: payload,
open: open,
onClose: async result => {
await closeDialog(promise, result);
}
}, key))]
});
}
export { DialogsProvider };