-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
CodeBlock.tsx
303 lines (280 loc) · 9.28 KB
/
CodeBlock.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import React from 'react'
import 'server-only'
import { getThemeColors } from '../../index'
import { CopyButton } from './CopyButton'
import { Tokens } from './Tokens'
import type { Languages } from './get-tokens'
import { getTokens } from './get-tokens'
import type { ContextValue } from './Context'
import { Context } from './Context'
import { CopyButtonContextProvider } from './contexts'
import { LineNumbers } from './LineNumbers'
import { Pre } from './Pre'
import { Toolbar } from './Toolbar'
import { parseSourceTextMetadata } from './parse-source-text-metadata'
import {
generateFocusedLinesGradient,
generateHighlightedLinesGradient,
} from './utils'
export type BaseCodeBlockProps = {
/** Name or path of the code block. Ordered filenames will be stripped from the name e.g. `01.index.tsx` becomes `index.tsx`. */
filename?: string
/** Language of the source code. When used with `source`, the file extension will be used by default. */
language?: Languages
/** A string of comma separated lines and ranges to highlight e.g. `'1, 3-5, 7'`. */
highlightedLines?: string
/** A string of comma separated lines and ranges to focus e.g. `'6-8, 12'`. */
focusedLines?: string
/** Opacity of unfocused lines when using `focusedLines`. */
unfocusedLinesOpacity?: number
/** Show or hide a button that copies the source code to the clipboard. */
allowCopy?: boolean
/** Whether or not to allow errors. Accepts a boolean or comma-separated list of allowed error codes. */
allowErrors?: boolean | string
/** Show or hide error diagnostics. */
showErrors?: boolean
/** Show or hide line numbers. */
showLineNumbers?: boolean
/** Show or hide the toolbar. */
showToolbar?: boolean
/** Path to the source file on disk in development and the git provider source in production. */
sourcePath?: string | false
/** Class names to apply to code block elements. Use the `children` prop for full control of styling. */
className?: {
container?: string
toolbar?: string
lineNumbers?: string
token?: string
popover?: string
}
/** Styles to apply to code block elements. Use the `children` prop for full control of styling. */
style?: {
container?: React.CSSProperties
toolbar?: React.CSSProperties
lineNumbers?: React.CSSProperties
token?: React.CSSProperties
popover?: React.CSSProperties
}
/** Overrides default rendering to allow full control over styles using `CodeBlock` components like `Tokens`, `LineNumbers`, and `Toolbar`. */
children?: React.ReactNode
}
export type CodeBlockProps =
| ({
/** Source code to highlight. */
value: string
} & BaseCodeBlockProps)
| ({
/** Path to the source file on disk to highlight. */
source: string
/** The working directory for the `source`. Added automatically when using `mdxts/loader`. */
workingDirectory?: string
} & BaseCodeBlockProps)
/** Renders a `pre` element with syntax highlighting, type information, and type checking. */
export async function CodeBlock({
filename,
language,
highlightedLines,
focusedLines,
unfocusedLinesOpacity = 0.6,
allowCopy,
allowErrors,
showErrors,
showLineNumbers,
showToolbar,
sourcePath,
...props
}: CodeBlockProps) {
const padding = props.style?.container?.padding ?? '0.5lh'
const hasValue = 'value' in props
const hasSource = 'source' in props
const options: any = {}
if (hasValue) {
options.value = props.value
} else if (hasSource) {
options.source = props.source
options.workingDirectory = props.workingDirectory
}
const metadata = await parseSourceTextMetadata({
filename,
language,
allowErrors,
...options,
})
const tokens = await getTokens(
metadata.value,
metadata.language,
metadata.filename,
allowErrors,
showErrors,
// Simplify the path for more legibile error messages.
sourcePath ? sourcePath.split(process.cwd()).at(1) : undefined
)
const contextValue = {
value: metadata.value,
filenameLabel: filename || hasSource ? metadata.filenameLabel : undefined,
highlightedLines,
padding,
sourcePath,
tokens,
} satisfies ContextValue
if ('children' in props) {
return (
<Context value={contextValue}>
<CopyButtonContextProvider value={metadata.value}>
{props.children}
</CopyButtonContextProvider>
</Context>
)
}
const theme = await getThemeColors()
const shouldRenderToolbar = Boolean(
showToolbar === undefined ? filename || hasSource || allowCopy : showToolbar
)
const highlightedLinesGradient = highlightedLines
? generateHighlightedLinesGradient(highlightedLines)
: undefined
const focusedLinesGradient = focusedLines
? generateFocusedLinesGradient(focusedLines)
: undefined
const Container = shouldRenderToolbar ? 'div' : React.Fragment
const containerProps = shouldRenderToolbar
? {
className: props.className?.container,
style: {
backgroundColor: theme.background,
color: theme.foreground,
borderRadius: 5,
boxShadow: `0 0 0 1px ${theme.panel.border}`,
...props.style?.container,
padding: 0,
} satisfies React.CSSProperties,
}
: {}
const sharedCodeStyles = {
gridRow: '1 / -1',
display: 'block',
width: 'max-content',
padding,
} satisfies React.CSSProperties
return (
<Context value={contextValue}>
<Container {...containerProps}>
{shouldRenderToolbar ? (
<Toolbar
allowCopy={allowCopy === undefined ? Boolean(filename) : allowCopy}
className={props.className?.toolbar}
style={{ padding, ...props.style?.toolbar }}
/>
) : null}
<Pre
className={
shouldRenderToolbar ? undefined : props.className?.container
}
style={{
position: 'relative',
whiteSpace: 'pre',
wordWrap: 'break-word',
display: 'grid',
gridTemplateColumns: showLineNumbers ? 'auto 1fr' : undefined,
margin: 0,
overflow: 'auto',
backgroundColor: shouldRenderToolbar ? 'inherit' : theme.background,
color: shouldRenderToolbar ? undefined : theme.foreground,
borderRadius: shouldRenderToolbar ? 'inherit' : 5,
boxShadow: shouldRenderToolbar
? undefined
: `0 0 0 1px ${theme.panel.border}`,
...(highlightedLines
? {
'--h0': `rgba(0, 0, 0, 0)`,
'--h1': theme.editor.rangeHighlightBackground,
backgroundPosition: `0 ${padding}`,
backgroundImage: highlightedLinesGradient,
}
: {}),
...(focusedLines
? {
'--m0': `rgba(0, 0, 0, ${unfocusedLinesOpacity})`,
'--m1': 'rgba(0, 0, 0, 1)',
maskPosition: `0 ${padding}`,
maskImage: focusedLinesGradient,
}
: {}),
...(shouldRenderToolbar ? {} : props.style?.container),
padding: 0,
}}
>
{showLineNumbers ? (
<>
<LineNumbers
className={props.className?.lineNumbers}
style={{
padding,
gridColumn: 1,
gridRow: '1 / -1',
width: '4ch',
backgroundPosition: 'inherit',
backgroundImage: 'inherit',
...props.style?.lineNumbers,
}}
/>
<code
style={{
...sharedCodeStyles,
gridColumn: 2,
paddingLeft: 0,
}}
>
<Tokens
className={{
token: props.className?.token,
popover: props.className?.popover,
}}
style={{
token: props.style?.token,
popover: props.style?.popover,
}}
/>
</code>
</>
) : (
<code
style={{
...sharedCodeStyles,
gridColumn: 1,
}}
>
<Tokens
className={{
token: props.className?.token,
popover: props.className?.popover,
}}
style={{
token: props.style?.token,
popover: props.style?.popover,
}}
/>
</code>
)}
{allowCopy !== false && !shouldRenderToolbar ? (
<CopyButton
css={{
placeSelf: 'start end',
gridColumn: showLineNumbers ? 2 : 1,
gridRow: '1 / -1',
position: 'sticky',
top: padding,
right: padding,
boxShadow: `0 0 0 1px ${theme.panel.border}`,
backgroundColor: theme.activityBar.background,
color: theme.activityBar.foreground,
borderRadius: 5,
}}
value={metadata.value}
/>
) : null}
</Pre>
</Container>
</Context>
)
}