Markdown: highlight nested blocks on their own
Every block now maps to its own source lines at any depth: quotes inside quotes, paragraphs, code, quotes and lists inside list items, and each table row. A list item's highlight covers only its own text, not its nested items, and a parent quote is not highlighted with its children. A Parser subclass marks each block in the rendered HTML; the output is otherwise identical to render(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c652ca456b
commit
12990a9c5d
2 changed files with 94 additions and 30 deletions
|
|
@ -1,5 +1,5 @@
|
|||
// Markdown editor with live preview. Modes: edit only, side by side, full-page preview.
|
||||
import { marked } from '../../vendor/marked.esm.js';
|
||||
import { marked, Parser } from '../../vendor/marked.esm.js';
|
||||
import DOMPurify from '../../vendor/purify.es.mjs';
|
||||
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave, modal } from '../ui.js';
|
||||
import { createPaste } from './paste.js';
|
||||
|
|
@ -48,57 +48,117 @@ export function render(md) {
|
|||
return DOMPurify.sanitize(marked.parse(md));
|
||||
}
|
||||
|
||||
// Puts an empty marker before the HTML of every block that has a source range (token.mdUnit),
|
||||
// at any depth: marked calls parse() again for the blocks inside quotes and list items.
|
||||
// tagBlocks() then moves each marker's index onto the elements after it.
|
||||
class MarkingParser extends Parser {
|
||||
parse(tokens) {
|
||||
let out = '';
|
||||
for (const t of tokens) out += (t.mdUnit != null ? `<span data-md-mark="${t.mdUnit}"></span>` : '') + super.parse([t]);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
const NO_UNIT = new Set(['space', 'def', 'checkbox']);
|
||||
|
||||
/** Renders like render(), but returns the source range of each block so the editor and the
|
||||
* preview can point at each other. units: [{start, end}] in source order: each top-level block,
|
||||
* then (for lists) each of its items. Elements get data-md-unit="<index>". */
|
||||
* preview can point at each other. units: [{start, end}], one per block at any depth (a quote
|
||||
* inside a quote, a paragraph or list inside a list item), list item and table row. A container's
|
||||
* own element covers its children, but each child has its own, smaller unit, and a list item's
|
||||
* unit is only its own text. Outer units come before inner ones. */
|
||||
export function renderBlocks(md) {
|
||||
const tokens = marked.lexer(md);
|
||||
const units = [];
|
||||
let html = '';
|
||||
const add = (t, start, end) => {
|
||||
// Without trailing blank lines, including ones that are only quote markers ("> >").
|
||||
const text = md.slice(start, end).replace(/(?:\n[ \t>]*)+$/, '').trimEnd();
|
||||
t.mdUnit = units.push({ start, end: start + text.length }) - 1;
|
||||
return t.mdUnit;
|
||||
};
|
||||
let pos = 0;
|
||||
for (const t of tokens) {
|
||||
const found = md.indexOf(t.raw, pos);
|
||||
const start = found === -1 ? pos : found;
|
||||
pos = start + t.raw.length;
|
||||
if (t.type === 'space' || t.type === 'def') continue;
|
||||
const block = units.push({ start, end: start + t.raw.trimEnd().length }) - 1;
|
||||
if (!NO_UNIT.has(t.type)) nest(add(t, start, pos), t, start, pos);
|
||||
}
|
||||
const html = new MarkingParser({ ...marked.defaults, renderer: null }).parse(tokens);
|
||||
return { html: DOMPurify.sanitize(html), units };
|
||||
|
||||
// Nested tokens hold copies of their source without the "> " or indent, so they're found by
|
||||
// their first line, searched in order within [from, to). Returns [[token, start, end]].
|
||||
function place(children, from, to) {
|
||||
const list = children.filter((c) => !NO_UNIT.has(c.type));
|
||||
let p = from;
|
||||
const starts = list.map((c) => {
|
||||
const first = c.raw.split('\n')[0].trim();
|
||||
const i = first ? md.indexOf(first, p) : -1;
|
||||
const s = i === -1 || i >= to ? p : i;
|
||||
p = s + first.length;
|
||||
return s;
|
||||
});
|
||||
return list.map((c, k) => [c, starts[k], k + 1 < starts.length ? starts[k + 1] : to]);
|
||||
}
|
||||
function nestAll(children) {
|
||||
for (const [c, s, e] of children) nest(add(c, s, e), c, s, e);
|
||||
}
|
||||
function nest(unit, t, from, to) {
|
||||
if (t.type === 'blockquote') nestAll(place(t.tokens, from, to));
|
||||
if (t.type === 'list') {
|
||||
let p = start;
|
||||
units[block].items = t.items.map((it) => {
|
||||
const s = Math.max(p, t.raw.indexOf(it.raw, p - start) + start);
|
||||
p = s + it.raw.length;
|
||||
return units.push({ start: s, end: s + it.raw.trimEnd().length }) - 1;
|
||||
units[unit].items = place(t.items, from, to).map(([it, s, e]) => {
|
||||
// The item's own text is its first text or paragraph; anything after it is nested.
|
||||
const k = it.tokens.findIndex((c) => c.type === 'text' || c.type === 'paragraph');
|
||||
const kids = place(it.tokens.slice(k + 1), s + it.raw.split('\n')[0].length, e);
|
||||
const u = add(it, s, kids.length ? kids[0][1] : e);
|
||||
nestAll(kids);
|
||||
return u;
|
||||
});
|
||||
}
|
||||
// An empty marker before each block's HTML; tagBlocks() moves its index onto the elements
|
||||
// that follow it. Rendering block by block keeps HTML blocks that wrap Markdown
|
||||
// (<details> … </details>) intact, since the markup is still sanitized as one document.
|
||||
html += `<span data-md-mark="${block}"></span>${marked.parser(Object.assign([t], { links: tokens.links }))}`;
|
||||
if (t.type === 'table') {
|
||||
// One row per line: header, delimiter (no row of its own), body rows.
|
||||
const lines = t.raw.split('\n').filter((_, k) => k !== 1).slice(0, t.rows.length + 1);
|
||||
units[unit].rows = place(lines.map((raw) => ({ raw, type: 'row' })), from, to).map(([r, s]) => add(r, s, s + r.raw.trim().length));
|
||||
}
|
||||
}
|
||||
return { html: DOMPurify.sanitize(html), units };
|
||||
}
|
||||
|
||||
/** Moves the markers' block indexes onto the elements after them (and list items), then
|
||||
* removes the markers. Fills units[i].els. */
|
||||
/** Moves the markers' indexes onto the elements after them, and list item and table row indexes
|
||||
* onto those, then removes the markers. Fills units[i].els. */
|
||||
function tagBlocks(root, units) {
|
||||
for (const u of units) u.els = [];
|
||||
const tag = (node, i) => {
|
||||
node.dataset.mdUnit = i;
|
||||
units[i].els.push(node);
|
||||
};
|
||||
for (const m of root.querySelectorAll('span[data-md-mark]')) {
|
||||
const i = Number(m.dataset.mdMark);
|
||||
for (let n = m.nextElementSibling; n && !n.matches('span[data-md-mark]'); n = n.nextElementSibling) {
|
||||
tag(n, i);
|
||||
if (units[i].items && /^[OU]L$/.test(n.tagName)) {
|
||||
[...n.children].filter((c) => c.tagName === 'LI').forEach((li, k) => units[i].items[k] != null && tag(li, units[i].items[k]));
|
||||
const isMark = (n) => n.matches('span[data-md-mark]');
|
||||
const marks = [...root.querySelectorAll('span[data-md-mark]')];
|
||||
for (const m of marks) {
|
||||
for (let n = m.nextElementSibling; n && !isMark(n); n = n.nextElementSibling) tag(n, Number(m.dataset.mdMark));
|
||||
}
|
||||
units.forEach((u) => {
|
||||
for (const n of u.els) {
|
||||
if (u.items && /^[OU]L$/.test(n.tagName)) {
|
||||
[...n.children].filter((c) => c.tagName === 'LI').forEach((li, k) => {
|
||||
if (u.items[k] == null) return;
|
||||
// Blocks nested in the item come after a marker; its own content is everything before
|
||||
// the first one, wrapped so highlighting it leaves the nested blocks alone.
|
||||
const firstMark = [...li.children].find(isMark);
|
||||
if (!firstMark) return tag(li, u.items[k]);
|
||||
const own = el('div.md-li-own');
|
||||
while (li.firstChild !== firstMark) own.append(li.firstChild);
|
||||
li.prepend(own);
|
||||
tag(own, u.items[k]);
|
||||
});
|
||||
}
|
||||
if (u.rows && n.tagName === 'TABLE') {
|
||||
n.querySelectorAll(':scope > thead > tr, :scope > tbody > tr').forEach((tr, k) => u.rows[k] != null && tag(tr, u.rows[k]));
|
||||
}
|
||||
}
|
||||
m.remove();
|
||||
}
|
||||
});
|
||||
marks.forEach((m) => m.remove());
|
||||
}
|
||||
|
||||
/** The innermost unit whose source contains pos (a list item before its list). */
|
||||
/** The innermost unit whose source contains pos (units are pushed outer before inner). */
|
||||
function unitAt(units, pos) {
|
||||
for (let i = units.length - 1; i >= 0; i--) {
|
||||
if (units[i].start <= pos && pos <= units[i].end && units[i].els?.length) return units[i];
|
||||
|
|
@ -275,7 +335,8 @@ export async function mount(root, ctx) {
|
|||
preview.addEventListener('click', (e) => {
|
||||
if (mode !== 'split' || e.target.closest('a, input, summary, button')) return;
|
||||
if (!getSelection().isCollapsed) return; // selecting text to copy
|
||||
const node = e.target.closest('[data-md-unit]');
|
||||
let node = e.target.closest('[data-md-unit], li');
|
||||
if (node?.tagName === 'LI' && !node.dataset.mdUnit) node = node.querySelector(':scope > .md-li-own'); // its bullet or margin
|
||||
const unit = node && units[node.dataset.mdUnit];
|
||||
if (!unit) return;
|
||||
editor.focus({ preventScroll: true });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue