Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(canvas): highlight code with @pierre/highlights (#21506)

Innei5b336e1f0bf1
diff --git a/packages/canvas-runtime/package.json b/packages/canvas-runtime/package.json
index 686a7c457da..76cb029a30c 100644
--- a/packages/canvas-runtime/package.json
+++ b/packages/canvas-runtime/package.json
@@ -9,7 +9,7 @@
},
"dependencies": {
"@lobechat/canvas": "workspace:*",
- "pele": "^1.6.0",
- "shiki": "^4.4.3"
+ "@pierre/highlights": "^0.2.0",
+ "pele": "^1.6.0"
}
}
diff --git a/packages/canvas-runtime/src/addons/highlight.test.ts b/packages/canvas-runtime/src/addons/highlight.test.ts
index a1fcf639d76..6c8bd71ec05 100644
--- a/packages/canvas-runtime/src/addons/highlight.test.ts
+++ b/packages/canvas-runtime/src/addons/highlight.test.ts
@@ -1,11 +1,12 @@
import { CANVAS_CODE_LANGUAGES } from '@lobechat/canvas';
+import { isSupportedLanguage } from '@pierre/highlights';
import { describe, expect, it } from 'vitest';
-import { CODE_GRAMMARS, highlightCode } from './highlight';
+import { highlightCode } from './highlight';
describe('highlight add-on', () => {
- it('bundles a grammar for every language the component reference promises', () => {
- expect(Object.keys(CODE_GRAMMARS).sort()).toEqual([...CANVAS_CODE_LANGUAGES].sort());
+ it('supports every language the component reference promises', () => {
+ expect(CANVAS_CODE_LANGUAGES.filter((lang) => !isSupportedLanguage(lang))).toEqual([]);
});
it('colors code with theme variables and accepts common aliases', async () => {
@@ -19,7 +20,7 @@ describe('highlight add-on', () => {
it('shows an unknown language as escaped plain text', async () => {
const html = await highlightCode('a < b', 'brainfudge');
- expect(html).toContain('a &#x3C; b');
+ expect(html).toContain('a &lt; b');
expect(html).not.toMatch(/<span style="color:\s?var\(--lobe-color-success/);
});
});
diff --git a/packages/canvas-runtime/src/addons/highlight.ts b/packages/canvas-runtime/src/addons/highlight.ts
index c99daf629d2..746d2e3ceb9 100644
--- a/packages/canvas-runtime/src/addons/highlight.ts
+++ b/packages/canvas-runtime/src/addons/highlight.ts
@@ -1,86 +1,14 @@
-import type { CANVAS_CODE_LANGUAGES } from '@lobechat/canvas';
-import { ShikiLobeTheme } from '@lobehub/ui';
-import {
- createHighlighterCore,
- type HighlighterCore,
- type LanguageRegistration,
- type ThemeRegistration,
-} from 'shiki/core';
-import c from 'shiki/dist/langs/c.mjs';
-import cpp from 'shiki/dist/langs/cpp.mjs';
-import csharp from 'shiki/dist/langs/csharp.mjs';
-import css from 'shiki/dist/langs/css.mjs';
-import diff from 'shiki/dist/langs/diff.mjs';
-import dockerfile from 'shiki/dist/langs/dockerfile.mjs';
-import go from 'shiki/dist/langs/go.mjs';
-import html from 'shiki/dist/langs/html.mjs';
-import java from 'shiki/dist/langs/java.mjs';
-import javascript from 'shiki/dist/langs/javascript.mjs';
-import json from 'shiki/dist/langs/json.mjs';
-import jsx from 'shiki/dist/langs/jsx.mjs';
-import kotlin from 'shiki/dist/langs/kotlin.mjs';
-import python from 'shiki/dist/langs/python.mjs';
-import ruby from 'shiki/dist/langs/ruby.mjs';
-import rust from 'shiki/dist/langs/rust.mjs';
-import shellscript from 'shiki/dist/langs/shellscript.mjs';
-import sql from 'shiki/dist/langs/sql.mjs';
-import swift from 'shiki/dist/langs/swift.mjs';
-import toml from 'shiki/dist/langs/toml.mjs';
-import tsx from 'shiki/dist/langs/tsx.mjs';
-import typescript from 'shiki/dist/langs/typescript.mjs';
-import yaml from 'shiki/dist/langs/yaml.mjs';
-import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
+import { LobeHighlightsTheme } from '@lobehub/ui';
+import { codeToHtml, isSupportedLanguage } from '@pierre/highlights';
import { registerCanvasAddon } from './registry';
-export const CODE_GRAMMARS: Record<(typeof CANVAS_CODE_LANGUAGES)[number], LanguageRegistration[]> =
- {
- bash: shellscript,
- c,
- cpp,
- csharp,
- css,
- diff,
- dockerfile,
- go,
- html,
- java,
- javascript,
- json,
- jsx,
- kotlin,
- python,
- ruby,
- rust,
- sql,
- swift,
- toml,
- tsx,
- typescript,
- yaml,
- };
-
-const PLAIN_TEXT = 'text';
-
-const LOBE_THEME = ShikiLobeTheme as ThemeRegistration;
-
-let highlighter: Promise<HighlighterCore> | undefined;
-
-const getHighlighter = () => {
- highlighter ??= createHighlighterCore({
- engine: createJavaScriptRegexEngine({ forgiving: true }),
- langs: Object.values(CODE_GRAMMARS),
- themes: [LOBE_THEME],
- });
- return highlighter;
-};
+const decoder = new TextDecoder();
export const highlightCode = async (code: string, language?: string) => {
- const instance = await getHighlighter();
- const requested = language?.trim().toLowerCase();
- const lang =
- requested && instance.getLoadedLanguages().includes(requested) ? requested : PLAIN_TEXT;
- return instance.codeToHtml(code, { lang, theme: LOBE_THEME.name! });
+ const requested = language?.trim().toLowerCase() ?? '';
+ const lang = isSupportedLanguage(requested) ? requested : 'text';
+ return decoder.decode(codeToHtml(code, { lang, theme: LobeHighlightsTheme }));
};
if (typeof window !== 'undefined') registerCanvasAddon('highlight', { highlight: highlightCode });
diff --git a/packages/canvas-runtime/src/base.css b/packages/canvas-runtime/src/base.css
index 032efa27bad..7ac17d9e90e 100644
--- a/packages/canvas-runtime/src/base.css
+++ b/packages/canvas-runtime/src/base.css
@@ -169,7 +169,7 @@
color: var(--lobe-color-text-description);
}
- /* shiki writes the theme background on the <pre> as an inline style */
+ /* the highlighter writes the theme background on the <pre> as an inline style */
[data-lobe-canvas-code] pre {
border: 0;
border-radius: 0;
diff --git a/packages/canvas/src/preview/index.ts b/packages/canvas/src/preview/index.ts
index 6601502efb0..081cfb2be28 100644
--- a/packages/canvas/src/preview/index.ts
+++ b/packages/canvas/src/preview/index.ts
@@ -19,5 +19,5 @@ export const createCanvasPreviewDocument = (
const bootstrap = installCanvasProject
.toString()
.replaceAll(/<\/script/gi, '<' + '\\' + '/script');
- return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'"><script>(${bootstrap})(...${args});</script></head><body></body></html>`;
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'"><script>(${bootstrap})(...${args});</script></head><body></body></html>`;
};
diff --git a/packages/canvas/src/preview/install.test.ts b/packages/canvas/src/preview/install.test.ts
index 6d9f73dda4a..0ce3e0f32fa 100644
--- a/packages/canvas/src/preview/install.test.ts
+++ b/packages/canvas/src/preview/install.test.ts
@@ -28,6 +28,8 @@ it('keeps HTML and closing script tags inside the serialized bootstrap until it
expect(document.querySelectorAll('script')).toHaveLength(1);
expect(document.querySelector('h1')).toBeNull();
expect(() => new Function(document.querySelector('script')!.textContent!)).not.toThrow();
+ expect(html).toMatch(/script-src[^;]*'wasm-unsafe-eval'/);
+ expect(html).not.toContain("'unsafe-eval'");
});
it.each(['lowercase', 'uppercase'])(
@@ -76,6 +78,8 @@ it.each(['lowercase', 'uppercase'])(
const html = String(write.mock.calls[0][0]);
expect(blobs).toHaveLength(3);
expect(html).toContain('type="importmap"');
+ expect(html).toMatch(/script-src[^;]*'wasm-unsafe-eval'/);
+ expect(html).not.toContain("'unsafe-eval'");
expect(html).toContain('lobe-canvas-project/app.js');
expect(html).toContain('src="blob:null/1#icon"');
expect(html).not.toContain('href="css/app.css"');
diff --git a/packages/canvas/src/preview/install.ts b/packages/canvas/src/preview/install.ts
index 0921fbfd024..afe8e38e64c 100644
--- a/packages/canvas/src/preview/install.ts
+++ b/packages/canvas/src/preview/install.ts
@@ -129,7 +129,7 @@ export function installCanvasProject(
Object.entries(urls).map(([path, url]) => [`lobe-canvas-project/${path}`, url]),
);
const injection =
- `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'">` +
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'">` +
`<script>(${bridgeSource})();(${globalsSource})(${serialize(urls)},${serialize(page)},${serialize(owned)});</script>` +
`<script type="importmap">${serialize({ imports })}</script>` +
`<script type="module">window.dispatchEvent(new CustomEvent('lobe-canvas-project-import',{detail:(url,options)=>import(url,options)}));</script>` +