-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
lazy-syntaxhighlighter.tsx
52 lines (44 loc) · 1.41 KB
/
lazy-syntaxhighlighter.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
import type { ComponentProps } from 'react';
import React, { Suspense, lazy } from 'react';
import type ReactSyntaxHighlighter from './syntaxhighlighter';
let languages: Parameters<typeof ReactSyntaxHighlighter.registerLanguage>[] = [];
let Comp: typeof ReactSyntaxHighlighter | null = null;
const LazySyntaxHighlighter = lazy(() => import('./syntaxhighlighter'));
const LazySyntaxHighlighterWithFormatter = lazy(async () => {
const [{ SyntaxHighlighter }, { formatter }] = await Promise.all([
import('./syntaxhighlighter'),
import('./formatter'),
]);
if (languages.length > 0) {
languages.forEach((args) => {
SyntaxHighlighter.registerLanguage(...args);
});
languages = [];
}
if (Comp === null) {
Comp = SyntaxHighlighter;
}
return {
default: (props: ComponentProps<typeof LazySyntaxHighlighter>) => (
<SyntaxHighlighter {...props} formatter={formatter} />
),
};
});
export const SyntaxHighlighter = (props: ComponentProps<typeof LazySyntaxHighlighter>) => (
<Suspense fallback={<div />}>
{props.format !== false ? (
<LazySyntaxHighlighterWithFormatter {...props} />
) : (
<LazySyntaxHighlighter {...props} />
)}
</Suspense>
);
SyntaxHighlighter.registerLanguage = (
...args: Parameters<typeof ReactSyntaxHighlighter.registerLanguage>
) => {
if (Comp !== null) {
Comp.registerLanguage(...args);
return;
}
languages.push(args);
};