Compare commits
2 commits
080fb451a6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12990a9c5d | ||
|
|
c652ca456b |
2 changed files with 246 additions and 9 deletions
|
|
@ -183,8 +183,20 @@ 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-preview tr[data-md-unit] > * { transition: background-color 0.6s; }
|
||||
.md-preview tr.md-active { box-shadow: none; }
|
||||
.md-preview tr.md-active > * { background-color: 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; }
|
||||
|
|
@ -198,8 +210,8 @@ textarea { tab-size: 4; }
|
|||
.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose table { margin: 0 0 1em; }
|
||||
.prose ul, .prose ol { padding-left: 1.6em; }
|
||||
.prose li + li { margin-top: 0.25em; }
|
||||
.prose li > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; }
|
||||
.prose li:has(> input[type='checkbox']) { list-style: none; }
|
||||
.prose li > input[type='checkbox'], .prose .md-li-own > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; }
|
||||
.prose li:has(> input[type='checkbox'], > .md-li-own > input[type='checkbox']) { list-style: none; }
|
||||
.prose code { padding: 0.15em 0.35em; border-radius: 4px; background: var(--code-bg); font: 0.88em var(--mono); }
|
||||
.prose pre { padding: 12px 14px; border-radius: var(--radius); background: var(--code-bg); overflow: auto; }
|
||||
.prose pre code { padding: 0; background: none; font-size: 13px; }
|
||||
|
|
|
|||
|
|
@ -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,6 +48,124 @@ 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}], 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 = [];
|
||||
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 (!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') {
|
||||
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;
|
||||
});
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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);
|
||||
};
|
||||
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]));
|
||||
}
|
||||
}
|
||||
});
|
||||
marks.forEach((m) => m.remove());
|
||||
}
|
||||
|
||||
/** 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];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cheat sheet for the Guide dialog: [section, [[label, source], ...]].
|
||||
const GUIDE = [
|
||||
['Text', [
|
||||
|
|
@ -119,9 +237,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 +270,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 +291,113 @@ 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
|
||||
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 });
|
||||
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 +406,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