Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): register the enabled languages before highlighting

Elian Doran38a0b0e11579
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index 39cdd40276..698de35520 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -39,8 +39,8 @@ class="image">
<td>
<ul>
<li>Table of contents.</li>
- <li>Syntax highlight of code blocks, provided a language is selected (does
- not work if “Auto-detected” is enabled).</li>
+ <li>Syntax highlight of code blocks. The language is detected automatically,
+ among the ones enabled in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Code Notes</em>.</li>
<li>Rendering for math equations.</li>
<li><a href="#root/_help_nBAXQFj20hS1">Including notes</a> (only if the included
notes are also shared).</li>
diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.ts
index 09f0edc2d5..745f12607d 100644
--- a/apps/server/src/share/routes.ts
+++ b/apps/server/src/share/routes.ts
@@ -1,4 +1,4 @@
-import { getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest } from "@triliumnext/core/src/share/index.js";
+import { ensureShareHighlighting, getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest } from "@triliumnext/core/src/share/index.js";
import type { Request, Response, Router } from "express";
import { registerShareProvider } from "./share_provider.js";
@@ -8,7 +8,8 @@ function register(router: Router) {
registerShareProvider();
for (const route of getShareRoutes()) {
- router.get(route.path, (req, res) => {
+ router.get(route.path, async (req, res) => {
+ await ensureShareHighlighting();
send(res, handleShareRequest(route, toShareRequest(req)));
});
}
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index e807c0e51d..38e68744b7 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -430,6 +430,7 @@ async function dispatchShare(path: ShareRoutePath, req: BrowserRequest) {
]);
registerShareProvider();
+ await share.ensureShareHighlighting();
/* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */
const headers = req.headers ?? {};
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 69082c3db1..1c1807b858 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -32,7 +32,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tbody>
<tr>
<th><a class="reference-link" href="../Note%20Types/Text.md">Text</a></th>
- <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, provided a language is selected (does not work if “Auto-detected” is enabled).</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li></ul></td>
+ <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks. The language is detected automatically, among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li></ul></td>
<td><ul><li>Inline Mermaid diagrams are not rendered.</li></ul></td>
</tr>
<tr>
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index 39d7c57a31..1ea0bbe365 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -49,6 +49,11 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
zipExportOptions
};
+ if (format === "share") {
+ const { ensureShareHighlighting } = await import("../../share/index.js");
+ await ensureShareHighlighting();
+ }
+
return getZipExportProviderFactory()(format, providerData);
}
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index a1668b7110..da3e972ac9 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -3,10 +3,11 @@ import ejs from "ejs";
import { parse } from "node-html-parser";
import { describe, expect, it, vi } from "vitest";
+import options from "../services/options.js";
import * as sanitize from "../services/sanitizer.js";
import * as utils from "../services/utils/index.js";
import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";
-import { getContent, readShareTemplate, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";
+import { ensureShareHighlighting, getContent, getMimeTypesForOption, readShareTemplate, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";
import type SNote from "./shaca/entities/snote.js";
import shaca from "./shaca/shaca.js";
import shareRoot from "./share_root.js";
@@ -251,7 +252,8 @@ describe("content_renderer", () => {
expect(result.content).toContain("<p>After</p>");
});
- it("handles syntax highlight for code blocks with escaped syntax", () => {
+ it("handles syntax highlight for code blocks with escaped syntax", async () => {
+ await ensureShareHighlighting();
const note = buildShareNote({
id: "note",
content: trimIndentation`\
@@ -689,6 +691,39 @@ describe("content_renderer", () => {
});
});
+ describe("ensureShareHighlighting", () => {
+ it("registers once per value of codeNotesMimeTypes", async () => {
+ const getOption = vi.spyOn(options, "getOptionOrNull");
+
+ getOption.mockReturnValue(JSON.stringify([ "text/x-python" ]));
+ const first = ensureShareHighlighting();
+ expect(ensureShareHighlighting()).toBe(first);
+ await first;
+
+ getOption.mockReturnValue(JSON.stringify([ "text/x-go" ]));
+ expect(ensureShareHighlighting()).not.toBe(first);
+
+ getOption.mockRestore();
+ });
+ });
+
+ describe("getMimeTypesForOption", () => {
+ const enabledMimes = (optionValue: string | null) => getMimeTypesForOption(optionValue)
+ .filter((mt) => mt.enabled)
+ .map((mt) => mt.mime);
+
+ it("enables the listed MIME types plus text/plain", () => {
+ expect(enabledMimes(JSON.stringify([ "text/x-python", null ])))
+ .toStrictEqual([ "text/plain", "text/x-python" ]);
+ });
+
+ it("falls back to the default MIME types when the option is missing", () => {
+ const enabled = enabledMimes(null);
+ expect(enabled).toContain("text/x-python");
+ expect(enabled).not.toContain("text/x-cobol");
+ });
+ });
+
describe("Share index", () => {
it("points each index entry at the child's shareId, whatever characters it carries", () => {
buildShareNote({
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 0d82799e86..bd60470be9 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -1,7 +1,7 @@
-import { extractYouTubeVideoId, isHttpUrl, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
+import { extractYouTubeVideoId, isHttpUrl, type MimeType, MIME_TYPES_DICT, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
-import { highlightAuto } from "@triliumnext/highlightjs";
+import { ensureMimeTypes, highlightAuto } from "@triliumnext/highlightjs";
import ejs from "ejs";
import escapeHtml from "escape-html";
import { t } from "i18next";
@@ -703,6 +703,46 @@ export function shouldSyntaxHighlight(code: string) {
return true;
}
+let registeredMimeTypesOption: string | null = null;
+let pendingRegistration: Promise<void> | null = null;
+
+/**
+ * Registers the highlight.js languages enabled in the `codeNotesMimeTypes` option, which are the
+ * only ones `highlightAuto` considers. The renderer is synchronous, so callers await this before
+ * rendering a share page or a share-theme export.
+ */
+export function ensureShareHighlighting(): Promise<void> {
+ const optionValue = options.getOptionOrNull("codeNotesMimeTypes");
+ if (pendingRegistration && optionValue === registeredMimeTypesOption) {
+ return pendingRegistration;
+ }
+
+ registeredMimeTypesOption = optionValue;
+ pendingRegistration = Promise.resolve()
+ .then(() => ensureMimeTypes(getMimeTypesForOption(optionValue)))
+ .catch((e: unknown) => {
+ getLog().error(`Unable to register the languages for syntax highlighting: ${e}`);
+ pendingRegistration = null;
+ });
+ return pendingRegistration;
+}
+
+/**
+ * Returns every MIME type in `MIME_TYPES_DICT`, enabled when the `codeNotesMimeTypes` option value
+ * lists it. Mirrors `getMimeTypes()` in the client: a missing option falls back to the defaults,
+ * and `text/plain` is always enabled.
+ */
+export function getMimeTypesForOption(optionValue: string | null): MimeType[] {
+ const enabledMimes: (string | null)[] = optionValue
+ ? JSON.parse(optionValue)
+ : MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);
+
+ return MIME_TYPES_DICT.map((mt) => ({
+ ...mt,
+ enabled: enabledMimes.includes(mt.mime) || mt.mime === "text/plain"
+ }));
+}
+
/**
* Renders a code note.
*/
diff --git a/packages/trilium-core/src/share/index.ts b/packages/trilium-core/src/share/index.ts
index e6dc6a065c..381124819e 100644
--- a/packages/trilium-core/src/share/index.ts
+++ b/packages/trilium-core/src/share/index.ts
@@ -6,7 +6,7 @@
* dynamic import, which only defers its cost — EJS, the share theme and the syntax highlighter —
* while nothing in the eager graph imports it.
*/
-export { assetUrlFragment, readShareTemplate, renderNoteContent, renderNoteForExport } from "./content_renderer.js";
+export { assetUrlFragment, ensureShareHighlighting, readShareTemplate, renderNoteContent, renderNoteForExport } from "./content_renderer.js";
export { getShareRoute, getShareRoutes, handleShareRequest, isVisibleInShareTree, type ShareReply, type ShareRequest, type ShareRoute } from "./handlers.js";
export { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";
export { initShare, isShareReady, type ShareProvider, type ShareSql } from "./share_provider.js";