11import {
2- highlight ,
2+ highlight as light ,
33 extractAnnotations ,
44 Annotation ,
5+ LANG_NAMES ,
56} from "@code-hike/lighter"
7+ import { Code } from "utils"
68import { annotationsMap } from "../mdx-client/annotations"
79import { CodeAnnotation } from "../smooth-code"
810
@@ -20,48 +22,11 @@ export async function extractLighterAnnotations(
2022) {
2123 return await extractAnnotations (
2224 codeWithAnnotations ,
23- lang ,
25+ warnIfUnknownLang ( lang ) ,
2426 annotationNames
2527 )
2628}
2729
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
6530export function parseLighterAnnotations (
6631 annotations : LighterAnnotation [ ]
6732) {
@@ -102,3 +67,44 @@ function rangeString(range: Annotation["ranges"][0]) {
10267 return `${ range . fromLineNumber } :${ range . toLineNumber } `
10368 }
10469}
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