// fidelity.mjs — origins, the side table, and the rules that keep the // editor's document and its Markdown saying the same thing (spec §6.4). // // - Origins are opaque, monotonic and never reused: a Fidelity issues // them from 1 for each page load. // - The table never forgets: each origin is recorded once, with the node // read for it, its source, its context, its neighbours and its seams. // - Origins enter the document only where a document is built from a // body: at mount (the document is made with them), on paste from // Mapa's own clipboard (the pasted nodes carry them), when the parse is // adopted, and when the table is rebuilt against a body after a rebase, // which is the one transaction that changes origins alone, marked // addToHistory false. Nothing re-stamps origins after an ordinary edit: // a later holder of an origin (a split's second half, a copy-drag's // copy) is treated as new where it is written (serialize.mjs), so no // table update ever follows an edit, an undo or a redo. // - The settle plugin runs after every edit: the reparse rule (step 6), // then the marker rule, the list rules and the trailing paragraph. import { Plugin, PluginKey, TextSelection } from 'prosemirror-state' import { Fragment } from 'prosemirror-model' import { parse, normalise, cleanBody, Item, Quote, Code, Rule, isFence, isFenceLike, fenceOf, closesFence } from './markup.mjs' import { fromBlocks } from './fromMarkdown.mjs' import { docBlocks, contextKey, bareNode, sameNode, serialise, serialiseBlock, serialiseDetailed, structureCheck, docShapes, originAttr, originOf as heldOrigin } from './serialize.mjs' export class Fidelity { constructor () { this.issued = 0 this.table = new Map() } // mint is a fresh origin: never issued before on this page load. mint () { return ++this.issued } get (origin) { return this.table.get(origin) } // record enters an origin once. An entry is never changed or removed. record (origin, entry) { if (this.table.has(origin)) throw new Error(`origin ${origin} is already recorded`) this.table.set(origin, Object.freeze(entry)) } } export const fidelityKey = new PluginKey('mapa-fidelity') // recordBody gives every block of body a fresh origin and records it: // the node that block reads as, its source, its context, and its // neighbours and seams within body. It returns the document built with // those origins, its blocks (in body order) and the origins. export function recordBody (schema, fidelity, body, options = {}) { const text = normalise(body) const blocks = parse(text) const origins = blocks.map(() => fidelity.mint()) const doc = fromBlocks(schema, blocks, { origin: index => origins[index], ...options }) // By origin, not by place: an empty column holds a paragraph to type // in that is no block of the body (columns and icons spec §1.5). const placed = new Map(docBlocks(doc).map(block => [heldOrigin(block), block])) const nodes = origins.map(origin => placed.get(origin)) const edges = options.edges !== false blocks.forEach((block, index) => { const before = blocks[index - 1] const after = blocks[index + 1] fidelity.record(origins[index], { node: nodes[index].node, source: block.source, context: contextKey(nodes[index]), prev: before ? origins[index - 1] : null, next: after ? origins[index + 1] : null, before: before ? text.slice(before.to, block.from) : null, after: after ? text.slice(block.to, after.from) : null, leading: edges && !before ? text.slice(0, block.from) : null, trailing: edges && !after ? text.slice(block.to) : null }) }) return { doc, nodes, origins } } // mount is the editor's document for a body, with a new table. Its // origins are made with it, so mounting puts nothing in undo history. export function mount (schema, body) { const fidelity = new Fidelity() const { doc } = recordBody(schema, fidelity, body) return { doc, fidelity } } // sameBlock is whether a document's block says what a parsed block says: // the same node, origins aside and tail aside, in the same context. function sameBlock (block, parsed) { if (isFence(block.kind) || isFence(parsed.kind)) { return block.kind === parsed.kind && contextKey(block) === contextKey(parsed) } return contextKey(block) === contextKey(parsed) && sameNode(bareNode(block), parsed.node) } // align pairs a's items with b's by a longest common subsequence under // same, in order. The common head and tail are paired first, so the // usual case (a few blocks differ) is linear. function align (a, b, same) { let head = 0 while (head < a.length && head < b.length && same(a[head], b[head])) head++ let tail = 0 while (tail < a.length - head && tail < b.length - head && same(a[a.length - 1 - tail], b[b.length - 1 - tail])) tail++ const middle = lcs(a.slice(head, a.length - tail), b.slice(head, b.length - tail), same) return [ ...Array.from({ length: head }, (_, index) => [index, index]), ...middle.map(([row, column]) => [row + head, column + head]), ...Array.from({ length: tail }, (_, index) => [a.length - tail + index, b.length - tail + index]) ] } function lcs (a, b, same) { const rows = a.length const columns = b.length const lengths = Array.from({ length: rows + 1 }, () => new Int32Array(columns + 1)) for (let row = rows - 1; row >= 0; row--) { for (let column = columns - 1; column >= 0; column--) { lengths[row][column] = same(a[row], b[column]) ? lengths[row + 1][column + 1] + 1 : Math.max(lengths[row + 1][column], lengths[row][column + 1]) } } const pairs = [] for (let row = 0, column = 0; row < rows && column < columns;) { if (same(a[row], b[column])) { pairs.push([row, column]) row++ column++ } else if (lengths[row + 1][column] >= lengths[row][column + 1]) { row++ } else { column++ } } return pairs } // rebuild is §6.5 step 3: the table rebuilt against body. Every block of // parse(body) gets a fresh origin, recorded with its source, context, // neighbours and seams from body, and each block of the document that // says what one of them says takes that origin. One transaction, marked // addToHistory false, changes origin attributes and nothing else. // ok is step 4: serialising the document now gives exactly body. export function rebuild (view, fidelity, body) { const state = view.state const { nodes, origins } = recordBody(state.schema, fidelity, body) const parsed = nodes.slice(0, origins.length) const current = serialiseDetailed(state.doc, fidelity).emitted const tr = state.tr for (const [mine, theirs] of align(current, parsed, sameBlock)) { tr.setNodeAttribute(current[mine].pos, originAttr(current[mine]), origins[theirs]) } tr.setMeta('addToHistory', false).setMeta(fidelityKey, { rebuilt: true }) view.dispatch(tr) return { ok: serialise(view.state.doc, fidelity) === cleanBody(body) } } // childKey is what a top-level node says: the shape and Markdown of each // block it writes, from its nodes. Empty blocks write nothing, so a node // that holds only empty blocks has the key '[]'. function childKey (node, schema) { const doc = schema.topNodeType.create(null, node) const { emitted } = serialiseDetailed(doc, null, { raw: true }) const shapes = docShapes(emitted) return JSON.stringify(emitted.map((block, index) => [shapes[index], block.text])) } // adoptInto makes tr's document what body says, by top-level node: each // node whose key (its shape and Markdown) body still has is kept as it // is, origins and all, and so is every node that writes nothing (the // empty block you are typing in); the rest are replaced by body's, with // fresh origins recorded from body. The selection, when it was in a // replaced run, keeps its distance from the end of that run. export function adoptInto (tr, fidelity, body, within = null) { const schema = tr.doc.type.schema // within is a column: its children are adopted, not the document's // (§1.7 rule 4), at their place inside it. const container = within ? within.node : tr.doc const base = within ? within.start : 0 const { doc: target } = recordBody(schema, fidelity, body, within ? { trailing: false, edges: false } : {}) const old = [] container.forEach((node, offset) => { const key = childKey(node, schema) if (key !== '[]') old.push({ node, offset: offset + base, key }) }) const neu = [] target.forEach(node => { const key = childKey(node, schema) if (key !== '[]') neu.push({ node, key }) }) const pairs = align(old, neu, (a, b) => a.key === b.key) // gaps: [old from, old to), and the new nodes for them, last first. const gaps = [] let previous = [-1, -1] for (const pair of [...pairs, [old.length, neu.length]]) { const [oldStart, neuStart] = [previous[0] + 1, previous[1] + 1] if (pair[0] > oldStart || pair[1] > neuStart) { const from = oldStart < old.length ? old[oldStart].offset : (old[old.length - 1] ? old[old.length - 1].offset + old[old.length - 1].node.nodeSize : base) const to = pair[0] > oldStart ? old[pair[0] - 1].offset + old[pair[0] - 1].node.nodeSize : from gaps.push({ from, to, nodes: neu.slice(neuStart, pair[1]).map(item => item.node) }) } previous = pair } const head = tr.selection.head let caret = null for (const gap of gaps.reverse()) { if (caret === null && head >= gap.from && head <= gap.to) { caret = { left: inlineLength(tr.doc, head, gap.to), gap } } // The empty nodes inside a replaced run stay, after the new nodes. const kept = [] tr.doc.nodesBetween(gap.from, gap.to, (node, pos) => { if (pos >= gap.from && childKey(node, schema) === '[]') kept.push(node) return false }) tr.replaceWith(gap.from, gap.to, Fragment.from([...gap.nodes, ...kept])) gap.size = [...gap.nodes, ...kept].reduce((size, node) => size + node.nodeSize, 0) } if (caret) { const from = tr.mapping.map(caret.gap.from, -1) const at = posBeforeEnd(tr.doc, from, from + caret.gap.size, caret.left) tr.setSelection(TextSelection.near(tr.doc.resolve(at), -1)) } return tr } // inlineLength counts the inline units (characters, breaks, atoms) // between from and to. function inlineLength (doc, from, to) { let count = 0 doc.nodesBetween(from, to, (node, pos) => { if (node.isText) { count += Math.min(pos + node.nodeSize, to) - Math.max(pos, from) } else if (node.isInline) { count += 1 } }) return count } // posBeforeEnd is the position left inline units before to, inside // [from, to). function posBeforeEnd (doc, from, to, left) { let found = null const textblocks = [] doc.nodesBetween(from, to, (node, pos) => { if (node.isTextblock) { textblocks.push({ node, pos }) return false } }) for (const { node, pos } of textblocks.reverse()) { const size = node.content.size if (left <= size) { found = pos + 1 + size - left break } left -= size } if (found === null) found = textblocks.length ? textblocks[textblocks.length - 1].pos + 1 : from return Math.min(Math.max(found, 0), doc.content.size) } // applyBody makes the document say body, and rebuilds the table against // it: adopting the parse (step 5's last resort), and applying a clean // merge (§6.5's "Apply" and "Rebuild"). The content change is one // ordinary transaction, so undo brings back the person's own text; the // rebuild is not in history. export function applyBody (view, fidelity, body) { // Marked as the server's text, so an upload's box keeps its place in a // block written again (upload.mjs, images build note I6). const tr = adoptInto(view.state.tr, fidelity, body).setMeta('mapa-applied', true) if (tr.docChanged) view.dispatch(tr.scrollIntoView()) return rebuild(view, fidelity, body) } // prepareSave is what autosave sends (step 5): the structure check, and, // when even writing every block from its node cannot give a body that // reloads as this document, the parse adopted as the document. Nothing // is sent that would reload as a different document. export function prepareSave (view, fidelity) { const check = structureCheck(view.state.doc, fidelity) if (check.ok) return { body: check.body, shapes: check.shapes, adopted: false } applyBody(view, fidelity, check.body) const again = structureCheck(view.state.doc, fidelity) return { body: again.body, shapes: again.shapes, adopted: true } } // The reparse rule (step 6). A block is written from its node and parsed // again; when that is not exactly the block, the block becomes what the // parse says. One block of the same kind is updated in place, so the // caret stays where it was; anything else adopts the parse. const kept = { paragraph: ['marker'], heading: ['level', 'marker'], code_block: ['fence', 'info', 'closed', 'close'], list_item: ['indent', 'bullet', 'number', 'delim', 'task', 'checked', 'marker'], blockquote: ['prefix', 'marker'] } function attrsOf (block) { return block.kind === Item || block.kind === Quote ? block.holder : block.node } export function reparseBlock (block, schema) { if (block.kind === Rule || isFence(block.kind)) return null const text = serialiseBlock(block) if (text === '') return null const parsed = parse(text) if (parsed.length !== 1 || parsed[0].kind !== block.kind) return 'structural' const ref = docBlocks(fromBlocks(schema, parsed, { trailing: false }))[0] if (block.kind === Item && ref.list !== block.list) return 'structural' const mine = attrsOf(block) const theirs = attrsOf(ref) const attrs = [] for (const name of kept[mine.type.name] ?? []) { if (JSON.stringify(mine.attrs[name]) !== JSON.stringify(theirs.attrs[name])) { attrs.push([name, theirs.attrs[name]]) } } const have = bareNode(block).content const want = ref.node.content const start = have.findDiffStart(want) if (start === null && attrs.length === 0) return null let diff = null if (start !== null) { let { a: endA, b: endB } = have.findDiffEnd(want) const overlap = start - Math.min(endA, endB) if (overlap > 0) { endA += overlap endB += overlap } diff = { from: start, to: endA, content: want.cut(start, endB) } } return { block, attrs, diff, text, node: ref.node } } function applyReparse (tr, { block, attrs, diff }, origin) { if (diff) { const at = block.pos + 1 tr.replaceWith(at + diff.from, at + diff.to, diff.content) } const pos = block.kind === Item || block.kind === Quote ? block.holderPos : block.pos for (const [name, value] of attrs) tr.setNodeAttribute(pos, name, value) tr.setNodeAttribute(block.pos, 'origin', origin) } // reparse checks the blocks of state's document that are not in oldDoc // (every block, without it) and returns the transaction that settles // them, or null. export function reparse (state, fidelity, oldDoc = null) { const tr = state.tr reparseInto(tr, fidelity, oldDoc) return tr.docChanged ? tr : null } // changedBlocks is the blocks of doc that oldDoc did not hold, in the // same context (all of them without it), less the untouched ones: an // untouched block re-emits its source, which is what the Markdown says by // definition. Undo bringing a block back is not an edit to it; an item // carried into a list of the other kind is. A later holder of an origin // (a copy-drag's copy, which is the very node it copied) is always // checked: it is written from its node, which need not say what its // source said (review L). function changedBlocks (detail, oldDoc) { const blocks = detail.blocks.filter(block => !block.untouched) if (!oldDoc) return blocks const before = new Map(docBlocks(oldDoc).map(block => [block.node, contextKey(block)])) return blocks.filter(block => !block.first || before.get(block.node) !== contextKey(block)) } // reparseInto settles the changed blocks of tr's document. A block the // reparse replaces takes a fresh origin, recorded with the Markdown it was // written as (which is what it now is), its neighbours and the seams // written beside it: so it re-emits those bytes, and a second reparse // finds nothing to do, even where writing the parse back would not give // the same parse (text holding a "*" inside a mark). function reparseInto (tr, fidelity, oldDoc) { const schema = tr.doc.type.schema const detail = serialiseDetailed(tr.doc, fidelity) const updates = [] for (const block of changedBlocks(detail, oldDoc)) { const update = reparseBlock(block, schema) if (update === 'structural') { // Inside a column, the column's own lines are parsed again, never // the whole body: a layout is never adopted as text (§1.7 rule 4). if (block.column > 0) adoptColumn(tr, fidelity, block) else adoptInto(tr, fidelity, detail.body) return } if (update) updates.push(update) } if (updates.length === 0) return const fresh = new Map(updates.map(update => [update.block, fidelity.mint()])) const originOf = block => fresh.get(block) ?? (block.first ? block.origin : null) const { emitted } = detail const entries = updates.map(({ block, text, node }) => { const at = emitted.indexOf(block) const before = emitted[at - 1] const after = emitted[at + 1] const origin = fresh.get(block) return { origin, source: text, node: node.type.create({ ...node.attrs, origin }, node.content, node.marks), prev: before ? originOf(before) : null, next: after ? originOf(after) : null, before: before ? block.seam : null, after: after ? after.seam : null, leading: at === 0 ? block.entry?.leading ?? null : null, trailing: at >= 0 && !after ? block.entry?.trailing ?? null : null } }) for (const update of [...updates].reverse()) applyReparse(tr, update, fresh.get(update.block)) const placed = new Map(docBlocks(tr.doc).map(block => [heldOrigin(block), block])) for (const { origin, ...entry } of entries) { fidelity.record(origin, { ...entry, context: contextKey(placed.get(origin)) }) } } // markerRule is step 1's: only the first holder keeps a marker. A marker // held more often than before the edit (or than once) is taken from its // newest holders, last first; markers a stored body already repeats are // left as the body has them. The holder that keeps it is the first that // held it before the edit, wherever a newcomer stands: a duplicate ^id // typed above it never takes the id from the block links already name // (review L). function markerRule (tr, oldDoc) { const count = doc => { const counts = new Map() for (const block of docBlocks(doc)) { const marker = block.holder.attrs.marker if (marker) counts.set(marker, (counts.get(marker) ?? 0) + 1) } return counts } const before = oldDoc ? count(oldDoc) : new Map() const oldHolders = new Set(oldDoc ? docBlocks(oldDoc).map(block => block.holder) : []) const blocks = docBlocks(tr.doc) for (const [marker, held] of count(tr.doc)) { let extra = held - Math.max(before.get(marker) ?? 0, 1) if (extra <= 0) continue const holders = blocks.filter(block => block.holder.attrs.marker === marker) const keeper = holders.find(block => oldHolders.has(block.holder)) ?? holders[0] const later = holders.filter(block => block !== keeper) const order = [...later.filter(block => !oldHolders.has(block.holder)).reverse(), ...later.filter(block => oldHolders.has(block.holder)).reverse()] for (const block of order.slice(0, extra)) { tr.setNodeAttribute(block.holderPos, 'marker', null) } } } // indentLevel is markup's item level for an indent. function indentLevel (indent) { return Math.floor(String(indent ?? '').replaceAll('\t', ' ').length / 2) } // listRule keeps each item's indent saying the depth it is drawn at // (§6.3: a moved item's indent is two spaces per depth), so the body // nests the way the document does; and joins two lists of one kind that // have come to sit side by side, which the body would read as one. function listRule (tr, fidelity) { let previous = -1 for (const block of serialiseDetailed(tr.doc, fidelity).emitted) { if (block.kind !== Item) { previous = -1 continue } const level = indentLevel(block.holder.attrs.indent) const indent = ' '.repeat(block.depth) // An indent can say any depth up to one under the item above; an // item drawn deeper (under an empty item, which is not written) is // left to the structure check. if (Math.min(level, previous + 1) !== block.depth && block.depth <= previous + 1 && block.holder.attrs.indent !== indent) { tr.setNodeAttribute(block.holderPos, 'indent', indent) } previous = block.depth } const joins = [] const siblings = (node, start) => { let offset = start let last = null node.forEach(child => { if (last && last.type === child.type && (child.type.name === 'bullet_list' || child.type.name === 'ordered_list')) joins.push(offset) last = child offset += child.nodeSize }) } siblings(tr.doc, 0) tr.doc.descendants((node, pos) => { if (node.isTextblock) return false siblings(node, pos + 1) }) for (const pos of joins.sort((a, b) => b - a)) tr.join(pos) } // fenceRule is columns and icons spec §1.7's rule 1 (D16): typed text // never makes or breaks a column layout. When the body would read // fences the document does not hold as fences (or miss one it does), a // line of text that looks like a fence is what did it: every such line // takes U+200B before its first ":", as the importer writes it, and // reads as the text it is. Only when needed, so a stored body that // already holds such a line, read as text, is left as it is. function fenceRule (tr, fidelity) { const detail = serialiseDetailed(tr.doc, fidelity) const held = detail.emitted.filter(block => isFence(block.kind)).map(block => block.kind) const read = parse(detail.body).filter(block => isFence(block.kind)).map(block => block.kind) if (held.join() === read.join()) return const inserts = [] tr.doc.descendants((node, pos) => { if (!node.isTextblock) return true if (node.type.name !== 'code_block') fenceLines(node, pos, inserts) return false }) for (const at of inserts.reverse()) tr.insertText('\u200b', at) } // fenceLines adds the position of the first ":" of each line of a // textblock that looks like a fence: from its start, or after a break. function fenceLines (node, pos, inserts) { let line = '' let start = pos + 1 let lineStart = start const close = () => { if (isFenceLike(line)) inserts.push(lineStart + line.indexOf(':')) } node.forEach((child, offset) => { if (child.type.name === 'hard_break') { close() line = '' lineStart = start + offset + child.nodeSize } else if (child.isText) { line += child.text } else { line += '\ufffc' } }) close() } // The document always ends in a paragraph (§6.2). function trailingRule (tr) { const last = tr.doc.lastChild if (!last || last.type.name !== 'paragraph') { tr.insert(tr.doc.content.size, tr.doc.type.schema.nodes.paragraph.create()) } } // settle is what follows an edit: the reparse, then the marker, list and // trailing paragraph rules, repeated over what they changed until nothing // changes (ProseMirror never shows a plugin its own appended transaction, // so one call must finish the job). It returns a transaction, or null // when the document already says what its Markdown says. export function settle (state, fidelity, oldDoc = null) { const tr = state.tr for (let round = 0; round < 4; round++) { const start = tr.doc // Each round looks at every block the edit changed: a block a round // has settled is untouched (or already says its parse) by then. reparseInto(tr, fidelity, oldDoc) fenceRule(tr, fidelity) markerRule(tr, oldDoc) listRule(tr, fidelity) trailingRule(tr) if (tr.doc === start) break } return tr.docChanged ? tr : null } // fidelityPlugin runs settle after each transaction that changes the // document, and holds it while an IME is composing (the reparse waits // for compositionend, §6.11). options.composing replaces the view's // flag, for tests. export function fidelityPlugin (fidelity, options = {}) { let editorView = null let pending = null const composing = () => options.composing ? options.composing() : editorView?.composing ?? false return new Plugin({ key: fidelityKey, state: { init: () => fidelity, apply: (tr, value) => value }, view (view) { editorView = view return { destroy () { editorView = null } } }, props: { handleDOMEvents: { compositionend (view) { setTimeout(() => { if (editorView === view && pending) { view.dispatch(view.state.tr.setMeta(fidelityKey, { composed: true })) } }, 50) return false } } }, appendTransaction (trs, oldState, newState) { const changed = trs.some(tr => tr.docChanged && !tr.getMeta(fidelityKey)?.rebuilt) if (!changed && !pending) return null if (composing()) { pending = pending ?? oldState.doc return null } const since = pending ?? oldState.doc pending = null const tr = settle(newState, fidelity, since) return tr ? tr.setMeta(fidelityKey, { settled: true }) : null } }) } export { serialise, structureCheck } // adoptColumn is a structural reparse inside a column: the column's own // blocks are written and parsed again as a body of their own, with // every fence-like line neutralised so nothing in it can read as a // layout, and they replace the column's content (§1.7 rule 4). A code // fence left open runs only to the column's end, and is written closed, // as the column's closer follows it. function adoptColumn (tr, fidelity, block) { const $at = tr.doc.resolve(block.pos) let depth = $at.depth while (depth > 0 && $at.node(depth).type.name !== 'column') depth-- if (depth === 0) return const column = $at.node(depth) const start = $at.before(depth) + 1 const schema = tr.doc.type.schema const own = schema.topNodeType.create(null, column.content) const text = neutralLines(serialiseDetailed(own, fidelity, { edges: false, raw: true }).body) // By child, as at the top level: the column's blocks the parse still // has stay as they are, origins and all, only the changed run is // replaced, and the caret keeps its distance from that run's end // (Fable on the build, round 3). adoptInto(tr, fidelity, text, { node: column, start }) const after = tr.doc.nodeAt(start - 1) if (after && after.type.name === 'column' && after.childCount === 0) { tr.insert(start, schema.nodes.paragraph.create()) } } // neutralLines puts U+200B before the first ":" of every fence-like // line of text, never inside code (§1.7 rule 1). function neutralLines (text) { let fence = null return text.split('\n').map(line => { if (fence) { if (closesFence(line, fence)) fence = null return line } const opened = fenceOf(line) if (opened) { fence = opened return line } return isFenceLike(line) ? line.replace(/^([ \t]*):::/u, '$1\u200b:::') : line }).join('\n') }