-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mdx-components.tsx
289 lines (268 loc) · 7.87 KB
/
mdx-components.tsx
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import React, {
useEffect,
useRef,
useState,
cloneElement,
Children,
ReactNode,
ReactElement,
ComponentProps
} from 'react'
import 'intersection-observer'
import { useSetActiveAnchor, DetailsProvider, useDetails } from './contexts'
import { Collapse, Anchor } from './components'
import { IS_BROWSER } from './constants'
import cn from 'clsx'
import { DocsThemeConfig } from './types'
import { Code, Pre, Table, Td, Th, Tr } from 'nextra/components'
let observer: IntersectionObserver
let setActiveAnchor: ReturnType<typeof useSetActiveAnchor>
const slugs = new WeakMap()
if (IS_BROWSER) {
observer ||= new IntersectionObserver(
entries => {
setActiveAnchor(f => {
const ret = { ...f }
for (const entry of entries) {
if (entry?.rootBounds && slugs.has(entry.target)) {
const [slug, index] = slugs.get(entry.target)
const aboveHalfViewport =
entry.boundingClientRect.y + entry.boundingClientRect.height <=
entry.rootBounds.y + entry.rootBounds.height
const insideHalfViewport = entry.intersectionRatio > 0
ret[slug] = {
index,
aboveHalfViewport,
insideHalfViewport
}
}
}
let activeSlug = ''
let smallestIndexInViewport = Infinity
let largestIndexAboveViewport = -1
for (let s in ret) {
ret[s].isActive = false
if (
ret[s].insideHalfViewport &&
ret[s].index < smallestIndexInViewport
) {
smallestIndexInViewport = ret[s].index
activeSlug = s
}
if (
smallestIndexInViewport === Infinity &&
ret[s].aboveHalfViewport &&
ret[s].index > largestIndexAboveViewport
) {
largestIndexAboveViewport = ret[s].index
activeSlug = s
}
}
if (ret[activeSlug]) ret[activeSlug].isActive = true
return ret
})
},
{
rootMargin: '0px 0px -50%',
threshold: [0, 1]
}
)
}
// Anchor links
const createHeaderLink = (
Tag: `h${2 | 3 | 4 | 5 | 6}`,
context: { index: number }
) =>
function HeaderLink({
children,
id,
...props
}: ComponentProps<'h2'>): ReactElement {
setActiveAnchor ??= useSetActiveAnchor()
const obRef = useRef<HTMLAnchorElement>(null)
useEffect(() => {
const heading = obRef.current
if (!heading) return
slugs.set(heading, [id, (context.index += 1)])
observer.observe(heading)
return () => {
observer.disconnect()
slugs.delete(heading)
setActiveAnchor(f => {
const ret = { ...f }
delete ret[id!]
return ret
})
}
}, [])
return (
<Tag
className={cn(
'nx-font-semibold nx-tracking-tight',
{
h2: 'nx-mt-10 nx-text-3xl nx-border-b nx-pb-1 dark:nx-border-primary-100/10 contrast-more:nx-border-neutral-400 contrast-more:dark:nx-border-neutral-400',
h3: 'nx-mt-8 nx-text-2xl',
h4: 'nx-mt-8 nx-text-xl',
h5: 'nx-mt-8 nx-text-lg',
h6: 'nx-mt-8 nx-text-base'
}[Tag]
)}
{...props}
>
{children}
<span className="nx-absolute -nx-mt-20" id={id} ref={obRef} />
<a href={`#${id}`} className="subheading-anchor" />
</Tag>
)
}
const findSummary = (children: ReactNode) => {
let summary: ReactNode = null
const restChildren: ReactNode[] = []
Children.forEach(children, (child, index) => {
if (child && (child as ReactElement).type === Summary) {
summary ||= child
return
}
let c = child
if (
!summary &&
child &&
typeof child === 'object' &&
(child as ReactElement).type !== Details &&
'props' in child &&
child.props
) {
const result = findSummary(child.props.children)
summary = result[0]
c = cloneElement(child, {
...child.props,
children: result[1]?.length ? result[1] : undefined,
key: index
})
}
restChildren.push(c)
})
return [summary, restChildren]
}
const Details = ({
children,
open,
...props
}: ComponentProps<'details'>): ReactElement => {
const [openState, setOpen] = useState(!!open)
const [summary, restChildren] = findSummary(children)
// To animate the close animation we have to delay the DOM node state here.
const [delayedOpenState, setDelayedOpenState] = useState(openState)
useEffect(() => {
if (openState) {
setDelayedOpenState(true)
} else {
const timeout = setTimeout(() => setDelayedOpenState(openState), 500)
return () => clearTimeout(timeout)
}
}, [openState])
return (
<details
className="nx-my-4 nx-rounded nx-border nx-border-gray-200 nx-bg-white nx-p-2 nx-shadow-sm dark:nx-border-neutral-800 dark:nx-bg-neutral-900 first:nx-mt-0"
{...props}
open={delayedOpenState}
{...(openState && { 'data-expanded': true })}
>
<DetailsProvider value={setOpen}>{summary}</DetailsProvider>
<Collapse open={openState}>{restChildren}</Collapse>
</details>
)
}
const Summary = (props: ComponentProps<'summary'>): ReactElement => {
const setOpen = useDetails()
return (
<summary
className={cn(
'nx-list-none nx-cursor-pointer nx-p-1 nx-transition-colors hover:nx-bg-gray-100 dark:hover:nx-bg-neutral-800',
"before:nx-mr-1 before:content-[''] before:nx-inline-block before:nx-transition-transform dark:before:nx-invert",
'[[data-expanded]>&]:before:nx-rotate-90 rtl:before:nx-rotate-180'
)}
{...props}
onClick={e => {
e.preventDefault()
setOpen(v => !v)
}}
/>
)
}
const A = ({ href = '', ...props }) => (
<Anchor href={href} newWindow={href.startsWith('https://')} {...props} />
)
export const getComponents = ({
isRawLayout,
components
}: {
isRawLayout?: boolean
components?: DocsThemeConfig['components']
}): DocsThemeConfig['components'] => {
if (isRawLayout) {
return { a: A }
}
const context = { index: 0 }
return {
h1: (props: ComponentProps<'h1'>) => (
<h1
className="nx-mt-2 nx-text-4xl nx-font-bold nx-tracking-tight"
{...props}
/>
),
h2: createHeaderLink('h2', context),
h3: createHeaderLink('h3', context),
h4: createHeaderLink('h4', context),
h5: createHeaderLink('h5', context),
h6: createHeaderLink('h6', context),
ul: (props: ComponentProps<'ul'>) => (
<ul
className="ltr:nx-ml-6 rtl:nx-mr-6 nx-mt-6 nx-list-disc first:nx-mt-0"
{...props}
/>
),
ol: (props: ComponentProps<'ol'>) => (
<ol
className="ltr:nx-ml-6 rtl:nx-mr-6 nx-mt-6 nx-list-decimal first:nx-mt-0"
{...props}
/>
),
li: (props: ComponentProps<'li'>) => <li className="nx-my-2" {...props} />,
blockquote: (props: ComponentProps<'blockquote'>) => (
<blockquote
className={cn(
'nx-mt-6 nx-border-gray-300 nx-italic nx-text-gray-700 dark:nx-border-gray-700 dark:nx-text-gray-400',
'rtl:nx-border-r-2 rtl:nx-pr-6 ltr:nx-border-l-2 ltr:nx-pl-6 first:nx-mt-0'
)}
{...props}
/>
),
hr: (props: ComponentProps<'hr'>) => (
<hr className="nx-my-8 dark:nx-border-gray-900" {...props} />
),
a: props => (
<A
{...props}
className="nx-text-primary-500 nx-underline nx-decoration-from-font [text-underline-position:under]"
/>
),
table: (props: ComponentProps<'table'>) => (
<Table
className="nextra-scrollbar nx-mt-6 nx-p-0 first:nx-mt-0"
{...props}
/>
),
p: (props: ComponentProps<'p'>) => (
<p className="nx-mt-6 nx-leading-7 first:nx-mt-0" {...props} />
),
tr: Tr,
th: Th,
td: Td,
details: Details,
summary: Summary,
pre: Pre,
code: Code,
...components
}
}