-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathlightweightCodeHighlighter.tsx
More file actions
316 lines (281 loc) · 10.7 KB
/
lightweightCodeHighlighter.tsx
File metadata and controls
316 lines (281 loc) · 10.7 KB
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
import { Parser } from '@lezer/common'
import { LanguageDescription, StreamLanguage } from '@codemirror/language'
import { Highlighter, highlightTree } from '@lezer/highlight'
import { languages as builtinLanguages } from '@codemirror/language-data'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { useCodeMirrorHighlighter } from '@/hooks/useCodeMirrorHighlighter'
import tailwind from '@/tailwind'
import { measure } from '@/lib/utils'
import { SourceRange } from '@/features/search'
import { CopyIconButton } from './copyIconButton'
// Define a plain text language
const plainTextLanguage = StreamLanguage.define({
token(stream) {
stream.next();
return null;
}
});
interface LightweightCodeHighlighter {
language: string;
children: string;
/* 1-based highlight ranges */
highlightRanges?: SourceRange[];
lineNumbers?: boolean;
/* 1-based line number offset */
lineNumbersOffset?: number;
renderWhitespace?: boolean;
isCopyButtonVisible?: boolean;
}
// The maximum number of characters per line that we will display in the preview.
const MAX_NUMBER_OF_CHARACTER_PER_LINE = 1000;
/**
* Lightweight code highlighter that uses the Lezer parser to highlight code.
* This is helpful in scenarios where we need to highlight a ton of code snippets
* (e.g., code nav, search results, etc)., but can't use the full-blown CodeMirror
* editor because of perf issues.
*
* Inspired by: https://github.com/craftzdog/react-codemirror-runmode
*/
export const LightweightCodeHighlighter = memo<LightweightCodeHighlighter>((props: LightweightCodeHighlighter) => {
const {
language,
children: code,
highlightRanges,
lineNumbers = false,
lineNumbersOffset = 1,
renderWhitespace = false,
isCopyButtonVisible = false,
} = props;
const unhighlightedLines = useMemo(() => {
return code.trimEnd().split('\n');
}, [code]);
const isFileTooLargeToDisplay = useMemo(() => {
return unhighlightedLines.some(line => line.length > MAX_NUMBER_OF_CHARACTER_PER_LINE);
}, [unhighlightedLines]);
const [highlightedLines, setHighlightedLines] = useState<React.ReactNode[] | null>(null);
const highlightStyle = useCodeMirrorHighlighter();
useEffect(() => {
if (isFileTooLargeToDisplay) {
return;
}
measure(() => Promise.all(
unhighlightedLines
.map(async (line, index) => {
const lineNumber = index + lineNumbersOffset;
// @todo: we will need to handle the case where a range spans multiple lines.
const ranges = highlightRanges?.filter(range => {
return range.start.lineNumber === lineNumber || range.end.lineNumber === lineNumber;
}).map(range => ({
from: range.start.column - 1,
to: range.end.column - 1,
}));
const snippets = await highlightCode(
language,
line,
highlightStyle,
ranges,
(text: string, style: string | null, from: number) => {
return (
<span
key={from}
className={`${style || ''}`}
>
{text}
</span>
)
}
);
return <span key={index}>{snippets}</span>
})
).then(highlightedLines => {
setHighlightedLines(highlightedLines);
}), 'highlightCode', /* outputLog = */ false);
}, [
language,
code,
highlightRanges,
highlightStyle,
unhighlightedLines,
lineNumbersOffset,
isFileTooLargeToDisplay,
]);
const onCopy = useCallback(() => {
try {
navigator.clipboard.writeText(code);
return true;
} catch {
return false;
}
}, [code]);
const lineCount = (highlightedLines ?? unhighlightedLines).length + lineNumbersOffset;
const lineNumberDigits = String(lineCount).length;
const lineNumberWidth = `${lineNumberDigits + 2}ch`; // +2 for padding
if (isFileTooLargeToDisplay) {
return (
<div className="font-mono text-sm px-2">
File too large to display in preview.
</div>
);
}
return (
<div className="relative group">
{isCopyButtonVisible && (
<CopyIconButton
onCopy={onCopy}
className="absolute top-1 right-1 z-10 opacity-0 group-hover:opacity-100 transition-opacity group-hover:bg-background"
/>
)}
<div
style={{
fontFamily: tailwind.theme.fontFamily.editor,
fontSize: tailwind.theme.fontSize.editor,
whiteSpace: renderWhitespace ? 'pre-wrap' : 'none',
wordBreak: 'break-all',
}}
>
{(highlightedLines ?? unhighlightedLines).map((line, index) => (
<div
key={index}
className="flex"
>
{lineNumbers && (
<span
style={{
width: lineNumberWidth,
minWidth: lineNumberWidth,
display: 'inline-block',
textAlign: 'left',
paddingLeft: '5px',
userSelect: 'none',
WebkitUserSelect: 'none',
fontFamily: tailwind.theme.fontFamily.editor,
color: tailwind.theme.colors.editor.gutterForeground,
}}
>
{index + lineNumbersOffset}
</span>
)}
<span
style={{
flex: 1,
paddingLeft: '6px',
paddingRight: '2px',
}}
>
{line}
</span>
</div>
))}
</div>
</div>
)
})
LightweightCodeHighlighter.displayName = 'LightweightCodeHighlighter';
async function getCodeParser(
languageName: string,
): Promise<Parser> {
if (languageName) {
const parser = await (async () => {
const found = LanguageDescription.matchLanguageName(
builtinLanguages,
languageName,
true
);
if (!found) {
return null;
}
if (!found.support) {
await found.load();
}
return found.support ? found.support.language.parser : null;
})();
if (parser) {
return parser;
}
}
return plainTextLanguage.parser;
}
async function highlightCode<Output>(
languageName: string,
input: string,
highlighter: Highlighter,
highlightRanges: { from: number, to: number }[] = [],
callback: (
text: string,
style: string | null,
from: number,
to: number
) => Output,
): Promise<Output[]> {
const parser = await getCodeParser(languageName);
/**
* Converts a range to a series of highlighted subranges.
*/
const convertRangeToHighlightedSubranges = (
from: number,
to: number,
classes: string | null,
cb: (from: number, to: number, classes: string | null) => void,
) => {
type HighlightRange = {
from: number,
to: number,
isHighlighted: boolean,
}
const highlightClasses = classes ? `${classes} searchMatch-selected` : 'searchMatch-selected';
let currentRange: HighlightRange | null = null;
for (let i = from; i < to; i++) {
const isHighlighted = isIndexHighlighted(i, highlightRanges);
if (currentRange) {
if (currentRange.isHighlighted === isHighlighted) {
currentRange.to = i + 1;
} else {
cb(
currentRange.from,
currentRange.to,
currentRange.isHighlighted ? highlightClasses : classes,
)
currentRange = { from: i, to: i + 1, isHighlighted };
}
} else {
currentRange = { from: i, to: i + 1, isHighlighted };
}
}
if (currentRange) {
cb(
currentRange.from,
currentRange.to,
currentRange.isHighlighted ? highlightClasses : classes,
)
}
}
const tree = parser.parse(input)
const output: Array<Output> = [];
let pos = 0;
highlightTree(tree, highlighter, (from, to, classes) => {
// `highlightTree` only calls this callback when at least one style/class
// is applied to the text (i.e., `classes` is not empty). This means that
// any unstyled regions will be skipped (e.g., whitespace, `=`. `;`. etc).
// This check ensures that we process these unstyled regions as well.
// @see: https://discuss.codemirror.net/t/static-highlighting-using-cm-v6/3420/2
if (from > pos) {
convertRangeToHighlightedSubranges(pos, from, null, (from, to, classes) => {
output.push(callback(input.slice(from, to), classes, from, to));
})
}
convertRangeToHighlightedSubranges(from, to, classes, (from, to, classes) => {
output.push(callback(input.slice(from, to), classes, from, to));
})
pos = to;
});
// Process any remaining unstyled regions.
if (pos != tree.length) {
convertRangeToHighlightedSubranges(pos, tree.length, null, (from, to, classes) => {
output.push(callback(input.slice(from, to), classes, from, to));
})
}
return output;
}
const isIndexHighlighted = (index: number, ranges: { from: number, to: number }[]) => {
return ranges.some(range => index >= range.from && index < range.to);
}