-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathindex.js
84 lines (74 loc) · 2.33 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
79
80
81
82
83
84
/**
* @typedef {import('mdx/types.js').MDXComponents} MDXComponents
* @typedef {import('react').Component<{}, {}, unknown>} Component
* @typedef {import('react').ReactNode} ReactNode
*/
/**
* @callback MergeComponents
* Custom merge function.
* @param {Readonly<MDXComponents>} currentComponents
* Current components from the context.
* @returns {MDXComponents}
* Additional components.
*
* @typedef Props
* Configuration for `MDXProvider`.
* @property {ReactNode | null | undefined} [children]
* Children (optional).
* @property {Readonly<MDXComponents> | MergeComponents | null | undefined} [components]
* Additional components to use or a function that creates them (optional).
* @property {boolean | null | undefined} [disableParentContext=false]
* Turn off outer component context (default: `false`).
*/
import React from 'react'
/** @type {Readonly<MDXComponents>} */
const emptyComponents = {}
const MDXContext = React.createContext(emptyComponents)
/**
* Get current components from the MDX Context.
*
* @param {Readonly<MDXComponents> | MergeComponents | null | undefined} [components]
* Additional components to use or a function that creates them (optional).
* @returns {MDXComponents}
* Current components.
*/
export function useMDXComponents(components) {
const contextComponents = React.useContext(MDXContext)
// Memoize to avoid unnecessary top-level context changes
return React.useMemo(
function () {
// Custom merge via a function prop
if (typeof components === 'function') {
return components(contextComponents)
}
return {...contextComponents, ...components}
},
[contextComponents, components]
)
}
/**
* Provider for MDX context.
*
* @param {Readonly<Props>} properties
* Properties.
* @returns {JSX.Element}
* Element.
* @satisfies {Component}
*/
export function MDXProvider(properties) {
/** @type {Readonly<MDXComponents>} */
let allComponents
if (properties.disableParentContext) {
allComponents =
typeof properties.components === 'function'
? properties.components(emptyComponents)
: properties.components || emptyComponents
} else {
allComponents = useMDXComponents(properties.components)
}
return React.createElement(
MDXContext.Provider,
{value: allComponents},
properties.children
)
}