Skip to content

Build your personal knowledge base with Trilium Notes

client/backend log: allow notes use the custom highlighter as well

Adorian Doran5e9c05eeaa7b
diff --git a/apps/client/src/services/mime_types.ts b/apps/client/src/services/mime_types.ts
index 3b72c531ca..96f62fbff0 100644
--- a/apps/client/src/services/mime_types.ts
+++ b/apps/client/src/services/mime_types.ts
@@ -1,6 +1,13 @@
-import { normalizeMimeTypeForCKEditor, type MimeType, MIME_TYPE_AUTO, MIME_TYPES_DICT } from "@triliumnext/commons";
+import { normalizeMimeTypeForCKEditor, type MimeType, MIME_TYPE_AUTO, MIME_TYPE_TRILIUM_LOG, MIME_TYPES_DICT } from "@triliumnext/commons";
+import { t } from "./i18n.js";
import options from "./options.js";
+// Titles that are descriptive names rather than language identifiers, so they get localized here
+// (the shared MIME dict in commons has no access to the client's i18n).
+const TRANSLATED_TITLES: Record<string, string> = {
+ [MIME_TYPE_TRILIUM_LOG]: "code_mime_types.trilium_log"
+};
+
let mimeTypes: MimeType[] | null = null;
function loadMimeTypes() {
@@ -10,6 +17,11 @@ function loadMimeTypes() {
for (const mt of mimeTypes) {
mt.enabled = enabledMimeTypes.includes(mt.mime) || mt.mime === "text/plain"; // text/plain is always enabled
+
+ const titleKey = TRANSLATED_TITLES[mt.mime];
+ if (titleKey) {
+ mt.title = t(titleKey);
+ }
}
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d625fd3640..2e015c3f5a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1507,7 +1507,8 @@
"title": "Available MIME types in the dropdown",
"tooltip_syntax_highlighting": "Syntax highlighting",
"tooltip_code_block_syntax": "Code blocks in Text notes",
- "tooltip_code_note_syntax": "Code notes"
+ "tooltip_code_note_syntax": "Code notes",
+ "trilium_log": "Trilium Log"
},
"vim_key_bindings": {
"use_vim_keybindings_in_code_notes": "Vim keybindings",
diff --git a/apps/client/src/widgets/type_widgets/code/BackendLog.tsx b/apps/client/src/widgets/type_widgets/code/BackendLog.tsx
index 4724d558e9..aa0c71bbd4 100644
--- a/apps/client/src/widgets/type_widgets/code/BackendLog.tsx
+++ b/apps/client/src/widgets/type_widgets/code/BackendLog.tsx
@@ -1,6 +1,7 @@
import "./code.css";
-import CodeMirror, { triliumLogHighlighter } from "@triliumnext/codemirror";
+import { MIME_TYPE_TRILIUM_LOG } from "@triliumnext/commons";
+import CodeMirror from "@triliumnext/codemirror";
import { useEffect, useRef, useState } from "preact/hooks";
import server from "../../../services/server";
@@ -48,10 +49,9 @@ export default function BackendLog({ ntxId, parentComponent }: TypeWidgetProps)
editorRef={editorRef}
ntxId={ntxId} parentComponent={parentComponent}
content={content ?? ""}
- mime="text/plain"
+ mime={MIME_TYPE_TRILIUM_LOG}
readOnly
preferPerformance
- onInitialized={() => editorRef.current?.setNamedExtension("triliumLogHighlighter", triliumLogHighlighter)}
{...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
/>
</div>
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index 6c5d960f16..72cd651355 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -39,6 +39,9 @@ export interface EditableCodeProps extends TypeWidgetProps, Omit<CodeEditorProps
export function ReadOnlyCode({ note, viewScope, ntxId, parentComponent, editorRef }: TypeWidgetProps & { editorRef?: Ref<VanillaCodeMirror> }) {
const [ content, setContent ] = useState("");
const blob = useNoteBlob(note);
+ // Read reactively so switching the language from the dropdown re-highlights live, rather than
+ // only after the note is reloaded (unlike the editable view, read-only has no edits to trigger it).
+ const mime = useNoteProperty(note, "mime");
const [ noteTabWidth ] = useNoteLabelInt(note, "tabWidth");
const [ noteUseTabs ] = useNoteLabelOptionalBool(note, "indentWithTabs");
const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
@@ -60,7 +63,7 @@ export function ReadOnlyCode({ note, viewScope, ntxId, parentComponent, editorRe
editorRef={editorRef}
className="note-detail-readonly-code-content"
content={content}
- mime={note.mime}
+ mime={mime ?? "text/plain"}
readOnly
{...(noteTabWidth != null && { indentSize: noteTabWidth })}
{...(noteUseTabs != null && { useTabs: noteUseTabs })}
diff --git a/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
new file mode 100644
index 0000000000..6eb5ef0e15
--- /dev/null
+++ b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
@@ -0,0 +1,94 @@
+import { Compartment, EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { describe, expect, it } from "vitest";
+
+import { triliumLogHighlighter } from "./trilium_log_highlighter.js";
+
+interface DecorationSpan {
+ from: number;
+ to: number;
+ class: string;
+}
+
+describe("triliumLogHighlighter", () => {
+ it("applies decorations the instant it enters the config (no edit/scroll needed)", () => {
+ // Mirrors switching a code note's MIME to text/x-trilium-log: the highlighter is added to an
+ // already-built editor state via a compartment reconfigure. Because it is a StateField, the
+ // decorations must be present in the resulting state synchronously — a view plugin would not
+ // paint until the next update.
+ const compartment = new Compartment();
+ const doc = "18:09:46.317 304 GET /api/notes/x/blob with 9911 bytes took 1ms";
+ const before = EditorState.create({ doc, extensions: [ compartment.of([]) ] });
+ expect(decorationsOf(before)).toHaveLength(0);
+
+ const after = before.update({ effects: compartment.reconfigure(triliumLogHighlighter) }).state;
+ expect(decorationsOf(after).length).toBeGreaterThan(0);
+ });
+
+ it("highlights an HTTP request line: timestamp, status class, verb and URL", () => {
+ const doc = "18:09:46.317 304 GET /api/notes/x/blob with 9911 bytes took 1ms";
+ const classes = classesOf(doc);
+
+ expect(classes).toContain("cm-log-http"); // whole-line tint
+ expect(classes).toContain("cm-log-timestamp");
+ expect(classes).toContain("cm-log-status cm-log-status-3xx");
+ expect(classes).toContain("cm-log-verb");
+ expect(classes).toContain("cm-log-url");
+
+ // The URL span covers exactly `/api/notes/x/blob`.
+ const url = decorationsOf(state(doc)).find((d) => d.class === "cm-log-url");
+ expect(url && doc.slice(url.from, url.to)).toBe("/api/notes/x/blob");
+ });
+
+ it("colours the status by class family", () => {
+ expect(classesOf("18:18:38.904 204 PUT /api/options with 0 bytes took 2ms"))
+ .toContain("cm-log-status cm-log-status-2xx");
+ expect(classesOf("18:18:38.904 503 GET /api/x with 0 bytes took 2ms"))
+ .toContain("cm-log-status cm-log-status-5xx");
+ });
+
+ it("colours an error line and its timestamp-less continuation lines", () => {
+ const doc = [
+ "17:34:08.519 JS Error: Uncaught error: boom",
+ " at foo (bar.ts:1:2)",
+ " at baz (qux.ts:3:4)",
+ "18:46:03.781 304 GET /api/options with 359 bytes took 4ms"
+ ].join("\n");
+ const errorLines = decorationsOf(state(doc)).filter((d) => d.class === "cm-log-error");
+
+ // The header line plus its two continuation lines are all decorated; the following HTTP
+ // request line is not.
+ const lineStarts = errorLines.filter((d) => d.from === d.to).map((d) => d.from);
+ expect(lineStarts).toHaveLength(3);
+ expect(classesOf(doc)).toContain("cm-log-http");
+ });
+
+ it("recognises JS Info lines and leaves plain lines with only a timestamp", () => {
+ expect(classesOf("17:34:08.519 JS Info: something happened")).toContain("cm-log-info");
+
+ const plain = classesOf("18:18:40.077 Slow query took 78ms: SELECT 1");
+ expect(plain).toEqual([ "cm-log-timestamp" ]);
+ });
+});
+
+function state(doc: string): EditorState {
+ return EditorState.create({ doc, extensions: [ triliumLogHighlighter ] });
+}
+
+/** All decoration ranges contributed to the view's decoration facet, in document order. */
+function decorationsOf(editorState: EditorState): DecorationSpan[] {
+ const spans: DecorationSpan[] = [];
+ for (const set of editorState.facet(EditorView.decorations)) {
+ if (typeof set === "function") continue; // plugin-provided sources (none here)
+ const iter = set.iter();
+ while (iter.value) {
+ spans.push({ from: iter.from, to: iter.to, class: iter.value.spec.class });
+ iter.next();
+ }
+ }
+ return spans;
+}
+
+function classesOf(doc: string): string[] {
+ return decorationsOf(state(doc)).map((d) => d.class);
+}
diff --git a/packages/codemirror/src/extensions/trilium_log_highlighter.ts b/packages/codemirror/src/extensions/trilium_log_highlighter.ts
index d88179271f..3be1c604b3 100644
--- a/packages/codemirror/src/extensions/trilium_log_highlighter.ts
+++ b/packages/codemirror/src/extensions/trilium_log_highlighter.ts
@@ -1,11 +1,14 @@
-import { RangeSetBuilder, type Extension, type Text } from "@codemirror/state";
-import { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
+import { type EditorState, type Extension, RangeSetBuilder, StateField } from "@codemirror/state";
+import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
/**
* Lightweight regex highlighter for the Trilium backend log. Each log entry is a single line
- * beginning with a `HH:MM:SS.mmm` timestamp; decorations are computed only over the visible
- * viewport, so this stays cheap even on very large logs (and is unaffected by `preferPerformance`,
- * which only disables the language-mode syntax highlighting).
+ * beginning with a `HH:MM:SS.mmm` timestamp. The decorations live in a {@link StateField} (rather
+ * than a view plugin) so they are applied deterministically the instant the extension enters the
+ * configuration — e.g. when a code note is switched to the `text/x-trilium-log` MIME type — instead
+ * of only after the next edit or scroll (a dynamically added view plugin doesn't paint until the
+ * following update). The whole document is scanned top-to-bottom, which also lets the error/info
+ * block state carry across continuation lines without a separate backwards scan.
*
* Recognised entries:
* - the leading timestamp (muted, on every entry)
@@ -53,39 +56,28 @@ const logHighlightTheme = EditorView.baseTheme({
".cm-log-info": { color: "var(--log-info-color, inherit)" }
});
-const logHighlightPlugin = ViewPlugin.fromClass(class {
- decorations: DecorationSet;
-
- constructor(view: EditorView) {
- this.decorations = buildLogDecorations(view);
- }
-
- update(update: ViewUpdate) {
- if (update.docChanged || update.viewportChanged) {
- this.decorations = buildLogDecorations(update.view);
- }
- }
-}, {
- decorations: (plugin) => plugin.decorations
+const logHighlightField = StateField.define<DecorationSet>({
+ create(state) {
+ return buildLogDecorations(state);
+ },
+ update(decorations, tr) {
+ return tr.docChanged ? buildLogDecorations(tr.state) : decorations;
+ },
+ provide: (field) => EditorView.decorations.from(field)
});
-/** The extension to register on the backend-log editor (e.g. via `setNamedExtension`). */
-export const triliumLogHighlighter: Extension = [ logHighlightPlugin, logHighlightTheme ];
+/** The extension to register on the backend-log editor (e.g. via a `text/x-trilium-log` MIME type). */
+export const triliumLogHighlighter: Extension = [ logHighlightField, logHighlightTheme ];
-function buildLogDecorations(view: EditorView): DecorationSet {
+function buildLogDecorations(state: EditorState): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
- const doc = view.state.doc;
-
- for (const { from, to } of view.visibleRanges) {
- // Continuation lines belong to the nearest preceding timestamped line, which may be
- // scrolled above the viewport — seed the state by scanning backwards from the top line.
- let blockLine = blockLineAtStart(doc, doc.lineAt(from).number);
- let pos = from;
- while (pos <= to) {
- const line = doc.lineAt(pos);
- blockLine = decorateLine(builder, line, blockLine);
- pos = line.to + 1;
- }
+ const doc = state.doc;
+
+ // A single top-to-bottom pass keeps the error/info block state (used to colour continuation
+ // lines) flowing naturally across lines.
+ let blockLine: Decoration | null = null;
+ for (let n = 1; n <= doc.lines; n++) {
+ blockLine = decorateLine(builder, doc.line(n), blockLine);
}
return builder.finish();
@@ -144,19 +136,3 @@ function decorateLine(builder: RangeSetBuilder<Decoration>, line: { from: number
return newBlockLine;
}
-
-/**
- * Walks backwards from the line above `lineNumber` to the nearest timestamped line and returns the
- * block decoration `lineNumber` starts inside (or null). The scan is capped so a pathologically long
- * block near the top of the viewport can't stall rendering.
- */
-function blockLineAtStart(doc: Text, lineNumber: number): Decoration | null {
- const MAX_SCAN = 1000;
- for (let n = lineNumber - 1, steps = 0; n >= 1 && steps < MAX_SCAN; n--, steps++) {
- const text = doc.line(n).text;
- if (TIMESTAMP.test(text)) {
- return blockLineFor(text);
- }
- }
- return null;
-}
diff --git a/packages/codemirror/src/syntax_highlighting.ts b/packages/codemirror/src/syntax_highlighting.ts
index 032b4f1c74..ad968ea009 100644
--- a/packages/codemirror/src/syntax_highlighting.ts
+++ b/packages/codemirror/src/syntax_highlighting.ts
@@ -192,6 +192,7 @@ const byMimeType: Record<SupportedMimeTypes, (() => Promise<StreamParser<unknown
"text/x-tiddlywiki": async () => (await import('@codemirror/legacy-modes/mode/tiddlywiki')).tiddlyWiki,
"text/x-toml": async () => (await import('@codemirror/legacy-modes/mode/toml')).toml,
"text/x-tornado": null,
+ "text/x-trilium-log": async () => [ (await import('./extensions/trilium_log_highlighter.js')).triliumLogHighlighter ],
"text/x-ttcn-asn": async () => (await import('@codemirror/legacy-modes/mode/ttcn')).ttcn,
"text/x-ttcn-cfg": async () => (await import('@codemirror/legacy-modes/mode/ttcn-cfg')).ttcnCfg,
"text/x-ttcn": async () => (await import('@codemirror/legacy-modes/mode/ttcn')).ttcn,
diff --git a/packages/commons/src/lib/mime_type.ts b/packages/commons/src/lib/mime_type.ts
index e62604ab7a..793753082b 100644
--- a/packages/commons/src/lib/mime_type.ts
+++ b/packages/commons/src/lib/mime_type.ts
@@ -3,6 +3,13 @@
*/
export const MIME_TYPE_AUTO = "text-x-trilium-auto";
+/**
+ * The MIME type of the Trilium backend log (and code notes that want the same log highlighting).
+ * Highlighted only in CodeMirror via the {@link https://github.com/TriliumNext/Notes Trilium Log Highlighter}
+ * extension; it has no highlight.js equivalent, so shared/read-only Markdown rendering shows it plain.
+ */
+export const MIME_TYPE_TRILIUM_LOG = "text/x-trilium-log";
+
export interface MimeTypeDefinition {
default?: boolean;
title: string;
@@ -183,6 +190,7 @@ const MIME_TYPES_DICT_RAW = [
{ title: "Tiki wiki", mime: "text/tiki" },
{ title: "TOML", mime: "text/x-toml", mdLanguageCode: "ini", icon: "bx bx-bracket" },
{ title: "Tornado", mime: "text/x-tornado" },
+ { title: "Trilium Log", mime: "text/x-trilium-log", icon: "bx bx-list-ul" },
{ title: "troff", mime: "text/troff" },
{ title: "TTCN_CFG", mime: "text/x-ttcn-cfg" },
{ title: "TTCN", mime: "text/x-ttcn" },
diff --git a/packages/highlightjs/src/syntax_highlighting.ts b/packages/highlightjs/src/syntax_highlighting.ts
index 5eff7b47e8..cd46a6f5f6 100644
--- a/packages/highlightjs/src/syntax_highlighting.ts
+++ b/packages/highlightjs/src/syntax_highlighting.ts
@@ -158,6 +158,7 @@ export const byMimeType: MimeRecord = {
"text/x-tiddlywiki": null,
"text/x-toml": () => import("highlight.js/lib/languages/ini"),
"text/x-tornado": null,
+ "text/x-trilium-log": null,
"text/x-ttcn-asn": null,
"text/x-ttcn-cfg": null,
"text/x-ttcn": () => import("./languages/ttcn3.js"),