Markdown: link editor and preview block by block in split view
Editing a block highlights its rendered copy in the preview for a moment (and scrolls it into view); clicking a block in the preview puts the cursor at its source and briefly marks that source behind the editor. Top-level blocks and list items each map to their own source range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
080fb451a6
commit
c652ca456b
2 changed files with 179 additions and 6 deletions
|
|
@ -183,8 +183,17 @@ textarea { tab-size: 4; }
|
|||
.json-workspace[data-mode='tree'] .json-text-pane { display: none; }
|
||||
|
||||
/* markdown */
|
||||
.md-edit-pane { display: flex; overflow: hidden; }
|
||||
.md-input { flex: 1; width: 100%; padding: 16px 18px; border: 0; outline: none; resize: none; background: var(--surface); line-height: 1.6; }
|
||||
.md-edit-pane { display: flex; overflow: hidden; position: relative; background: var(--surface); }
|
||||
.md-input { position: relative; flex: 1; width: 100%; padding: 16px 18px; border: 0; outline: none; resize: none; background: transparent; line-height: 1.6; }
|
||||
/* the clicked preview block's source, drawn behind the transparent editor */
|
||||
.md-backdrop { position: absolute; box-sizing: border-box; overflow: hidden; white-space: pre-wrap; overflow-wrap: break-word; color: transparent; pointer-events: none; }
|
||||
.md-backdrop mark { color: transparent; background: transparent; border-radius: 3px; transition: background-color 0.6s; }
|
||||
.md-backdrop mark.on { background: var(--sel); transition: none; }
|
||||
/* the block being edited, in the preview */
|
||||
.md-preview [data-md-unit] { border-radius: 4px; transition: background-color 0.6s, box-shadow 0.6s; }
|
||||
.md-preview .md-active { background-color: var(--accent-soft); box-shadow: 0 0 0 4px var(--accent-soft); transition: none; }
|
||||
.md-workspace[data-mode='split'] .md-preview [data-md-unit] { cursor: text; }
|
||||
.md-workspace[data-mode='split'] .md-preview :is(a, input, summary) { cursor: pointer; }
|
||||
.md-workspace[data-mode='edit'] .md-input { max-width: 900px; margin: 0 auto; }
|
||||
.md-preview { padding: 16px 24px 48px; }
|
||||
.md-workspace[data-mode='preview'] .md-preview { max-width: 820px; margin: 0 auto; padding: 32px 32px 80px; }
|
||||
|
|
|
|||
|
|
@ -48,6 +48,64 @@ export function render(md) {
|
|||
return DOMPurify.sanitize(marked.parse(md));
|
||||
}
|
||||
|
||||
/** 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>". */
|
||||
export function renderBlocks(md) {
|
||||
const tokens = marked.lexer(md);
|
||||
const units = [];
|
||||
let html = '';
|
||||
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 (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;
|
||||
});
|
||||
}
|
||||
// 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 }))}`;
|
||||
}
|
||||
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. */
|
||||
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]));
|
||||
}
|
||||
}
|
||||
m.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/** The innermost unit whose source contains pos (a list item before its list). */
|
||||
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];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cheat sheet for the Guide dialog: [section, [[label, source], ...]].
|
||||
const GUIDE = [
|
||||
['Text', [
|
||||
|
|
@ -119,9 +177,14 @@ export async function mount(root, ctx) {
|
|||
'View mode',
|
||||
);
|
||||
|
||||
// Behind the (transparent) editor: a copy of its text with one range marked, to show
|
||||
// which source a clicked preview block came from. A textarea can't highlight a range itself.
|
||||
const backdrop = el('div.md-backdrop', { 'aria-hidden': 'true', hidden: true });
|
||||
|
||||
const previewPane = el('div.pane.md-preview-pane', {}, preview);
|
||||
const workspace = el('div.md-workspace', {},
|
||||
el('div.pane.md-edit-pane', {}, editor),
|
||||
el('div.pane.md-preview-pane', {}, preview),
|
||||
el('div.pane.md-edit-pane', {}, backdrop, editor),
|
||||
previewPane,
|
||||
);
|
||||
|
||||
const toolbar = el('div.toolbar', {},
|
||||
|
|
@ -147,8 +210,19 @@ export async function mount(root, ctx) {
|
|||
|
||||
root.append(el('div.tool.md-tool', {}, toolbar, workspace));
|
||||
|
||||
let units = [];
|
||||
function update() {
|
||||
preview.innerHTML = render(editor.value);
|
||||
const out = renderBlocks(editor.value);
|
||||
preview.innerHTML = out.html; // sanitized by renderBlocks()
|
||||
units = out.units;
|
||||
tagBlocks(preview, units);
|
||||
if (flashOnRender) {
|
||||
flashOnRender = false;
|
||||
flashPreview(unitAt(units, editor.selectionStart));
|
||||
} else if (active) {
|
||||
// The preview was rebuilt: keep the highlight on the new copy of the block.
|
||||
flashPreview(unitAt(units, active.start), { keepTimer: true });
|
||||
}
|
||||
const words = (editor.value.match(/\S+/g) || []).length;
|
||||
stats.textContent = `${words} word${words === 1 ? '' : 's'}`;
|
||||
}
|
||||
|
|
@ -157,21 +231,112 @@ export async function mount(root, ctx) {
|
|||
const save = debounce(() => !fromPaste && store.set('md:text', editor.value), 400);
|
||||
const live = debounce(update, 60);
|
||||
editor.addEventListener('input', () => {
|
||||
hideBackdrop();
|
||||
flashOnRender = mode === 'split';
|
||||
live();
|
||||
save();
|
||||
});
|
||||
|
||||
// ---------- editor ↔ preview: which block is which ----------
|
||||
|
||||
// Editing (or clicking into) a block highlights its rendered copy for a moment.
|
||||
let flashOnRender = false;
|
||||
let active = null; // the highlighted unit
|
||||
let activeTimer = 0;
|
||||
function flashPreview(unit, { keepTimer = false } = {}) {
|
||||
preview.querySelectorAll('.md-active').forEach((n) => n.classList.remove('md-active'));
|
||||
active = unit;
|
||||
if (!unit) return;
|
||||
unit.els.forEach((n) => n.classList.add('md-active'));
|
||||
if (!keepTimer) {
|
||||
clearTimeout(activeTimer);
|
||||
activeTimer = setTimeout(() => {
|
||||
preview.querySelectorAll('.md-active').forEach((n) => n.classList.remove('md-active'));
|
||||
active = null;
|
||||
}, 1200);
|
||||
revealInPreview(unit.els[0]);
|
||||
}
|
||||
}
|
||||
editor.addEventListener('click', () => {
|
||||
if (mode === 'split' && editor.selectionStart === editor.selectionEnd) flashPreview(unitAt(units, editor.selectionStart));
|
||||
});
|
||||
|
||||
/** Scrolls the preview just enough to show `node`, without dragging the editor along. */
|
||||
function revealInPreview(node) {
|
||||
const pane = previewPane.getBoundingClientRect();
|
||||
const r = node.getBoundingClientRect();
|
||||
if (r.top >= pane.top && r.bottom <= pane.bottom) return;
|
||||
quietly(editor, () => {
|
||||
previewPane.scrollTop += r.top - pane.top - (r.height > pane.height ? 16 : (pane.height - r.height) / 3);
|
||||
});
|
||||
}
|
||||
|
||||
// Clicking a block in the preview puts the cursor at its source and marks that source.
|
||||
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]');
|
||||
const unit = node && units[node.dataset.mdUnit];
|
||||
if (!unit) return;
|
||||
editor.focus({ preventScroll: true });
|
||||
editor.setSelectionRange(unit.start, unit.start);
|
||||
markSource(unit.start, unit.end);
|
||||
flashPreview(unit);
|
||||
});
|
||||
|
||||
let backdropTimer = 0;
|
||||
function markSource(start, end) {
|
||||
const cs = getComputedStyle(editor);
|
||||
Object.assign(backdrop.style, {
|
||||
left: `${editor.offsetLeft}px`, top: `${editor.offsetTop}px`,
|
||||
width: `${editor.clientWidth}px`, height: `${editor.clientHeight}px`,
|
||||
padding: cs.padding, fontFamily: cs.fontFamily, fontSize: cs.fontSize, lineHeight: cs.lineHeight,
|
||||
letterSpacing: cs.letterSpacing, tabSize: cs.tabSize,
|
||||
});
|
||||
const mark = el('mark.on');
|
||||
mark.textContent = editor.value.slice(start, end);
|
||||
// The trailing newline keeps a last empty line the same height as in the textarea.
|
||||
backdrop.replaceChildren(editor.value.slice(0, start), mark, `${editor.value.slice(end)}\n`);
|
||||
backdrop.hidden = false;
|
||||
// Bring the marked text into view, a third of the way down, if it isn't already.
|
||||
const top = mark.offsetTop;
|
||||
const bottom = top + mark.offsetHeight;
|
||||
if (top < editor.scrollTop || bottom > editor.scrollTop + editor.clientHeight) {
|
||||
quietly(previewPane, () => { editor.scrollTop = Math.max(0, top - editor.clientHeight / 3); });
|
||||
}
|
||||
backdrop.scrollTop = editor.scrollTop;
|
||||
clearTimeout(backdropTimer);
|
||||
backdropTimer = setTimeout(() => {
|
||||
mark.classList.remove('on');
|
||||
backdropTimer = setTimeout(hideBackdrop, 700);
|
||||
}, 1200);
|
||||
}
|
||||
function hideBackdrop() {
|
||||
clearTimeout(backdropTimer);
|
||||
backdrop.hidden = true;
|
||||
backdrop.replaceChildren();
|
||||
}
|
||||
editor.addEventListener('scroll', () => { if (!backdrop.hidden) backdrop.scrollTop = editor.scrollTop; });
|
||||
|
||||
function setMode(m) {
|
||||
mode = m;
|
||||
workspace.dataset.mode = m;
|
||||
modes.set(m);
|
||||
if (!fromPaste) store.set('md:mode', m);
|
||||
hideBackdrop();
|
||||
if (m !== 'edit') update();
|
||||
if (m !== 'preview') editor.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
// Keep the preview roughly in step with the editor while scrolling side by side.
|
||||
let syncing = null;
|
||||
/** Runs fn (which scrolls) as if `driver` were being scrolled, so the other pane stays put. */
|
||||
function quietly(driver, fn) {
|
||||
syncing = driver;
|
||||
fn();
|
||||
clearTimeout(sync.t);
|
||||
sync.t = setTimeout(() => (syncing = null), 120);
|
||||
}
|
||||
const sync = (from, to) => () => {
|
||||
if (mode !== 'split' || (syncing && syncing !== from)) return;
|
||||
syncing = from;
|
||||
|
|
@ -180,7 +345,6 @@ export async function mount(root, ctx) {
|
|||
clearTimeout(sync.t);
|
||||
sync.t = setTimeout(() => (syncing = null), 80);
|
||||
};
|
||||
const previewPane = workspace.querySelector('.md-preview-pane');
|
||||
editor.addEventListener('scroll', sync(editor, previewPane));
|
||||
previewPane.addEventListener('scroll', sync(previewPane, editor));
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue