Skip to content

Build your personal knowledge base with Trilium Notes

fix(markdown): keep the preview in step with tabs blocks

Elian Doran55ba8ad4fd06
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
index 9fae7d9f93..dad8b5a0f6 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
@@ -2,11 +2,12 @@
// DOMPurify relies on browser-faithful DOM traversal (NodeIterator); happy-dom
// mishandles it and strips valid markup (surfaced by dompurify 3.4.8). Run the
// sanitization-dependent specs under jsdom, which matches real-browser behavior.
+import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import type VanillaCodeMirror from "@triliumnext/codemirror";
import { HIGHLIGHT_STYLE } from "@triliumnext/commons";
import { describe, expect, it, vi } from "vitest";
-import { findActiveBlock, renderWithSourceLines, scrollToSourceLine } from "./Markdown.js";
+import { findActiveBlock, renderWithSourceLines, revealTabAtLine, scrollToSourceLine } from "./Markdown.js";
describe("renderWithSourceLines", () => {
function extractLines(src: string): number[] {
@@ -82,6 +83,25 @@ describe("renderWithSourceLines", () => {
expect(blocks.every((block) => block.hasAttribute("data-source-line"))).toBe(true);
});
+ it("counts a tabs block as one top-level block, so the lines after it stay aligned", () => {
+ const src = [
+ "Before", // 1
+ "", // 2
+ "=== \"A\"", // 3
+ "", // 4
+ " a", // 5
+ "", // 6
+ "=== \"B\"", // 7
+ "", // 8
+ " b", // 9
+ "", // 10
+ "After" // 11
+ ].join("\n");
+
+ expect(extractLines(src)).toEqual([ 1, 3, 11 ]);
+ expect(html(src)).toContain("<p>After</p>");
+ });
+
it("keeps H1 as H1 in the preview (no title-row context to avoid)", () => {
expect(html("# Top level")).toContain("<h1>Top level</h1>");
});
@@ -373,3 +393,58 @@ describe("scrollToSourceLine", () => {
expect(heading.scrollIntoView).not.toHaveBeenCalled();
});
});
+
+describe("revealTabAtLine", () => {
+ const src = [
+ "=== \"A\"", // 1
+ "", // 2
+ " a", // 3
+ "", // 4
+ "=== \"B\"", // 5
+ "", // 6
+ " === \"B1\"", // 7
+ "", // 8
+ " b1", // 9
+ "", // 10
+ " === \"B2\"", // 11
+ "", // 12
+ " b2", // 13
+ "", // 14
+ "After" // 15
+ ].join("\n");
+
+ function preview() {
+ const el = document.createElement("div");
+ el.innerHTML = renderWithSourceLines(src).html;
+ applyTabs(el, { placeholder: "" });
+ return el;
+ }
+
+ function activeTitles(el: HTMLElement) {
+ return [ ...el.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ].map((title) => title.textContent);
+ }
+
+ it("tags each tab with the line of its header", () => {
+ const lines = [ ...preview().querySelectorAll<HTMLElement>("section.trilium-tab") ]
+ .map((tab) => tab.dataset.tabSourceLine);
+ expect(lines).toEqual([ "1", "5", "7", "11" ]);
+ });
+
+ it("shows the tab the line falls in, including a nested one", () => {
+ const el = preview();
+ expect(activeTitles(el)).toEqual([ "A", "B1" ]);
+
+ revealTabAtLine(el, 13);
+ expect(activeTitles(el)).toEqual([ "B", "B2" ]);
+
+ revealTabAtLine(el, 2);
+ expect(activeTitles(el)).toEqual([ "A", "B2" ]);
+ });
+
+ it("leaves the tabs alone for a line outside the block", () => {
+ const el = preview();
+ revealTabAtLine(el, 13);
+ revealTabAtLine(el, 15);
+ expect(activeTitles(el)).toEqual([ "B", "B2" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
index 336dea9634..61290aea01 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
@@ -1,12 +1,13 @@
import "./Markdown.css";
import "./MarkdownCommons.css";
+import { revealTab } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import VanillaCodeMirror from "@triliumnext/codemirror";
import { findWikilinkNoteIds, triliumNoteChips } from "@triliumnext/codemirror/src/extensions/trilium_note_chips";
import { CustomMarkdownRenderer, renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer";
-import { createLiteralTildeExtension } from "@triliumnext/commons/src/lib/marked_extensions";
+import { createLiteralTildeExtension, createTabsExtensions } from "@triliumnext/commons/src/lib/marked_extensions";
import DOMPurify from "dompurify";
-import { Marked, type Tokens } from "marked";
+import { Marked, type Token, type Tokens } from "marked";
import { createContext } from "preact";
import { useCallback, useContext, useEffect, useMemo, useState } from "preact/hooks";
@@ -31,8 +32,9 @@ import { insertText, replaceSelection, uploadImageAndInsert } from "./editor_uti
const marked = new Marked({ breaks: true, gfm: true });
// Headings in the outline are rendered by this instance rather than by `renderToHtml`, so it needs
-// the same single-tilde handling to stay consistent with the preview body.
-marked.use({ extensions: [createLiteralTildeExtension()] });
+// the same single-tilde handling to stay consistent with the preview body. `renderWithSourceLines`
+// pairs its top-level tokens with the rendered blocks, so it also needs every block extension.
+marked.use({ extensions: [createLiteralTildeExtension(), ...createTabsExtensions()] });
/**
* The default {@link CustomMarkdownRenderer} falls back to
@@ -304,9 +306,10 @@ function useSyncedHighlight(view: VanillaCodeMirror | null, preview: HTMLDivElem
let current: HTMLElement | null = null;
- function update() {
+ function update(revealCursorTab: boolean) {
if (!view || !preview) return;
const activeLine = view.state.doc.lineAt(view.state.selection.main.head).number;
+ if (revealCursorTab) revealTabAtLine(preview, activeLine);
const blocks = preview.querySelectorAll<HTMLElement>("[data-source-line]");
const match = findActiveBlock(blocks, activeLine);
@@ -321,13 +324,14 @@ function useSyncedHighlight(view: VanillaCodeMirror | null, preview: HTMLDivElem
preview.style.setProperty("--markdown-preview-marker-height", `${match?.offsetHeight ?? 0}px`);
}
- update();
- const observer = new ResizeObserver(update);
+ // A resize leaves the tabs alone, so a tab picked in the preview stays shown.
+ update(true);
+ const observer = new ResizeObserver(() => update(false));
observer.observe(preview);
for (const block of preview.children) observer.observe(block);
const unsubscribe = view.addUpdateListener((v) => {
- if (v.selectionSet || v.docChanged) update();
+ if (v.selectionSet || v.docChanged) update(true);
});
return () => {
observer.disconnect();
@@ -336,6 +340,20 @@ function useSyncedHighlight(view: VanillaCodeMirror | null, preview: HTMLDivElem
}, [ view, preview, html ]);
}
+/**
+ * Shows the tab that `line` falls in, nested tabs included: the last tab whose header starts at or
+ * before `line` within the top-level block that holds it. A line outside every tabs block leaves the
+ * tabs as they are.
+ */
+export function revealTabAtLine(preview: HTMLElement, line: number) {
+ const block = findActiveBlock(preview.querySelectorAll<HTMLElement>(":scope > [data-source-line]"), line);
+ let match: HTMLElement | null = null;
+ for (const tab of block?.querySelectorAll<HTMLElement>("section.trilium-tab") ?? []) {
+ if (Number(tab.dataset.tabSourceLine) <= line) match = tab;
+ }
+ if (match) revealTab(match);
+}
+
/** The last block that starts at or before `activeLine`, i.e. the one the cursor sits in. */
export function findActiveBlock(blocks: ArrayLike<HTMLElement>, activeLine: number) {
let match: HTMLElement | null = null;
@@ -680,9 +698,53 @@ export function renderWithSourceLines(src: string): { html: string; headings: Ma
children[i].setAttribute("data-source-line", String(sourceLine));
}
+ // A separate attribute: the scroll sync and the active-line marker measure every
+ // `[data-source-line]` element, and a hidden tab has no geometry.
+ const tabLines = collectTabLines(tokens, 1);
+ const tabs = container.querySelectorAll<HTMLElement>("section.trilium-tab");
+ if (tabs.length === tabLines.length) {
+ for (const [ index, tab ] of tabs.entries()) {
+ tab.dataset.tabSourceLine = String(tabLines[index]);
+ }
+ }
+
return { html: container.innerHTML, headings, highlights: extractHighlights(container) };
}
+/**
+ * The 1-indexed line of every tab header, in document order, which is also the order of the
+ * rendered `section.trilium-tab` elements. A tab panel is dedented, which keeps its line count, so
+ * the lines of nested tabs follow from their parent tab. Inside a list or a block quote the lines
+ * are approximate.
+ */
+function collectTabLines(tokens: Token[], firstLine: number): number[] {
+ const lines: number[] = [];
+ let line = firstLine;
+ for (const token of tokens) {
+ if (token.type === "tabs") {
+ let tabLine = line;
+ for (const tab of (token as Tokens.Generic).tokens ?? []) {
+ lines.push(tabLine);
+ // The panel starts below the `=== "Title"` line.
+ lines.push(...collectTabLines((tab as Tokens.Generic).tokens ?? [], tabLine + 1));
+ tabLine += countNewlines(tab.raw);
+ }
+ } else if (token.type === "list") {
+ for (const item of (token as Tokens.List).items) {
+ lines.push(...collectTabLines(item.tokens, line));
+ }
+ } else if (token.type === "blockquote") {
+ lines.push(...collectTabLines((token as Tokens.Blockquote).tokens, line));
+ }
+ line += countNewlines(token.raw);
+ }
+ return lines;
+}
+
+function countNewlines(text: string) {
+ return (text.match(/\n/g) ?? []).length;
+}
+
/**
* The note's formatted runs, read off the rendered preview rather than the Markdown source: by
* this point `**bold**` is a `<strong>` like any other, so the sidebar's own extractor applies