Open History to see the last commit
1import {
2 Show,
3 createContext,
4 createSignal,
5 splitProps,
6 useContext,
7} from 'solid-js'
8import { Portal as SolidPortal } from 'solid-js/web'
9import type { Accessor, JSX } from 'solid-js'
10import { cn } from '@/utils'
11β
12const PortalContext = createContext<Accessor<HTMLElement | undefined>>()
13β
14type PortalProviderProps = Omit<JSX.HTMLElementTags['div'], 'ref'>
15β
16/**
17 * Provides a local mount element for descendant Portal content.
18 *
19 * @example
20 * ```tsx
21 * <PortalProvider>
22 * <Portal>
23 * <div>Portalled content</div>
24 * </Portal>
25 * </PortalProvider>
26 * ```
27 */
28function PortalProvider(props: PortalProviderProps) {
29 const [local, others] = splitProps(props, ['children', 'class'])
30 const [portalMount, setPortalMount] = createSignal<HTMLElement>()
31β
32 return (
33 <PortalContext.Provider value={portalMount}>
34 <div
35 {...others}
36 data-slot="portal-provider"
37 class={cn(local.class ?? 'contents')}
38 ref={(element) => setPortalMount(element)}
39 >
40 {local.children}
41 </div>
42 </PortalContext.Provider>
43 )
44}
45β
46type PortalProps = {
47 children?: JSX.Element
48 mount?: Node
49}
50β
51/**
52 * Renders children into the nearest PortalProvider mount, a custom mount, or the
53 * document body.
54 *
55 * @example
56 * ```tsx
57 * <PortalProvider>
58 * <Portal>
59 * <div>Portalled content</div>
60 * </Portal>
61 * </PortalProvider>
62 * ```
63 */
64function Portal(props: PortalProps) {
65 const contextMount = useContext(PortalContext)
66 const mount = () => props.mount ?? contextMount?.()
67β
68 return (
69 <Show
70 when={mount()}
71 fallback={
72 contextMount ? null : <SolidPortal>{props.children}</SolidPortal>
73 }
74 >
75 {(resolvedMount) => (
76 <SolidPortal mount={resolvedMount()}>{props.children}</SolidPortal>
77 )}
78 </Show>
79 )
80}
81β
82export { Portal, PortalProvider }