Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(options): syntax-highlight the code block component
Elian Doran387185e83701
diff --git a/apps/client/src/widgets/react/CodeBlock.css b/apps/client/src/widgets/react/CodeBlock.cssindex b7b2acdabb..a0b66cdfab 100644--- a/apps/client/src/widgets/react/CodeBlock.css+++ b/apps/client/src/widgets/react/CodeBlock.css@@ -14,6 +14,13 @@overflow-x: auto;}+/* Only supply a background when highlighting is off. A highlighted block carries `hljs`,+ whose theme stylesheet brings its own — and that sheet is injected at runtime, so+ relying on source order to win an equal-specificity fight would be fragile. */+.code-block:not(.hljs) {+ background-color: var(--accented-background-color);+}+.code-block > code {display: block;font-variant: none;diff --git a/apps/client/src/widgets/react/CodeBlock.spec.tsx b/apps/client/src/widgets/react/CodeBlock.spec.tsxnew file mode 100644index 0000000000..62e385ebe0--- /dev/null+++ b/apps/client/src/widgets/react/CodeBlock.spec.tsx@@ -0,0 +1,86 @@+import { render } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const applySingleBlockSyntaxHighlight = vi.fn(async (_codeBlock: unknown, _normalizedMimeType: string) => {});+const isSyntaxHighlightEnabled = vi.fn(() => true);++vi.mock("../../services/syntax_highlight", () => ({+ applySingleBlockSyntaxHighlight,+ isSyntaxHighlightEnabled+}));++vi.mock("../../services/clipboard_ext", () => ({ copyTextWithToast: vi.fn() }));++// ActionButton drags in tooltips and command wiring that are irrelevant here.+vi.mock("./ActionButton", () => ({ default: () => <button class="code-block-copy" /> }));++const { default: CodeBlock } = await import("./CodeBlock");++let container: HTMLDivElement;++beforeEach(() => {+ // The component hands the <code> element to jQuery before delegating to the+ // highlighter; the identity wrapper is enough since the helper itself is mocked.+ (globalThis as unknown as { $: (el: unknown) => unknown }).$ = (el) => el;+ container = document.createElement("div");+ document.body.appendChild(container);+});++afterEach(() => {+ render(null, container);+ container.remove();+ vi.clearAllMocks();+ isSyntaxHighlightEnabled.mockReturnValue(true);+});++describe("CodeBlock", () => {+ it("renders the code as text, never as markup", () => {+ render(<CodeBlock code={"<img src=x onerror=alert(1)>"} />, container);++ const code = container.querySelector("code");+ expect(code?.textContent).toBe("<img src=x onerror=alert(1)>");+ // Rendered verbatim rather than parsed — no element was created from it.+ expect(container.querySelector("img")).toBeNull();+ });++ it("does not highlight when no MIME type is given", () => {+ render(<CodeBlock code={"{}"} />, container);+ expect(applySingleBlockSyntaxHighlight).not.toHaveBeenCalled();+ });++ it("respects the user turning syntax highlighting off", () => {+ isSyntaxHighlightEnabled.mockReturnValue(false);+ render(<CodeBlock code={"{}"} mimeType="application/json" />, container);+ expect(applySingleBlockSyntaxHighlight).not.toHaveBeenCalled();+ });++ it("highlights with the normalized MIME type when enabled", async () => {+ render(<CodeBlock code={'{"a": 1}'} mimeType="application/json" />, container);++ await vi.waitFor(() => expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledTimes(1));+ // highlight.js registers languages under the CKEditor-normalized name, so+ // "application/json" must reach it as "application-json" or nothing matches.+ expect(applySingleBlockSyntaxHighlight.mock.calls[0][1]).toBe("application-json");+ });++ it("forces the hljs class on rather than toggling it, so a re-highlight keeps colours", async () => {+ const rerender = (code: string) => render(<CodeBlock code={code} mimeType="application/json" />, container);++ rerender('{"a": 1}');+ await vi.waitFor(() => expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledTimes(1));+ expect(container.querySelector("pre")?.classList.contains("hljs")).toBe(true);++ // The underlying helper toggles the class; a second pass must not switch it off.+ rerender('{"a": 2}');+ await vi.waitFor(() => expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledTimes(2));+ expect(container.querySelector("pre")?.classList.contains("hljs")).toBe(true);+ });++ it("rewrites the plain text when the code changes", () => {+ render(<CodeBlock code={"first"} />, container);+ expect(container.querySelector("code")?.textContent).toBe("first");++ render(<CodeBlock code={"second"} />, container);+ expect(container.querySelector("code")?.textContent).toBe("second");+ });+});diff --git a/apps/client/src/widgets/react/CodeBlock.tsx b/apps/client/src/widgets/react/CodeBlock.tsxindex 9dac943978..545e4ce244 100644--- a/apps/client/src/widgets/react/CodeBlock.tsx+++ b/apps/client/src/widgets/react/CodeBlock.tsx@@ -1,12 +1,21 @@import "./CodeBlock.css";+import { normalizeMimeTypeForCKEditor } from "@triliumnext/commons";+import { useEffect, useLayoutEffect, useRef } from "preact/hooks";+import { copyTextWithToast } from "../../services/clipboard_ext";import { t } from "../../services/i18n";+import { applySingleBlockSyntaxHighlight, isSyntaxHighlightEnabled } from "../../services/syntax_highlight";import ActionButton from "./ActionButton";interface CodeBlockProps {- /** The code to display. Rendered verbatim — never HTML. */+ /** The code to display. Rendered verbatim — never interpreted as HTML. */code: string;+ /**+ * MIME type to highlight as, e.g. `application/json` or `text/x-sh`. Omit to render the+ * code unhighlighted. Highlighting is skipped when the user has turned it off for notes.+ */+ mimeType?: string;/** Shows a copy-to-clipboard button in the corner. */copyable?: boolean;/** Wraps long lines instead of scrolling horizontally. */@@ -18,16 +27,49 @@ interface CodeBlockProps {* A read-only code block styled to match the ones rendered inside text notes.** Text notes get their code blocks from CKEditor, which the jQuery helpers in- * `services/syntax_highlight` decorate after the fact. That path can't be reused from+ * `services/syntax_highlight` decorate after the fact. That path can't be driven from* Preact, so this component reproduces the same treatment — shared `--code-block-*`- * variables, the same copy affordance — for code samples rendered directly by the UI- * (options screens, dialogs). It does not syntax-highlight: these are short, static- * samples, and pulling in highlight.js for them would cost far more than it returns.+ * variables, the same copy affordance, and the same highlighter — for code rendered+ * directly by the UI (options screens, dialogs).*/-export default function CodeBlock({ code, copyable = true, wrap, className }: CodeBlockProps) {+export default function CodeBlock({ code, mimeType, copyable = true, wrap, className }: CodeBlockProps) {+ const codeRef = useRef<HTMLElement>(null);++ // The <code> subtree is deliberately left out of Preact's control: highlighting swaps+ // its innerHTML, and Preact reconciling children it no longer recognises would either+ // clobber the highlight or duplicate the text. Writing the plain code in a layout+ // effect keeps it painted before the first frame, so there is no flash of empty block.+ useLayoutEffect(() => {+ if (codeRef.current) {+ codeRef.current.textContent = code;+ }+ }, [code]);++ useEffect(() => {+ const element = codeRef.current;+ if (!element || !mimeType || !isSyntaxHighlightEnabled()) {+ return;+ }++ let cancelled = false;+ void (async () => {+ await applySingleBlockSyntaxHighlight($(element), normalizeMimeTypeForCKEditor(mimeType));+ if (cancelled) {+ // A newer render is authoritative; the layout effect above has already+ // restored the correct plain text, so drop this stale highlight.+ return;+ }+ // The helper *toggles* `hljs` on the parent, so a second pass over the same+ // element would switch the theme's colours back off. Force it on instead.+ element.parentElement?.classList.add("hljs");+ })();++ return () => { cancelled = true; };+ }, [code, mimeType]);+return (<pre className={`code-block ${wrap ? "wrap" : ""} ${className ?? ""}`}>- <code>{code}</code>+ <code ref={codeRef} />{copyable && (<ActionButtonclassName="code-block-copy"diff --git a/apps/client/src/widgets/type_widgets/options/llm.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsxindex 988069786f..c07c230f14 100644--- a/apps/client/src/widgets/type_widgets/options/llm.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx@@ -181,9 +181,9 @@ function McpSettings() {<Collapsible title={t("llm.mcp_config_title")} initiallyExpanded><p>{t("llm.mcp_config_description")}</p>- <CodeBlock code={buildMcpClientConfig(localUrl, t("llm.mcp_config_token_placeholder"))} />+ <CodeBlock mimeType="application/json" code={buildMcpClientConfig(localUrl, t("llm.mcp_config_token_placeholder"))} /><p>{t("llm.mcp_config_cli_description")}</p>- <CodeBlock code={buildMcpClientCommand(localUrl, t("llm.mcp_config_token_placeholder"))} wrap />+ <CodeBlock mimeType="text/x-sh" code={buildMcpClientCommand(localUrl, t("llm.mcp_config_token_placeholder"))} wrap /><p class="mcp-config-warning">{t("llm.mcp_config_warning")}</p></Collapsible></>diff --git a/apps/client/src/widgets/type_widgets/options/security.tsx b/apps/client/src/widgets/type_widgets/options/security.tsxindex b2c5315282..0bada48a13 100644--- a/apps/client/src/widgets/type_widgets/options/security.tsx+++ b/apps/client/src/widgets/type_widgets/options/security.tsx@@ -71,9 +71,11 @@ function ServerConfigHint({ configKey, envVar }: { configKey: string; envVar: streturn (<Collapsible title={t("security.how_to_enable")}><p>{t("security.server_config_hint")}</p>- <CodeBlock code={`[Security]\n${configKey}=true`} />+ {/* `text/x-toml` is Trilium's entry for INI-family files — it is backed by+ highlight.js's `ini` grammar, which is what config.ini actually is. */}+ <CodeBlock mimeType="text/x-toml" code={`[Security]\n${configKey}=true`} /><p>{t("security.server_env_hint")}</p>- <CodeBlock code={`${envVar}=true`} />+ <CodeBlock mimeType="text/x-sh" code={`${envVar}=true`} /></Collapsible>);}