| 1 | import pierreDark from "@pierre/theme/pierre-dark"; |
| 2 | import pierreLight from "@pierre/theme/pierre-light |
| 3 | import { |
| 4 | createBundledHighlighter, |
| 5 | createSingletonShorthands, |
| 6 | guessEmbeddedLanguages, |
| 7 | type ThemeRegistrationRaw, |
| 8 | } from "shiki/core"; |
| 9 | import { createJavaScriptRegexEngine } |
| 10 | import { bundledLanguages, type |
| 11 | import { bundledThemes } |
| 12 | |
| 13 | import { APP_THEME_IDS, APP_THEMES |
| 14 | |
| 15 | // the pierre themes ship as frozen TextMate objects, which shiki loads and caches by their own `name`; the rest are bundled names. keys line up with the `--shiki-<id>` selectors in globals.css. |
| 16 | const THEMES = Object |
| 17 | APP_THEMES.map((t |
| 18 | t.id, |
| 19 | t.id === |
| 20 | ? (pierreLight as |
| 21 | : t.id |
| 22 | ? (pierreDark as |
| 23 | : t.shiki, |
| 24 | ]), |
| 25 | ); |
| 26 | |
| 27 | // The JavaScript engine spares the browser the oniguruma wasm download. Its default target mis-tokenizes TypeScript in JavaScriptCore, so Safari would; ES2018 runs the same everywhere. `forgiving` skips the rare grammar pattern it cannot run instead of failing the whole highlight. |
| 28 | const { codeToTokens } |
| 29 | createBundledHighlighter({ |
| 30 | langs: bundledLanguages, |
| 31 | themes: bundledThemes, |
| 32 | engine: () => |
| 33 | createJavaScriptRegexEngine({ target: |
| 34 | }), |
| 35 | { guessEmbeddedLanguages }, |
| 36 | ); |
| 37 | |
| 38 | const LANGUAGE_BY_NAME: Record |
| 39 | dockerfile: "docker", |
| 40 | makefile: "make", |
| 41 | gemfile: "ruby", |
| 42 | rakefile: "ruby", |
| 43 | }; |
| 44 | |
| 45 | function languageFor(filename: |
| 46 | const name = |
| 47 | if (name in |
| 48 | |
| 49 | const extension = |
| 50 | return extension in |
| 51 | ? (extension as |
| 52 | : "text"; |
| 53 | } |
| 54 | |
| 55 | /** Tokens per line, coloured for every theme in `themeIds` at once. Render them inside `[data-shiki]`, which picks the active theme's colour. */ |
| 56 | export async function highlightLines |
| 57 | code: string, |
| 58 | filename: string, |
| 59 | themeIds = APP_THEME_IDS, |
| 60 | ) { |
| 61 | const { tokens |
| 62 | lang: languageFor(filename |
| 63 | themes: Object.fromEntries |
| 64 | defaultColor: false, |
| 65 | }); |
| 66 | return tokens; |
| 67 | } |