@@ -3,6 +3,7 @@ import terminalLink from "terminal-link";
33import terminalImage from "terminal-image" ;
44import got from "got" ;
55import { Resvg } from "@resvg/resvg-js" ;
6+ import { FontStyle } from "@shikijs/vscode-textmate" ;
67import * as Shiki from "shiki" ;
78
89let state = [ ] ; // global var
@@ -166,6 +167,44 @@ function heading(token) {
166167 return builtString ;
167168}
168169
170+ export async function codeBlock ( token ) {
171+ if ( ! token . type . match ( / f e n c e | c o d e _ b l o c k / ) )
172+ throw new Error ( "WRONG TOKEN HOW IS THIS DEV SO STUPID" ) ;
173+ if (
174+ Object . keys ( Shiki . bundledLanguages ) . includes ( token . info ) ||
175+ Object . keys ( Shiki . bundledLanguagesAlias ) . includes ( token . info )
176+ ) {
177+ const shikiTokens = await Shiki . codeToTokens ( token . content , {
178+ lang : token . info ,
179+ theme : "github-dark" ,
180+ } ) ;
181+ const stylizedCodeArr = [ ] ;
182+ for ( let line of shikiTokens . tokens ) {
183+ let styledTokens = [ ] ;
184+ for ( let token of line ) {
185+ let temp = Chalk . hex ( token . color ) ( token . content ) ;
186+ if ( token . color & FontStyle . Bold ) temp = Chalk . bold ( temp ) ;
187+ if ( token . color & FontStyle . Italic ) temp = Chalk . italic ( temp ) ;
188+ if ( token . color & FontStyle . Underline ) temp = Chalk . underline ( temp ) ;
189+ if ( token . color & FontStyle . Strikethrough )
190+ temp = Chalk . strikethrough ( temp ) ;
191+ styledTokens . push ( temp ) ;
192+ }
193+ stylizedCodeArr . push ( styledTokens . join ( "" ) ) ;
194+ }
195+ const code = {
196+ code : stylizedCodeArr . join ( "\n" ) ,
197+ language : shikiTokens ? shikiTokens . grammarState . lang : "plain" ,
198+ } ;
199+ return code ;
200+ } else {
201+ return {
202+ code : token . content ,
203+ language : token . info !== "" ? token . info : "plain" ,
204+ } ;
205+ }
206+ }
207+
169208export default async function stylize ( input ) {
170209 // input is an array returned by `parse()` in `parse-input.js`
171210 const output = [ ] ;
@@ -187,6 +226,8 @@ export default async function stylize(input) {
187226 if ( input [ index ] === "inline" ) {
188227 push . content = heading ( input [ index ] ) ;
189228 }
229+ index ++ ;
230+ if ( input [ index ] . type === "heading_close" ) state . pop ( ) ;
190231 }
191232
192233 // PARAGRAPH
@@ -202,6 +243,12 @@ export default async function stylize(input) {
202243 if ( input [ index ] . type === "paragraph_close" ) state . pop ( ) ;
203244 }
204245
246+ if ( i . type === "fence" || i . type === "code_block" ) {
247+ state . push ( "fence" ) ;
248+ push . type = "codeBlock" ;
249+ push . content = await codeBlock ( i ) ;
250+ }
251+
205252 // no more! push the `push` object to the output array
206253 output . push ( push ) ;
207254 index ++ ;
0 commit comments