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(markdown): show the highlights sidebar for Markdown notes
Elian Doran5e55a3c2f289
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.tsindex dd2ce689dd..c39f51b9b7 100644--- a/apps/client/src/components/note_context.ts+++ b/apps/client/src/components/note_context.ts@@ -13,6 +13,7 @@ import { shouldRedirectPinnedNavigation } from "../services/tab_pinning.js";import treeService from "../services/tree.js";import utils from "../services/utils.js";import { ReactWrappedWidget } from "../widgets/basic_widget.js";+import type { HighlightContext } from "../widgets/sidebar/HighlightsList.js";import type { HeadingContext } from "../widgets/sidebar/TableOfContents.js";import type { ChatHighlightsContext } from "../widgets/type_widgets/llm_chat/chat_highlights.js";import appContext, { type EventData, type EventListener } from "./app_context.js";@@ -40,6 +41,7 @@ const READ_ONLY_CAPABLE_TYPES: string[] = [export interface NoteContextDataMap {toc: HeadingContext;+ highlights: HighlightContext;chatHighlights: ChatHighlightsContext;pdfPages: {totalPages: number;diff --git a/apps/client/src/widgets/sidebar/HighlightsList.tsx b/apps/client/src/widgets/sidebar/HighlightsList.tsxindex 81686d6cbd..d068cfed3d 100644--- a/apps/client/src/widgets/sidebar/HighlightsList.tsx+++ b/apps/client/src/widgets/sidebar/HighlightsList.tsx@@ -5,22 +5,20 @@ import { t } from "../../services/i18n";import { randomString } from "../../services/utils";import Dropdown from "../react/Dropdown";import { FormListToggleableItem } from "../react/FormList";-import { useActiveNoteContext, useContentElement, useIsNoteReadOnly, useMathRendering, useNoteProperty, useTextEditor, useTriliumOptionJson } from "../react/hooks";+import { useActiveNoteContext, useContentElement, useGetContextData, useIsNoteReadOnly, useMathRendering, useNoteProperty, useTextEditor, useTriliumOptionJson } from "../react/hooks";import RawHtml from "../react/RawHtml";import { HIGHLIGHT_FORMATS, HighlightFormat } from "../type_widgets/options/highlights_list_options";+import { extractHighlightsFromStaticHtml, type DomHighlight, type RawHighlight } from "./highlights_extract";import RightPanelWidget from "./RightPanelWidget";import SidebarHelp from "./SidebarHelp";-interface RawHighlight {- id: string;- text: string;- attrs: {- bold: boolean;- italic: boolean;- underline: boolean;- color: string | undefined;- background: string | undefined;- }+/**+ * Highlights published by a type widget that renders its own content, rather than one the+ * sidebar can read out of the editor or the DOM itself (see the Markdown note type).+ */+export interface HighlightContext {+ highlights: RawHighlight[];+ scrollToHighlight(highlight: RawHighlight): void;}export default function HighlightsList() {@@ -32,10 +30,21 @@ export default function HighlightsList() {<>{noteType === "text" && isReadOnly && <ReadOnlyTextHighlightsList />}{noteType === "text" && !isReadOnly && <EditableTextHighlightsList />}+ {note?.isMarkdown() && <ContextDataHighlightsList />}</>);}+/** Reads what the note's own widget published, so the source stays the widget's business. */+function ContextDataHighlightsList() {+ const data = useGetContextData("highlights");++ return <AbstractHighlightsList+ highlights={data?.highlights ?? []}+ scrollToHighlight={data?.scrollToHighlight ?? (() => {})}+ />;+}+function AbstractHighlightsList<T extends RawHighlight>({ highlights, scrollToHighlight }: {highlights: T[],scrollToHighlight(highlight: T): void;@@ -270,10 +279,6 @@ function extractHighlightsFromTextEditor(editor: CKTextEditor) {//#endregion//#region Read-only text-interface DomHighlight extends RawHighlight {- element: HTMLElement;-}-function ReadOnlyTextHighlightsList() {const { noteContext } = useActiveNoteContext();const contentEl = useContentElement(noteContext);@@ -289,68 +294,4 @@ function ReadOnlyTextHighlightsList() {/>;}-export function extractHighlightsFromStaticHtml(el: HTMLElement | null) {- if (!el) return [];-- const highlights: DomHighlight[] = [];- const processedElements = new Set<Element>();-- // Find all elements with inline background-color or color styles- const styledElements = el.querySelectorAll<HTMLElement>('[style*="background-color"], [style*="color"]');-- for (const styledEl of styledElements) {- if (processedElements.has(styledEl)) continue;- if (!styledEl.textContent?.trim()) continue;-- const attrs: RawHighlight["attrs"] = {- bold: !!styledEl.closest("strong"),- italic: !!styledEl.closest("em"),- underline: !!styledEl.closest("u"),- background: styledEl.style.backgroundColor,- color: styledEl.style.color- };-- if (Object.values(attrs).some(Boolean)) {- processedElements.add(styledEl);-- highlights.push({- id: randomString(),- text: styledEl.innerHTML,- element: styledEl,- attrs- });- }- }-- // Also find bold, italic, underline elements- const formattingElements = el.querySelectorAll<HTMLElement>("strong, em, u, b, i");-- for (const formattedEl of formattingElements) {- // Skip if already processed or inside a processed element- if (processedElements.has(formattedEl)) continue;- if (Array.from(processedElements).some(processed => processed.contains(formattedEl))) continue;- if (!formattedEl.textContent?.trim()) continue;-- const attrs: RawHighlight["attrs"] = {- bold: formattedEl.matches("strong, b"),- italic: formattedEl.matches("em, i"),- underline: formattedEl.matches("u"),- background: formattedEl.style.backgroundColor,- color: formattedEl.style.color- };-- if (Object.values(attrs).some(Boolean)) {- processedElements.add(formattedEl);-- highlights.push({- id: randomString(),- text: formattedEl.innerHTML,- element: formattedEl,- attrs- });- }- }-- return highlights;-}//#endregiondiff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsxindex 42dfe7c672..48e83f5404 100644--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx@@ -271,7 +271,7 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent):},{el: <HighlightsList />,- enabled: noteType === "text" && highlightsList.length > 0,+ enabled: (noteType === "text" || !!note?.isMarkdown()) && highlightsList.length > 0,tab: "outline"},{diff --git a/apps/client/src/widgets/sidebar/highlights_extract.spec.ts b/apps/client/src/widgets/sidebar/highlights_extract.spec.tsindex 10ef0fae00..f6415a71f2 100644--- a/apps/client/src/widgets/sidebar/highlights_extract.spec.ts+++ b/apps/client/src/widgets/sidebar/highlights_extract.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { extractHighlightsFromStaticHtml } from "./HighlightsList.js";+import { extractHighlightsFromStaticHtml } from "./highlights_extract.js";describe("extractHighlightsFromStaticHtml", () => {it("extracts a single highlight containing text and math equation together", () => {diff --git a/apps/client/src/widgets/sidebar/highlights_extract.ts b/apps/client/src/widgets/sidebar/highlights_extract.tsnew file mode 100644index 0000000000..212954ac0a--- /dev/null+++ b/apps/client/src/widgets/sidebar/highlights_extract.ts@@ -0,0 +1,94 @@+import { randomString } from "../../services/utils";++/**+ * A formatted run of text, as the highlights sidebar consumes it. Every producer — the text+ * editor, read-only HTML, the Markdown preview — reduces its own representation to this.+ */+export interface RawHighlight {+ id: string;+ /** Inline HTML of the run, so nested content (e.g. maths) survives into the list. */+ text: string;+ attrs: {+ bold: boolean;+ italic: boolean;+ underline: boolean;+ color: string | undefined;+ background: string | undefined;+ }+}++export interface DomHighlight extends RawHighlight {+ element: HTMLElement;+}++/**+ * Collects the formatted runs of a rendered HTML tree: coloured runs first, then bold/italic/+ * underline ones that are not already inside a coloured run.+ *+ * Used both for read-only text notes and for the Markdown preview, whose rendered HTML this+ * treats identically — `**bold**` reaches here as `<strong>` like any other.+ */+export function extractHighlightsFromStaticHtml(el: HTMLElement | null) {+ if (!el) return [];++ const highlights: DomHighlight[] = [];+ const processedElements = new Set<Element>();++ // Find all elements with inline background-color or color styles+ const styledElements = el.querySelectorAll<HTMLElement>('[style*="background-color"], [style*="color"]');++ for (const styledEl of styledElements) {+ if (processedElements.has(styledEl)) continue;+ if (!styledEl.textContent?.trim()) continue;++ const attrs: RawHighlight["attrs"] = {+ bold: !!styledEl.closest("strong"),+ italic: !!styledEl.closest("em"),+ underline: !!styledEl.closest("u"),+ background: styledEl.style.backgroundColor,+ color: styledEl.style.color+ };++ if (Object.values(attrs).some(Boolean)) {+ processedElements.add(styledEl);++ highlights.push({+ id: randomString(),+ text: styledEl.innerHTML,+ element: styledEl,+ attrs+ });+ }+ }++ // Also find bold, italic, underline elements+ const formattingElements = el.querySelectorAll<HTMLElement>("strong, em, u, b, i");++ for (const formattedEl of formattingElements) {+ // Skip if already processed or inside a processed element+ if (processedElements.has(formattedEl)) continue;+ if (Array.from(processedElements).some(processed => processed.contains(formattedEl))) continue;+ if (!formattedEl.textContent?.trim()) continue;++ const attrs: RawHighlight["attrs"] = {+ bold: formattedEl.matches("strong, b"),+ italic: formattedEl.matches("em, i"),+ underline: formattedEl.matches("u"),+ background: formattedEl.style.backgroundColor,+ color: formattedEl.style.color+ };++ if (Object.values(attrs).some(Boolean)) {+ processedElements.add(formattedEl);++ highlights.push({+ id: randomString(),+ text: formattedEl.innerHTML,+ element: formattedEl,+ attrs+ });+ }+ }++ return highlights;+}diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.tsindex 7cda45f5dc..f3591ae49e 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts@@ -251,6 +251,49 @@ describe("renderWithSourceLines", () => {expect(html("a == b")).toBe("<p>a == b</p>");});+ describe("highlights", () => {+ function highlights(src: string) {+ return renderWithSourceLines(src).highlights;+ }++ it("extracts bold, italic and underline runs", () => {+ expect(highlights("**bold** and *italic* and <u>underline</u>").map(h => [ h.text, h.attrs.bold, h.attrs.italic, h.attrs.underline ]))+ .toEqual([+ [ "bold", true, false, false ],+ [ "italic", false, true, false ],+ [ "underline", false, false, true ]+ ]);+ });++ it("traces each run back to the source line of its block, for scrolling the editor", () => {+ const src = [+ "# Heading", // line 1+ "", // line 2+ "a **one** b", // line 3+ "", // line 4+ "c *two* d" // line 5+ ].join("\n");++ expect(highlights(src).map(h => [ h.text, h.line ])).toEqual([ [ "one", 3 ], [ "two", 5 ] ]);+ });++ it("gives each run an id that is stable across re-renders", () => {+ const src = "**a** and *b*";+ expect(highlights(src).map(h => h.id)).toEqual(highlights(src).map(h => h.id));+ });++ it("picks up a ==highlight== as a background colour", () => {+ const [ highlight ] = highlights("some ==marked== text");++ expect(highlight.text).toBe("marked");+ expect(highlight.attrs.background).toBeTruthy();+ });++ it("finds nothing in unformatted text", () => {+ expect(highlights("just a plain paragraph")).toEqual([]);+ });+ });+it("renders a colour the exporter preserved as inline HTML", () => {// Non-default colours survive a Markdown export as a span, so the preview has to show them.expect(html(`a <span style="color:#ff0000">**red**</span> b`))diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsxindex 2f37e647dd..10ac6c9862 100644--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx@@ -19,6 +19,7 @@ import { removeIndividualBinding } from "../../../services/shortcuts";import tree from "../../../services/tree";import utils, { isDesktop } from "../../../services/utils";import { useLegacyImperativeHandlers, useTriliumEvent } from "../../react/hooks";+import { extractHighlightsFromStaticHtml, type RawHighlight } from "../../sidebar/highlights_extract";import SplitEditor from "../helpers/SplitEditor";import { ReadOnlyTextContent } from "../text/ReadOnlyText";import { TypeWidgetProps } from "../type_widget";@@ -51,6 +52,11 @@ export interface MarkdownHeading {line: number;}+/** A formatted run of the rendered note, carrying the source line it came from. */+export interface MarkdownHighlight extends RawHighlight {+ line: number;+}+interface MarkdownContextValue {html: string;headings: MarkdownHeading[];@@ -70,7 +76,7 @@ export default function Markdown(props: TypeWidgetProps) {const [ content, setContent ] = useState("");const [ editorView, setEditorView ] = useState<VanillaCodeMirror | null>(null);const [ previewEl, setPreviewEl ] = useState<HTMLDivElement | null>(null);- const { html, headings } = useMemo(() => renderWithSourceLines(content), [ content ]);+ const { html, headings, highlights } = useMemo(() => renderWithSourceLines(content), [ content ]);// Bind text-detail shortcuts (e.g. Ctrl+L for add link) to CodeMirror's contentDOM,// since the outer `dom` only receives events after CodeMirror has already handled them.@@ -90,6 +96,7 @@ 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);useImageDrop(props.note, editorView);useTextCommands(props.parentComponent, editorView);useSlashCommands(props.parentComponent, editorView, props.note);@@ -143,14 +150,8 @@ function usePublishToc(noteContext.setContextData("toc", {headings,scrollToHeading(heading) {- if (!editorView) return;const mdHeading = headings.find(h => h.id === heading.id);- if (!mdHeading) return;- const line = editorView.state.doc.line(Math.min(mdHeading.line, editorView.state.doc.lines));- const lineBlock = editorView.lineBlockAt(line.from);- const scrollerHeight = editorView.scrollDOM.clientHeight;- const targetTop = lineBlock.top - scrollerHeight / 2 + lineBlock.height / 2;- editorView.scrollDOM.scrollTo({ top: targetTop, behavior: "smooth" });+ if (mdHeading) scrollEditorToLine(editorView, mdHeading.line);}});}, [ noteContext, headings, editorView, note.noteId ]);@@ -167,6 +168,53 @@ function usePublishToc(}});}++/** 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;++ const line = editorView.state.doc.line(Math.min(lineNumber, editorView.state.doc.lines));+ const lineBlock = editorView.lineBlockAt(line.from);+ const scrollerHeight = editorView.scrollDOM.clientHeight;+ const targetTop = lineBlock.top - scrollerHeight / 2 + lineBlock.height / 2;++ editorView.scrollDOM.scrollTo({ top: targetTop, behavior: "smooth" });+}+//#endregion++//#region Highlights+/**+ * Publishes the note's formatted runs via `setContextData("highlights", ...)`, the same way the+ * table of contents is published, so the sidebar's Highlights list works for Markdown notes+ * without needing to know how they are rendered.+ */+function usePublishHighlights(+ noteContext: NoteContext | undefined,+ editorView: VanillaCodeMirror | null,+ highlights: MarkdownHighlight[],+ note: FNote+) {+ const publish = useCallback(() => {+ if (!noteContext || noteContext.noteId !== note.noteId) return;+ noteContext.setContextData("highlights", {+ highlights,+ scrollToHighlight(highlight) {+ const mdHighlight = highlights.find(h => h.id === highlight.id);+ if (mdHighlight) scrollEditorToLine(editorView, mdHighlight.line);+ }+ });+ }, [ noteContext, highlights, editorView, note.noteId ]);++ useEffect(() => { publish(); }, [ publish ]);++ // Context data is cleared when the note changes, so restore it when ours becomes active+ // again — the noteId guard in publish() keeps it from overwriting another note's list.+ useTriliumEvent("noteSwitched", ({ noteContext: ctx }) => {+ if (ctx === noteContext) {+ publish();+ }+ });+}//#endregion//#region Synced scrolling@@ -528,7 +576,7 @@ const NON_RENDERED_TOKENS = new Set([ "space", "def" ]);* with the matching lexer token's start line. Marked does not emit source* positions (markedjs/marked#1267) so we count newlines in `raw` ourselves.*/-export function renderWithSourceLines(src: string): { html: string; headings: MarkdownHeading[] } {+export function renderWithSourceLines(src: string): { html: string; headings: MarkdownHeading[]; highlights: MarkdownHighlight[] } {// Compute the start line of each renderable top-level token in source order.const tokens = marked.lexer(src);const lines: number[] = [];@@ -557,7 +605,7 @@ export function renderWithSourceLines(src: string): { html: string; headings: MademoteH1: false,renderer: new MarkdownPreviewRenderer({ async: false })});- if (!html) return { html: "", headings };+ if (!html) return { html: "", headings, highlights: [] };const container = document.createElement("div");container.innerHTML = html;@@ -569,6 +617,26 @@ export function renderWithSourceLines(src: string): { html: string; headings: Maconst sourceLine = lines[i] ?? lines[lines.length - 1] ?? 1;children[i].setAttribute("data-source-line", String(sourceLine));}- return { html: container.innerHTML, headings };++ return { html: container.innerHTML, headings, highlights: extractHighlights(container) };+}++/**+ * 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+ * 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.+ */+function extractHighlights(container: HTMLElement): MarkdownHighlight[] {+ return extractHighlightsFromStaticHtml(container).map(({ element, ...highlight }, index) => ({+ ...highlight,+ // Stable across re-renders, unlike the random id the extractor assigns: the list is+ // rebuilt on every keystroke and would otherwise remount each item every time.+ id: `md-highlight-${index}`,+ line: Number(element.closest("[data-source-line]")?.getAttribute("data-source-line")) || 1+ }));}//#endregion