-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.js
78 lines (68 loc) · 2.07 KB
/
index.js
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
71
72
73
74
75
76
77
78
/**
* @typedef {import('mdx/types.js').MDXComponents} Components
* @typedef {import('preact').ComponentChildren} ComponentChildren
*/
/**
* @callback MergeComponents
* Custom merge function.
* @param {Readonly<Components>} currentComponents
* Current components from the context.
* @returns {Components}
* Merged components.
*
* @typedef Props
* Configuration.
* @property {Readonly<Components> | MergeComponents | null | undefined} [components]
* Mapping of names for JSX components to Preact components (optional).
* @property {boolean | null | undefined} [disableParentContext=false]
* Turn off outer component context (default: `false`).
* @property {ComponentChildren | null | undefined} [children]
* Children (optional).
*/
import {createContext, h} from 'preact'
import {useContext} from 'preact/hooks'
const MDXContext = createContext({})
/**
* Get current components from the MDX Context.
*
* @param {Readonly<Components> | MergeComponents | null | undefined} [components]
* Additional components to use or a function that takes the current
* components and filters/merges/changes them (optional).
* @returns {Components}
* Current components.
*/
export function useMDXComponents(components) {
const contextComponents = useContext(MDXContext)
// Custom merge via a function prop
if (typeof components === 'function') {
return components(contextComponents)
}
return {...contextComponents, ...components}
}
/** @type {Readonly<Components>} */
const emptyObject = {}
/**
* Provider for MDX context
*
* @param {Readonly<Props>} props
* Props.
* @returns {JSX.Element}
* Element.
*/
export function MDXProvider({children, components, disableParentContext}) {
/** @type {Readonly<Components>} */
let allComponents
if (disableParentContext) {
allComponents =
typeof components === 'function'
? components({})
: components || emptyObject
} else {
allComponents = useMDXComponents(components)
}
return h(
MDXContext.Provider,
{children: undefined, value: allComponents},
children
)
}