-
-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathCodeBlock.tsx
411 lines (393 loc) · 11.1 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import cn from 'classnames';
import {HighlightStyle} from '@codemirror/language';
import {highlightTree} from '@lezer/highlight';
import {javascript} from '@codemirror/lang-javascript';
import {html} from '@codemirror/lang-html';
import {css} from '@codemirror/lang-css';
import rangeParser from 'parse-numeric-range';
import {tags} from '@lezer/highlight';
import {CustomTheme} from '../Sandpack/Themes';
interface InlineHighlight {
step: number;
line: number;
startColumn: number;
endColumn: number;
}
const jsxLang = javascript({jsx: true, typescript: false});
const cssLang = css();
const htmlLang = html();
const CodeBlock = function CodeBlock({
children: {
props: {className = 'language-js', children: code = '', meta},
},
noMargin,
noShadow,
onLineHover,
}: {
children: React.ReactNode & {
props: {
className: string;
children?: string;
meta?: string;
};
};
className?: string;
noMargin?: boolean;
noShadow?: boolean;
onLineHover?: (lineNumber: number | null) => void;
}) {
code = code.trimEnd();
let lang = jsxLang;
if (className === 'language-css') {
lang = cssLang;
} else if (className === 'language-html') {
lang = htmlLang;
}
const tree = lang.language.parser.parse(code);
let tokenStarts = new Map();
let tokenEnds = new Map();
const highlightTheme = getSyntaxHighlight(CustomTheme);
highlightTree(tree, highlightTheme, (from, to, className) => {
tokenStarts.set(from, className);
tokenEnds.set(to, className);
});
const highlightedLines = new Map();
const lines = code.split('\n');
const lineDecorators = getLineDecorators(code, meta);
for (let decorator of lineDecorators) {
highlightedLines.set(decorator.line - 1, decorator.className);
}
const inlineDecorators = getInlineDecorators(code, meta);
const decoratorStarts = new Map();
const decoratorEnds = new Map();
for (let decorator of inlineDecorators) {
// Find where inline highlight starts and ends.
let decoratorStart = 0;
for (let i = 0; i < decorator.line - 1; i++) {
decoratorStart += lines[i].length + 1;
}
decoratorStart += decorator.startColumn;
const decoratorEnd =
decoratorStart + (decorator.endColumn - decorator.startColumn);
if (decoratorStarts.has(decoratorStart)) {
throw Error('Already opened decorator at ' + decoratorStart);
}
decoratorStarts.set(decoratorStart, decorator.className);
if (decoratorEnds.has(decoratorEnd)) {
throw Error('Already closed decorator at ' + decoratorEnd);
}
decoratorEnds.set(decoratorEnd, decorator.className);
}
// Produce output based on tokens and decorators.
// We assume tokens never overlap other tokens, and
// decorators never overlap with other decorators.
// However, tokens and decorators may mutually overlap.
// In that case, decorators always take precedence.
let currentDecorator = null;
let currentToken = null;
let buffer = '';
let lineIndex = 0;
let lineOutput = [];
let finalOutput = [];
for (let i = 0; i < code.length; i++) {
if (tokenEnds.has(i)) {
if (!currentToken) {
throw Error('Cannot close token at ' + i + ' because it was not open.');
}
if (!currentDecorator) {
lineOutput.push(
<span key={i + '/t'} className={currentToken}>
{buffer}
</span>
);
buffer = '';
}
currentToken = null;
}
if (decoratorEnds.has(i)) {
if (!currentDecorator) {
throw Error(
'Cannot close decorator at ' + i + ' because it was not open.'
);
}
lineOutput.push(
<span key={i + '/d'} className={currentDecorator}>
{buffer}
</span>
);
buffer = '';
currentDecorator = null;
}
if (decoratorStarts.has(i)) {
if (currentDecorator) {
throw Error(
'Cannot open decorator at ' + i + ' before closing last one.'
);
}
if (currentToken) {
lineOutput.push(
<span key={i + 'd'} className={currentToken}>
{buffer}
</span>
);
buffer = '';
} else {
lineOutput.push(buffer);
buffer = '';
}
currentDecorator = decoratorStarts.get(i);
}
if (tokenStarts.has(i)) {
if (currentToken) {
throw Error('Cannot open token at ' + i + ' before closing last one.');
}
currentToken = tokenStarts.get(i);
if (!currentDecorator) {
lineOutput.push(buffer);
buffer = '';
}
}
if (code[i] === '\n') {
lineOutput.push(buffer);
buffer = '';
const currentLineIndex = lineIndex;
finalOutput.push(
<div
key={lineIndex}
className={'cm-line ' + (highlightedLines.get(lineIndex) ?? '')}
onMouseEnter={
onLineHover ? () => onLineHover(currentLineIndex) : undefined
}>
{lineOutput}
<br />
</div>
);
lineOutput = [];
lineIndex++;
} else {
buffer += code[i];
}
}
if (currentDecorator) {
lineOutput.push(
<span key={'end/d'} className={currentDecorator}>
{buffer}
</span>
);
} else if (currentToken) {
lineOutput.push(
<span key={'end/t'} className={currentToken}>
{buffer}
</span>
);
} else {
lineOutput.push(buffer);
}
finalOutput.push(
<div
key={lineIndex}
className={'cm-line ' + (highlightedLines.get(lineIndex) ?? '')}
onMouseEnter={onLineHover ? () => onLineHover(lineIndex) : undefined}>
{lineOutput}
</div>
);
return (
<div
dir="ltr"
className={cn(
'sandpack sandpack--codeblock',
'rounded-2xl h-full w-full overflow-x-auto flex items-center bg-wash dark:bg-gray-95 shadow-lg',
!noMargin && 'my-8',
noShadow &&
'shadow-none rounded-2xl overflow-hidden w-full flex bg-transparent'
)}
style={{contain: 'content'}}>
<div className="sp-wrapper">
<div className="sp-stack">
<div className="sp-code-editor">
<pre className="sp-cm sp-pristine sp-javascript flex align-start">
<code
className="sp-pre-placeholder grow-[2]"
onMouseLeave={
onLineHover ? () => onLineHover(null) : undefined
}>
{finalOutput}
</code>
</pre>
</div>
</div>
</div>
</div>
);
};
export default CodeBlock;
function classNameToken(name: string): string {
return `sp-syntax-${name}`;
}
function getSyntaxHighlight(theme: any): HighlightStyle {
return HighlightStyle.define([
{tag: tags.link, textdecorator: 'underline'},
{tag: tags.emphasis, fontStyle: 'italic'},
{tag: tags.strong, fontWeight: 'bold'},
{
tag: tags.keyword,
class: classNameToken('keyword'),
},
{
tag: [tags.atom, tags.number, tags.bool],
class: classNameToken('static'),
},
{
tag: tags.standard(tags.tagName),
class: classNameToken('tag'),
},
{tag: tags.variableName, class: classNameToken('plain')},
{
// Highlight function call
tag: tags.function(tags.variableName),
class: classNameToken('definition'),
},
{
// Highlight function definition differently (eg: functional component def in React)
tag: [tags.definition(tags.function(tags.variableName)), tags.tagName],
class: classNameToken('definition'),
},
{
tag: tags.propertyName,
class: classNameToken('property'),
},
{
tag: [tags.literal, tags.inserted],
class: classNameToken(theme.syntax.string ? 'string' : 'static'),
},
{
tag: tags.punctuation,
class: classNameToken('punctuation'),
},
{
tag: [tags.comment, tags.quote],
class: classNameToken('comment'),
},
]);
}
function getLineDecorators(
code: string,
meta?: string
): Array<{
line: number;
className: string;
}> {
if (!meta) {
return [];
}
const linesToHighlight = getHighlightLines(meta);
const highlightedLineConfig = linesToHighlight.map((line) => {
return {
className: 'bg-github-highlight dark:bg-opacity-10',
line,
};
});
return highlightedLineConfig;
}
function getInlineDecorators(
code: string,
meta?: string
): Array<{
step: number;
line: number;
startColumn: number;
endColumn: number;
className: string;
}> {
if (!meta) {
return [];
}
const inlineHighlightLines = getInlineHighlights(meta, code);
const inlineHighlightConfig = inlineHighlightLines.map(
(line: InlineHighlight) => ({
...line,
elementAttributes: {'data-step': `${line.step}`},
className: cn(
'code-step bg-opacity-10 dark:bg-opacity-20 relative rounded px-1 py-[1.5px] border-b-[2px] border-opacity-60',
{
'bg-blue-40 border-blue-40 text-blue-60 dark:text-blue-30':
line.step === 1,
'bg-yellow-40 border-yellow-40 text-yellow-60 dark:text-yellow-30':
line.step === 2,
'bg-purple-40 border-purple-40 text-purple-60 dark:text-purple-30':
line.step === 3,
'bg-green-40 border-green-40 text-green-60 dark:text-green-30':
line.step === 4,
// TODO: Some codeblocks use up to 6 steps.
}
),
})
);
return inlineHighlightConfig;
}
/**
*
* @param meta string provided after the language in a markdown block
* @returns array of lines to highlight
* @example
* ```js {1-3,7} [[1, 1, 20, 33], [2, 4, 4, 8]] App.js active
* ...
* ```
*
* -> The meta is `{1-3,7} [[1, 1, 20, 33], [2, 4, 4, 8]] App.js active`
*/
function getHighlightLines(meta: string): number[] {
const HIGHLIGHT_REGEX = /{([\d,-]+)}/;
const parsedMeta = HIGHLIGHT_REGEX.exec(meta);
if (!parsedMeta) {
return [];
}
return rangeParser(parsedMeta[1]);
}
/**
*
* @param meta string provided after the language in a markdown block
* @returns InlineHighlight[]
* @example
* ```js {1-3,7} [[1, 1, 'count'], [2, 4, 'setCount']] App.js active
* ...
* ```
*
* -> The meta is `{1-3,7} [[1, 1, 'count', [2, 4, 'setCount']] App.js active`
*/
function getInlineHighlights(meta: string, code: string) {
const INLINE_HEIGHT_REGEX = /(\[\[.*\]\])/;
const parsedMeta = INLINE_HEIGHT_REGEX.exec(meta);
if (!parsedMeta) {
return [];
}
const lines = code.split('\n');
const encodedHighlights = JSON.parse(parsedMeta[1]);
return encodedHighlights.map(([step, lineNo, substr, fromIndex]: any[]) => {
const line = lines[lineNo - 1];
let index = line.indexOf(substr);
const lastIndex = line.lastIndexOf(substr);
if (index !== lastIndex) {
if (fromIndex === undefined) {
throw Error(
"Found '" +
substr +
"' twice. Specify fromIndex as the fourth value in the tuple."
);
}
index = line.indexOf(substr, fromIndex);
}
if (index === -1) {
throw Error("Could not find: '" + substr + "'");
}
return {
step,
line: lineNo,
startColumn: index,
endColumn: index + substr.length,
};
});
}