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): mark substitutable placeholders in code blocks
Elian Dorandd75f83a8aa0
diff --git a/apps/client/src/widgets/react/CodeBlock.css b/apps/client/src/widgets/react/CodeBlock.cssindex a0b66cdfab..ea8f82662a 100644--- a/apps/client/src/widgets/react/CodeBlock.css+++ b/apps/client/src/widgets/react/CodeBlock.css@@ -29,6 +29,18 @@user-select: text;}+/* Marks a value the user has to substitute. Two selectors deep so it outranks the+ highlight.js token colour of whatever string it sits inside. The tint is mixed from+ currentColor rather than a theme variable because the backdrop here is the hljs theme's,+ which may be light or dark independently of the rest of the UI. */+.code-block .code-block-placeholder {+ padding: 0 0.2em;+ border-radius: 3px;+ outline: 1px dashed currentColor;+ outline-offset: -1px;+ background-color: color-mix(in srgb, currentColor 12%, transparent);+}+.code-block.wrap > code {white-space: pre-wrap;word-break: break-word;diff --git a/apps/client/src/widgets/react/CodeBlock.spec.tsx b/apps/client/src/widgets/react/CodeBlock.spec.tsxindex 62e385ebe0..c64d070fe4 100644--- a/apps/client/src/widgets/react/CodeBlock.spec.tsx+++ b/apps/client/src/widgets/react/CodeBlock.spec.tsx@@ -76,6 +76,31 @@ describe("CodeBlock", () => {expect(container.querySelector("pre")?.classList.contains("hljs")).toBe(true);});+ it("marks every occurrence of the placeholder without altering the code", () => {+ render(<CodeBlock code={"a TOKEN b TOKEN c"} placeholder="TOKEN" />, container);++ const marks = container.querySelectorAll(".code-block-placeholder");+ expect(marks.length).toBe(2);+ expect([...marks].map((m) => m.textContent)).toEqual(["TOKEN", "TOKEN"]);+ // Marking is purely decorative — what gets copied must still be the original.+ expect(container.querySelector("code")?.textContent).toBe("a TOKEN b TOKEN c");+ });++ it("re-marks the placeholder after highlighting rebuilds the subtree", async () => {+ // The real highlighter replaces innerHTML, wiping the marks added on first paint.+ applySingleBlockSyntaxHighlight.mockImplementationOnce(async (codeBlock: unknown) => {+ const element = codeBlock as HTMLElement;+ element.innerHTML = `<span class="hljs-string">${element.textContent}</span>`;+ });++ render(<CodeBlock code={'"Bearer TOKEN"'} mimeType="application/json" placeholder="TOKEN" />, container);++ // Nested inside the token span, which is why the CSS has to outrank hljs colours.+ await vi.waitFor(() => expect(container.querySelector(".hljs-string > .code-block-placeholder")).not.toBeNull());+ expect(container.querySelectorAll(".code-block-placeholder").length).toBe(1);+ expect(container.querySelector("code")?.textContent).toBe('"Bearer TOKEN"');+ });+it("rewrites the plain text when the code changes", () => {render(<CodeBlock code={"first"} />, container);expect(container.querySelector("code")?.textContent).toBe("first");diff --git a/apps/client/src/widgets/react/CodeBlock.tsx b/apps/client/src/widgets/react/CodeBlock.tsxindex 545e4ce244..1ecd9e8514 100644--- a/apps/client/src/widgets/react/CodeBlock.tsx+++ b/apps/client/src/widgets/react/CodeBlock.tsx@@ -16,6 +16,12 @@ interface CodeBlockProps {* code unhighlighted. Highlighting is skipped when the user has turned it off for notes.*/mimeType?: string;+ /**+ * A literal in `code` that the user is meant to substitute, e.g. `your-etapi-token`.+ * Every occurrence is marked so it reads as a blank to fill in rather than as part of+ * the snippet. Matched verbatim, not as a pattern.+ */+ placeholder?: string;/** Shows a copy-to-clipboard button in the corner. */copyable?: boolean;/** Wraps long lines instead of scrolling horizontally. */@@ -32,7 +38,7 @@ interface CodeBlockProps {* variables, the same copy affordance, and the same highlighter — for code rendered* directly by the UI (options screens, dialogs).*/-export default function CodeBlock({ code, mimeType, copyable = true, wrap, className }: CodeBlockProps) {+export default function CodeBlock({ code, mimeType, placeholder, copyable = true, wrap, className }: CodeBlockProps) {const codeRef = useRef<HTMLElement>(null);// The <code> subtree is deliberately left out of Preact's control: highlighting swaps@@ -42,8 +48,9 @@ export default function CodeBlock({ code, mimeType, copyable = true, wrap, classuseLayoutEffect(() => {if (codeRef.current) {codeRef.current.textContent = code;+ markPlaceholder(codeRef.current, placeholder);}- }, [code]);+ }, [code, placeholder]);useEffect(() => {const element = codeRef.current;@@ -62,10 +69,13 @@ export default function CodeBlock({ code, mimeType, copyable = true, wrap, class// 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");+ // Highlighting rebuilt the subtree from the raw text, discarding the marks the+ // layout effect added — so they have to be reapplied over the new tokens.+ markPlaceholder(element, placeholder);})();return () => { cancelled = true; };- }, [code, mimeType]);+ }, [code, mimeType, placeholder]);return (<pre className={`code-block ${wrap ? "wrap" : ""} ${className ?? ""}`}>@@ -84,3 +94,44 @@ export default function CodeBlock({ code, mimeType, copyable = true, wrap, class</pre>);}++/**+ * Wraps every verbatim occurrence of `placeholder` in a marker span.+ *+ * Runs over the rendered DOM rather than the source string because it has to work on the+ * highlighted output too, where the text is already split across the highlighter's token+ * spans. An occurrence straddling two of those spans is left unmarked — that only costs+ * the visual hint, so it degrades quietly instead of mangling the snippet.+ */+function markPlaceholder(root: HTMLElement, placeholder: string | undefined) {+ if (!placeholder) {+ return;+ }++ // Collected up front: splitting text nodes while the walker is still traversing them+ // would have it revisit the pieces it just created.+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const candidates: Text[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ if (node.textContent?.includes(placeholder)) {+ candidates.push(node as Text);+ }+ }++ for (const candidate of candidates) {+ let remainder: Text | null = candidate;+ while (remainder) {+ const index = remainder.data.indexOf(placeholder);+ if (index < 0) {+ break;+ }+ const match: Text = remainder.splitText(index);+ remainder = match.splitText(placeholder.length);++ const marker = document.createElement("span");+ marker.className = "code-block-placeholder";+ match.replaceWith(marker);+ marker.appendChild(match);+ }+ }+}diff --git a/apps/client/src/widgets/type_widgets/options/llm.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsxindex c07c230f14..76c0cb337b 100644--- a/apps/client/src/widgets/type_widgets/options/llm.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx@@ -134,6 +134,7 @@ function McpSettings() {const [mcpEnabled, setMcpEnabled] = useTriliumOptionBool("mcpEnabled");const [networkInfo, setNetworkInfo] = useState<NetworkAddressesResponse | null>(null);const localUrl = useMemo(() => getMcpEndpointUrl(), []);+ const tokenPlaceholder = t("llm.mcp_config_token_placeholder");// The renderer can't enumerate network interfaces itself (Node integration is// disabled on desktop), so reuse the endpoint the sync-from-desktop setup screen@@ -181,9 +182,18 @@ function McpSettings() {<Collapsible title={t("llm.mcp_config_title")} initiallyExpanded><p>{t("llm.mcp_config_description")}</p>- <CodeBlock mimeType="application/json" code={buildMcpClientConfig(localUrl, t("llm.mcp_config_token_placeholder"))} />+ <CodeBlock+ mimeType="application/json"+ code={buildMcpClientConfig(localUrl, tokenPlaceholder)}+ placeholder={tokenPlaceholder}+ /><p>{t("llm.mcp_config_cli_description")}</p>- <CodeBlock mimeType="text/x-sh" code={buildMcpClientCommand(localUrl, t("llm.mcp_config_token_placeholder"))} wrap />+ <CodeBlock+ mimeType="text/x-sh"+ code={buildMcpClientCommand(localUrl, tokenPlaceholder)}+ placeholder={tokenPlaceholder}+ wrap+ /><p class="mcp-config-warning">{t("llm.mcp_config_warning")}</p></Collapsible></>