diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index 9ebcb80042..e2b6df6040 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -290,8 +290,10 @@ function sourceResizeAnchor(view: EditorView) { if (pos !== null && coords) return { view, doc: view.state.doc, pos, inset: coords.top - viewport.top, top }; } -function blocksOf(root: HTMLElement) { +function blocksOf(root: HTMLElement, source: Text) { const blocks = []; + const topOf = (element: HTMLElement) => + element.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop; for (const el of root.querySelectorAll(":scope > [data-preview-blocks] > [data-line]")) { const line = Number(el.dataset.line); const endLine = Number(el.dataset.endLine); @@ -307,7 +309,7 @@ function blocksOf(root: HTMLElement) { line: start, endLine: i === 0 ? line + 2 : start + 1, get top() { - return row.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop; + return topOf(row); }, get bottom() { return row.getBoundingClientRect().bottom - root.getBoundingClientRect().top + root.scrollTop; @@ -315,9 +317,14 @@ function blocksOf(root: HTMLElement) { }); } } else { + const listItems = listItemPositions(el, line, endLine, topOf); + const offsetForLine = listItems.length + ? (target: number) => previewOffsetForLine(listItems, target, el.offsetTop + el.offsetHeight) + : paragraphPosition(root, el, source, line, endLine); blocks.push({ line, endLine, + offsetForLine, get top() { return el.offsetTop; }, @@ -330,6 +337,54 @@ function blocksOf(root: HTMLElement) { return blocks; } +function listItemPositions(block: HTMLElement, start: number, end: number, topOf: (element: HTMLElement) => number) { + if (!block.firstElementChild?.matches("ol, ul")) return []; + const positions = []; + let previous = start - 1; + for (const item of block.querySelectorAll("li[data-markdown-line-offset]")) { + const line = start + Number(item.dataset.markdownLineOffset); + if (!Number.isInteger(line) || line <= previous || line >= end) continue; + previous = line; + positions.push({ + line, + get top() { + return topOf(item); + }, + }); + } + return positions; +} + +function paragraphPosition(root: HTMLElement, block: HTMLElement, source: Text, start: number, end: number) { + const paragraph = block.firstElementChild; + const text = paragraph?.firstChild; + if ( + paragraph?.tagName !== "P" || + paragraph.childNodes.length !== 1 || + !(text instanceof globalThis.Text) || + !Number.isInteger(start) || + !Number.isInteger(end) || + start < 0 || + end <= start || + start >= source.lines + ) + return; + const from = source.line(start + 1).from; + const to = end < source.lines ? source.line(end + 1).from : source.length; + if (source.sliceString(from, to).trimEnd() !== text.data) return; + return (target: number) => { + const line = source.line(Math.floor(target) + 1); + const progress = target - Math.floor(target); + const offset = Math.min(text.length - 1, Math.floor(line.from - from + progress * (line.length + 1))); + if (offset < 0) return; + const range = root.ownerDocument.createRange(); + range.setStart(text, offset); + range.setEnd(text, offset + 1); + const bounds = range.getBoundingClientRect(); + if (bounds.height) return bounds.top - root.getBoundingClientRect().top + root.scrollTop; + }; +} + let svgRenderer: Promise | undefined; function loadSvgRenderer() { @@ -758,7 +813,7 @@ function MarkdownPreview({ const open = toggled.current.get(i); if (open !== undefined) d.open = open; }); - blocks.current = blocksOf(root); + blocks.current = blocksOf(root, renderedSource); invalidatePreviewIndex(root); return () => { if (view) parkedPreviews.set(view, { source: renderedSource, markup, root }); diff --git a/src/features/viewers/markdown/render.test.ts b/src/features/viewers/markdown/render.test.ts index 6bbc5e4bbd..26097c2f4c 100644 --- a/src/features/viewers/markdown/render.test.ts +++ b/src/features/viewers/markdown/render.test.ts @@ -160,6 +160,17 @@ describe("markdown preview rendering", () => { expect(root.querySelector("h1")?.id).toBe("user-content-title"); }); + it("records nested list item offsets relative to their top-level block", () => { + const root = document.createElement("div"); + root.innerHTML = renderMarkdown("# Title\n\n- parent\n continued\n - nested\n - next\n\n- last\n"); + expect([...root.querySelectorAll("li")].map((item) => item.dataset.markdownLineOffset)).toEqual([ + "0", + "2", + "3", + "5", + ]); + }); + it("keeps embedded image destinations and code samples intact", () => { const url = "data:image/png;base64," + "abcd".repeat(100); const line = `![](${url})`; diff --git a/src/features/viewers/markdown/render.ts b/src/features/viewers/markdown/render.ts index abe5b7b211..b56a569a75 100644 --- a/src/features/viewers/markdown/render.ts +++ b/src/features/viewers/markdown/render.ts @@ -7,7 +7,7 @@ * placeholders, typeset by the preview (`renderMath`). YAML front matter is shown * as a table of its top-level fields. */ -import { Marked, Renderer, type Token, type TokensList } from "marked"; +import { Marked, Renderer, type Token, type Tokens, type TokensList } from "marked"; import DOMPurify from "dompurify"; import { mathExtension } from "@/editor/lsp/markdownMath"; import { opensOtherShare } from "@/platform/paths"; @@ -23,6 +23,7 @@ export const markdownFenceMarker = Array.from(crypto.getRandomValues(new Uint32A value.toString(36), ).join("-"); const defaultRenderer = new Renderer(); +const listItemLines = new WeakMap(); export const isRenderedFence = (pre: HTMLElement): boolean => pre.hasAttribute(FENCE_ATTR); @@ -34,6 +35,12 @@ function previewParser(marker: string): Marked { gfm: true, breaks: false, renderer: { + listitem(item) { + const line = listItemLines.get(item); + if (line === undefined) return false; + const html = defaultRenderer.listitem.call(this, item); + return html.replace(/^
  • /, `
  • `); + }, code(token) { const { text, lang, codeBlockStyle } = token; if (lang?.trim().split(/\s+/)[0]?.toLowerCase() === "mermaid") @@ -114,6 +121,21 @@ const countLines = (s: string) => { return n; }; +function markListItems(list: Tokens.List, start: number) { + let line = start; + for (const item of list.items) { + listItemLines.set(item, line); + let cursor = 0; + for (const token of item.tokens) { + const index = item.text.indexOf(token.raw, cursor); + if (index < 0) break; + if (token.type === "list") markListItems(token as Tokens.List, line + countLines(item.text.slice(0, index))); + cursor = index + token.raw.length; + } + line += countLines(item.raw); + } +} + /** The YAML front matter at the start of `text`: its top-level fields and how many lines it spans. */ export function frontMatter(text: string): { fields: [string, string][]; lines: number } | null { const m = /^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(text); @@ -227,6 +249,7 @@ export function parseMarkdownBlocks(text: string, marker = markdownFenceMarker): const start = line; line += countLines(token.raw); if (token.type === "space" || token.type === "footnoteDefinition") continue; + if (token.type === "list" && !open.length) markListItems(token as Tokens.List, 0); const list = Object.assign([token], { links: tokens.links }) as TokensList; let body = parser.parser(list); if (token.type === "table") { @@ -474,7 +497,13 @@ export function resolveLink(file: string, href: string): LinkTarget | null { * between the blocks around it (`blocks` sorted by line, with their offsets). */ export function previewOffsetForLine( - blocks: ReadonlyArray<{ line: number; top: number; endLine?: number; bottom?: number }>, + blocks: ReadonlyArray<{ + line: number; + top: number; + endLine?: number; + bottom?: number; + offsetForLine?: (line: number) => number | undefined; + }>, line: number, end: number, sourceOffsets?: readonly number[], @@ -493,6 +522,8 @@ export function previewOffsetForLine( const endLine = a.endLine ?? b?.line ?? a.line + 1; const bottom = a.bottom ?? b?.top ?? end; if (line < endLine) { + const precise = a.offsetForLine?.(line); + if (precise !== undefined) return precise; let progress = (line - a.line) / Math.max(1, endLine - a.line); if (sourceOffsets && endLine < sourceOffsets.length) { const row = Math.floor(line);