1
1
import {
2
- highlight ,
2
+ highlight as light ,
3
3
extractAnnotations ,
4
4
Annotation ,
5
+ LANG_NAMES ,
5
6
} from "@code-hike/lighter"
7
+ import { Code } from "utils"
6
8
import { annotationsMap } from "../mdx-client/annotations"
7
9
import { CodeAnnotation } from "../smooth-code"
8
10
@@ -20,48 +22,11 @@ export async function extractLighterAnnotations(
20
22
) {
21
23
return await extractAnnotations (
22
24
codeWithAnnotations ,
23
- lang ,
25
+ warnIfUnknownLang ( lang ) ,
24
26
annotationNames
25
27
)
26
28
}
27
29
28
- export async function extractAnnotationsFromCode (
29
- codeWithAnnotations : string ,
30
- lang : string ,
31
- names ?: string [ ]
32
- ) {
33
- const { code, annotations } = await extractAnnotations (
34
- codeWithAnnotations ,
35
- lang ,
36
- names || annotationNames
37
- )
38
-
39
- const focusList = [ ] as string [ ]
40
-
41
- const codeAnnotations = [ ] as CodeAnnotation [ ]
42
-
43
- annotations . forEach ( ( { name, query, ranges } ) => {
44
- ranges . forEach ( range => {
45
- const focus = rangeString ( range )
46
- if ( name === "focus" ) {
47
- focusList . push ( focus )
48
- } else {
49
- const Component = annotationsMap [ name ]
50
- if ( Component ) {
51
- codeAnnotations . push ( {
52
- Component,
53
- focus : focus ,
54
- data : query ,
55
- } )
56
- }
57
- }
58
- } )
59
- } )
60
-
61
- return { code, annotations : codeAnnotations }
62
- }
63
-
64
- // lighter annotations to CodeAnnotations
65
30
export function parseLighterAnnotations (
66
31
annotations : LighterAnnotation [ ]
67
32
) {
@@ -102,3 +67,44 @@ function rangeString(range: Annotation["ranges"][0]) {
102
67
return `${ range . fromLineNumber } :${ range . toLineNumber } `
103
68
}
104
69
}
70
+
71
+ const warnings = new Set ( )
72
+
73
+ function warnIfUnknownLang ( lang : string ) {
74
+ if ( ! LANG_NAMES . includes ( lang ) ) {
75
+ if ( ! warnings . has ( lang ) ) {
76
+ console . warn (
77
+ "[Code Hike warning]" ,
78
+ `${ lang } isn't a valid language, no syntax highlighting will be applied.`
79
+ )
80
+ warnings . add ( lang )
81
+ }
82
+ return "text"
83
+ }
84
+ return lang
85
+ }
86
+
87
+ export async function highlight ( {
88
+ code,
89
+ lang,
90
+ theme,
91
+ } : {
92
+ code : string
93
+ lang : string
94
+ theme : any // TODO type this
95
+ } ) : Promise < Code > {
96
+ const r = await light (
97
+ code ,
98
+ warnIfUnknownLang ( lang ) ,
99
+ theme
100
+ )
101
+
102
+ const lines = r . lines . map ( line => ( {
103
+ tokens : line . map ( token => ( {
104
+ content : token . content ,
105
+ props : { style : token . style } ,
106
+ } ) ) ,
107
+ } ) )
108
+
109
+ return { lines, lang : r . lang }
110
+ }
0 commit comments