aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/highlight.ts
blob: 9d76850ec46589d0f6c6f9d50f2035efc01ce894 (plain)
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
import { toJsxRuntime } from "hast-util-to-jsx-runtime";
import { Fragment, type JSX } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { type BundledLanguage, codeToHast } from "./shiki.bundle";

export type { BundledLanguage };

// https://shiki.matsu.io/packages/next
export async function highlight(code: string, lang: BundledLanguage) {
  let out;
  try {
    out = await codeToHast(code.trimEnd(), {
      lang,
      theme: "github-light",
    });
  } catch {
    // Fallback to plaintext (no highlight).
    out = await codeToHast(code.trimEnd(), {
      lang: "text",
      theme: "github-light",
    });
  }

  return toJsxRuntime(out, {
    Fragment,
    jsx,
    jsxs,
  }) as JSX.Element;
}