-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprovider.tsx
More file actions
70 lines (63 loc) · 1.64 KB
/
Copy pathprovider.tsx
File metadata and controls
70 lines (63 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"use client";
import { AlertDialog } from "@base-ui/react";
import { Dialog } from "@base-ui/react/dialog";
import type {
ModalRole,
ModalWrapperComponent,
ModalWrapperType,
} from "@hirotoshioi/hiraku-core";
import { useModalStore } from "@hirotoshioi/hiraku-core";
import { Suspense } from "react";
/**
* Resolve a wrapper type to the corresponding Base UI Root component.
*/
function getWrapperComponent(
wrapper: ModalWrapperType | undefined,
): ModalWrapperComponent {
if (typeof wrapper === "function") {
return wrapper;
}
switch (wrapper) {
case "sheet":
return Dialog.Root;
case "alert-dialog":
return AlertDialog.Root;
default:
return Dialog.Root;
}
}
/**
* Provider that renders all active modals.
* Place this at the app root.
*
* Base UI style: the library controls the Root, users implement the Content.
*/
export function ModalProvider() {
const modals = useModalStore((state) => state.modals);
const close = useModalStore((state) => state.close);
const handleClose = (id: string, role: ModalRole = "dismiss") => {
void close(id, undefined, role);
};
return (
<>
{modals.map((modal) => {
const ModalComponent = modal.component;
const Wrapper = getWrapperComponent(modal.wrapper);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const props = modal.props ?? {};
const onOpenChange = (open: boolean) => {
if (!open) {
handleClose(modal.id, "dismiss");
}
};
return (
<Wrapper key={modal.id} open={modal.open} onOpenChange={onOpenChange}>
<Suspense>
<ModalComponent {...props} />
</Suspense>
</Wrapper>
);
})}
</>
);
}