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
fix(markdown): scroll the preview from the table of contents (closes #11936)
Elian Doran6974b6752f62
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.tsindex 74433e03ad..9fae7d9f93 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts@@ -2,10 +2,11 @@// 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 type VanillaCodeMirror from "@triliumnext/codemirror";import { HIGHLIGHT_STYLE } from "@triliumnext/commons";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { findActiveBlock, renderWithSourceLines } from "./Markdown.js";+import { findActiveBlock, renderWithSourceLines, scrollToSourceLine } from "./Markdown.js";describe("renderWithSourceLines", () => {function extractLines(src: string): number[] {@@ -328,3 +329,47 @@ describe("findActiveBlock", () => {expect(findActiveBlock([], 1)).toBeNull();});});++describe("scrollToSourceLine", () => {+ function preview() {+ const el = document.createElement("div");+ el.innerHTML = renderWithSourceLines("# One\n\ntext\n\n## Two\n\nmore").html;+ const heading = el.querySelector<HTMLElement>("h2");+ if (!heading) throw new Error("h2 not rendered");+ heading.scrollIntoView = vi.fn();+ return { el, heading };+ }++ /** A stand-in for the CodeMirror view, with a scroller of the given height (0 when hidden). */+ function editor(clientHeight: number) {+ const scrollTo = vi.fn();+ const view = {+ state: { doc: { lines: 7, line: () => ({ from: 0 }) } },+ lineBlockAt: () => ({ top: 0, height: 10 }),+ scrollDOM: { clientHeight, scrollTo }+ } as unknown as VanillaCodeMirror;+ return { view, scrollTo };+ }++ it("scrolls the preview when the editor is unmounted or hidden (preview mode)", () => {+ const { el, heading } = preview();+ expect(heading.dataset.sourceLine).toBe("5");++ scrollToSourceLine(null, el, 5);+ expect(heading.scrollIntoView).toHaveBeenCalledTimes(1);++ const hidden = editor(0);+ scrollToSourceLine(hidden.view, el, 5);+ expect(heading.scrollIntoView).toHaveBeenCalledTimes(2);+ expect(hidden.scrollTo).not.toHaveBeenCalled();+ });++ it("scrolls the editor when it is on screen, leaving the preview to follow", () => {+ const { el, heading } = preview();+ const visible = editor(400);++ scrollToSourceLine(visible.view, el, 5);+ expect(visible.scrollTo).toHaveBeenCalledTimes(1);+ expect(heading.scrollIntoView).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsxindex fd8174379e..336dea9634 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx@@ -101,8 +101,8 @@ export default function Markdown(props: TypeWidgetProps) {useSyncedScrolling(editorView, previewEl);useSyncedHighlight(editorView, previewEl, html);- usePublishToc(props.noteContext, editorView, headings, props.note);- usePublishHighlights(props.noteContext, editorView, highlights, props.note);+ usePublishToc(props.noteContext, editorView, previewEl, headings, props.note);+ usePublishHighlights(props.noteContext, editorView, previewEl, highlights, props.note);useImageDrop(props.note, editorView);useTextCommands(props.parentComponent, editorView);useNoteLinkChips(editorView);@@ -150,6 +150,7 @@ function MarkdownPreview({ ntxId }: { ntxId: TypeWidgetProps["ntxId"] }) {function usePublishToc(noteContext: NoteContext | undefined,editorView: VanillaCodeMirror | null,+ previewEl: HTMLDivElement | null,headings: MarkdownHeading[],note: FNote) {@@ -159,10 +160,10 @@ function usePublishToc(headings,scrollToHeading(heading) {const mdHeading = headings.find(h => h.id === heading.id);- if (mdHeading) scrollEditorToLine(editorView, mdHeading.line);+ if (mdHeading) scrollToSourceLine(editorView, previewEl, mdHeading.line);}});- }, [ noteContext, headings, editorView, note.noteId ]);+ }, [ noteContext, headings, editorView, previewEl, note.noteId ]);// Publish when headings or editor change.useEffect(() => { publish(); }, [ publish ]);@@ -177,9 +178,24 @@ function usePublishToc(});}+/**+ * Scrolls to the given 1-indexed source line: in the editor when it is on screen, since+ * `useSyncedScrolling` makes the preview follow, otherwise in the preview. In preview mode the+ * editor is either unmounted or hidden.+ */+export function scrollToSourceLine(editorView: VanillaCodeMirror | null, previewEl: HTMLElement | null, lineNumber: number) {+ if (editorView && editorView.scrollDOM.clientHeight > 0) {+ scrollEditorToLine(editorView, lineNumber);+ return;+ }++ if (!previewEl) return;+ const block = findActiveBlock(previewEl.querySelectorAll<HTMLElement>("[data-source-line]"), lineNumber);+ block?.scrollIntoView({ block: "start", behavior: "smooth" });+}+/** Scrolls the source editor so the given 1-indexed line sits in the middle of the viewport. */-function scrollEditorToLine(editorView: VanillaCodeMirror | null, lineNumber: number) {- if (!editorView) return;+function scrollEditorToLine(editorView: VanillaCodeMirror, lineNumber: number) {const line = editorView.state.doc.line(Math.min(lineNumber, editorView.state.doc.lines));const lineBlock = editorView.lineBlockAt(line.from);@@ -199,6 +215,7 @@ function scrollEditorToLine(editorView: VanillaCodeMirror | null, lineNumber: nufunction usePublishHighlights(noteContext: NoteContext | undefined,editorView: VanillaCodeMirror | null,+ previewEl: HTMLDivElement | null,highlights: MarkdownHighlight[],note: FNote) {@@ -208,10 +225,10 @@ function usePublishHighlights(highlights,scrollToHighlight(highlight) {const mdHighlight = highlights.find(h => h.id === highlight.id);- if (mdHighlight) scrollEditorToLine(editorView, mdHighlight.line);+ if (mdHighlight) scrollToSourceLine(editorView, previewEl, mdHighlight.line);}});- }, [ noteContext, highlights, editorView, note.noteId ]);+ }, [ noteContext, highlights, editorView, previewEl, note.noteId ]);useEffect(() => { publish(); }, [ publish ]);@@ -672,8 +689,7 @@ export function renderWithSourceLines(src: string): { html: string; headings: Ma* unchanged — and `==highlight==`, which renders as a coloured span, is picked up too.** Each run is traced back to the source line of the block it sits in (the attribute tagged on- * just above), so clicking it can scroll the editor rather than the preview, which may not even- * be on screen.+ * just above), so clicking it scrolls whichever pane is on screen (`scrollToSourceLine`).*/function extractHighlights(container: HTMLElement): MarkdownHighlight[] {return extractHighlightsFromStaticHtml(container).map(({ element, ...highlight }, index) => ({