| 1 | // fidelity.mjs — origins, the side table, and the rules that keep the |
| 2 | // editor's document and its Markdown saying the same thing (spec §6.4). |
| 3 | // |
| 4 | // - Origins are opaque, monotonic and never reused: a Fidelity issues |
| 5 | // them from 1 for each page load. |
| 6 | // - The table never forgets: each origin is recorded once, with the node |
| 7 | // read for it, its source, its context, its neighbours and its seams. |
| 8 | // - Origins enter the document only where a document is built from a |
| 9 | // body: at mount (the document is made with them), on paste from |
| 10 | // Mapa's own clipboard (the pasted nodes carry them), when the parse is |
| 11 | // adopted, and when the table is rebuilt against a body after a rebase, |
| 12 | // which is the one transaction that changes origins alone, marked |
| 13 | // addToHistory false. Nothing re-stamps origins after an ordinary edit: |
| 14 | // a later holder of an origin (a split's second half, a copy-drag's |
| 15 | // copy) is treated as new where it is written (serialize.mjs), so no |
| 16 | // table update ever follows an edit, an undo or a redo. |
| 17 | // - The settle plugin runs after every edit: the reparse rule (step 6), |
| 18 | // then the marker rule, the list rules and the trailing paragraph. |
| 19 | |
| 20 | import { Plugin, PluginKey, TextSelection } from 'prosemirror-state' |
| 21 | import { Fragment } from 'prosemirror-model' |
| 22 | import { |
| 23 | parse, normalise, cleanBody, Item, Quote, Code, Rule, isFence, isFenceLike, fenceOf, closesFence |
| 24 | } from './markup.mjs' |
| 25 | import { fromBlocks } from './fromMarkdown.mjs' |
| 26 | import { |
| 27 | docBlocks, contextKey, bareNode, sameNode, serialise, serialiseBlock, |
| 28 | serialiseDetailed, structureCheck, docShapes, originAttr, originOf as heldOrigin |
| 29 | } from './serialize.mjs' |
| 30 | |
| 31 | export class Fidelity { |
| 32 | constructor () { |
| 33 | this.issued = 0 |
| 34 | this.table = new Map() |
| 35 | } |
| 36 | |
| 37 | // mint is a fresh origin: never issued before on this page load. |
| 38 | mint () { return ++this.issued } |
| 39 | |
| 40 | get (origin) { return this.table.get(origin) } |
| 41 | |
| 42 | // record enters an origin once. An entry is never changed or removed. |
| 43 | record (origin, entry) { |
| 44 | if (this.table.has(origin)) throw new Error(`origin ${origin} is already recorded`) |
| 45 | this.table.set(origin, Object.freeze(entry)) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | export const fidelityKey = new PluginKey('mapa-fidelity') |
| 50 | |
| 51 | // recordBody gives every block of body a fresh origin and records it: |
| 52 | // the node that block reads as, its source, its context, and its |
| 53 | // neighbours and seams within body. It returns the document built with |
| 54 | // those origins, its blocks (in body order) and the origins. |
| 55 | export function recordBody (schema, fidelity, body, options = {}) { |
| 56 | const text = normalise(body) |
| 57 | const blocks = parse(text) |
| 58 | const origins = blocks.map(() => fidelity.mint()) |
| 59 | const doc = fromBlocks(schema, blocks, { origin: index => origins[index], ...options }) |
| 60 | // By origin, not by place: an empty column holds a paragraph to type |
| 61 | // in that is no block of the body (columns and icons spec §1.5). |
| 62 | const placed = new Map(docBlocks(doc).map(block => [heldOrigin(block), block])) |
| 63 | const nodes = origins.map(origin => placed.get(origin)) |
| 64 | const edges = options.edges !== false |
| 65 | blocks.forEach((block, index) => { |
| 66 | const before = blocks[index - 1] |
| 67 | const after = blocks[index + 1] |
| 68 | fidelity.record(origins[index], { |
| 69 | node: nodes[index].node, |
| 70 | source: block.source, |
| 71 | context: contextKey(nodes[index]), |
| 72 | prev: before ? origins[index - 1] : null, |
| 73 | next: after ? origins[index + 1] : null, |
| 74 | before: before ? text.slice(before.to, block.from) : null, |
| 75 | after: after ? text.slice(block.to, after.from) : null, |
| 76 | leading: edges && !before ? text.slice(0, block.from) : null, |
| 77 | trailing: edges && !after ? text.slice(block.to) : null |
| 78 | }) |
| 79 | }) |
| 80 | return { doc, nodes, origins } |
| 81 | } |
| 82 | |
| 83 | // mount is the editor's document for a body, with a new table. Its |
| 84 | // origins are made with it, so mounting puts nothing in undo history. |
| 85 | export function mount (schema, body) { |
| 86 | const fidelity = new Fidelity() |
| 87 | const { doc } = recordBody(schema, fidelity, body) |
| 88 | return { doc, fidelity } |
| 89 | } |
| 90 | |
| 91 | // sameBlock is whether a document's block says what a parsed block says: |
| 92 | // the same node, origins aside and tail aside, in the same context. |
| 93 | function sameBlock (block, parsed) { |
| 94 | if (isFence(block.kind) || isFence(parsed.kind)) { |
| 95 | return block.kind === parsed.kind && contextKey(block) === contextKey(parsed) |
| 96 | } |
| 97 | return contextKey(block) === contextKey(parsed) && |
| 98 | sameNode(bareNode(block), parsed.node) |
| 99 | } |
| 100 | |
| 101 | // align pairs a's items with b's by a longest common subsequence under |
| 102 | // same, in order. The common head and tail are paired first, so the |
| 103 | // usual case (a few blocks differ) is linear. |
| 104 | function align (a, b, same) { |
| 105 | let head = 0 |
| 106 | while (head < a.length && head < b.length && same(a[head], b[head])) head++ |
| 107 | let tail = 0 |
| 108 | while (tail < a.length - head && tail < b.length - head && |
| 109 | same(a[a.length - 1 - tail], b[b.length - 1 - tail])) tail++ |
| 110 | const middle = lcs(a.slice(head, a.length - tail), b.slice(head, b.length - tail), same) |
| 111 | return [ |
| 112 | ...Array.from({ length: head }, (_, index) => [index, index]), |
| 113 | ...middle.map(([row, column]) => [row + head, column + head]), |
| 114 | ...Array.from({ length: tail }, (_, index) => |
| 115 | [a.length - tail + index, b.length - tail + index]) |
| 116 | ] |
| 117 | } |
| 118 | |
| 119 | function lcs (a, b, same) { |
| 120 | const rows = a.length |
| 121 | const columns = b.length |
| 122 | const lengths = Array.from({ length: rows + 1 }, () => new Int32Array(columns + 1)) |
| 123 | for (let row = rows - 1; row >= 0; row--) { |
| 124 | for (let column = columns - 1; column >= 0; column--) { |
| 125 | lengths[row][column] = same(a[row], b[column]) |
| 126 | ? lengths[row + 1][column + 1] + 1 |
| 127 | : Math.max(lengths[row + 1][column], lengths[row][column + 1]) |
| 128 | } |
| 129 | } |
| 130 | const pairs = [] |
| 131 | for (let row = 0, column = 0; row < rows && column < columns;) { |
| 132 | if (same(a[row], b[column])) { |
| 133 | pairs.push([row, column]) |
| 134 | row++ |
| 135 | column++ |
| 136 | } else if (lengths[row + 1][column] >= lengths[row][column + 1]) { |
| 137 | row++ |
| 138 | } else { |
| 139 | column++ |
| 140 | } |
| 141 | } |
| 142 | return pairs |
| 143 | } |
| 144 | |
| 145 | // rebuild is §6.5 step 3: the table rebuilt against body. Every block of |
| 146 | // parse(body) gets a fresh origin, recorded with its source, context, |
| 147 | // neighbours and seams from body, and each block of the document that |
| 148 | // says what one of them says takes that origin. One transaction, marked |
| 149 | // addToHistory false, changes origin attributes and nothing else. |
| 150 | // ok is step 4: serialising the document now gives exactly body. |
| 151 | export function rebuild (view, fidelity, body) { |
| 152 | const state = view.state |
| 153 | const { nodes, origins } = recordBody(state.schema, fidelity, body) |
| 154 | const parsed = nodes.slice(0, origins.length) |
| 155 | const current = serialiseDetailed(state.doc, fidelity).emitted |
| 156 | const tr = state.tr |
| 157 | for (const [mine, theirs] of align(current, parsed, sameBlock)) { |
| 158 | tr.setNodeAttribute(current[mine].pos, originAttr(current[mine]), origins[theirs]) |
| 159 | } |
| 160 | tr.setMeta('addToHistory', false).setMeta(fidelityKey, { rebuilt: true }) |
| 161 | view.dispatch(tr) |
| 162 | return { ok: serialise(view.state.doc, fidelity) === cleanBody(body) } |
| 163 | } |
| 164 | |
| 165 | // childKey is what a top-level node says: the shape and Markdown of each |
| 166 | // block it writes, from its nodes. Empty blocks write nothing, so a node |
| 167 | // that holds only empty blocks has the key '[]'. |
| 168 | function childKey (node, schema) { |
| 169 | const doc = schema.topNodeType.create(null, node) |
| 170 | const { emitted } = serialiseDetailed(doc, null, { raw: true }) |
| 171 | const shapes = docShapes(emitted) |
| 172 | return JSON.stringify(emitted.map((block, index) => [shapes[index], block.text])) |
| 173 | } |
| 174 | |
| 175 | // adoptInto makes tr's document what body says, by top-level node: each |
| 176 | // node whose key (its shape and Markdown) body still has is kept as it |
| 177 | // is, origins and all, and so is every node that writes nothing (the |
| 178 | // empty block you are typing in); the rest are replaced by body's, with |
| 179 | // fresh origins recorded from body. The selection, when it was in a |
| 180 | // replaced run, keeps its distance from the end of that run. |
| 181 | export function adoptInto (tr, fidelity, body, within = null) { |
| 182 | const schema = tr.doc.type.schema |
| 183 | // within is a column: its children are adopted, not the document's |
| 184 | // (§1.7 rule 4), at their place inside it. |
| 185 | const container = within ? within.node : tr.doc |
| 186 | const base = within ? within.start : 0 |
| 187 | const { doc: target } = recordBody(schema, fidelity, body, |
| 188 | within ? { trailing: false, edges: false } : {}) |
| 189 | const old = [] |
| 190 | container.forEach((node, offset) => { |
| 191 | const key = childKey(node, schema) |
| 192 | if (key !== '[]') old.push({ node, offset: offset + base, key }) |
| 193 | }) |
| 194 | const neu = [] |
| 195 | target.forEach(node => { |
| 196 | const key = childKey(node, schema) |
| 197 | if (key !== '[]') neu.push({ node, key }) |
| 198 | }) |
| 199 | const pairs = align(old, neu, (a, b) => a.key === b.key) |
| 200 | // gaps: [old from, old to), and the new nodes for them, last first. |
| 201 | const gaps = [] |
| 202 | let previous = [-1, -1] |
| 203 | for (const pair of [...pairs, [old.length, neu.length]]) { |
| 204 | const [oldStart, neuStart] = [previous[0] + 1, previous[1] + 1] |
| 205 | if (pair[0] > oldStart || pair[1] > neuStart) { |
| 206 | const from = oldStart < old.length |
| 207 | ? old[oldStart].offset |
| 208 | : (old[old.length - 1] ? old[old.length - 1].offset + old[old.length - 1].node.nodeSize : base) |
| 209 | const to = pair[0] > oldStart |
| 210 | ? old[pair[0] - 1].offset + old[pair[0] - 1].node.nodeSize |
| 211 | : from |
| 212 | gaps.push({ from, to, nodes: neu.slice(neuStart, pair[1]).map(item => item.node) }) |
| 213 | } |
| 214 | previous = pair |
| 215 | } |
| 216 | const head = tr.selection.head |
| 217 | let caret = null |
| 218 | for (const gap of gaps.reverse()) { |
| 219 | if (caret === null && head >= gap.from && head <= gap.to) { |
| 220 | caret = { left: inlineLength(tr.doc, head, gap.to), gap } |
| 221 | } |
| 222 | // The empty nodes inside a replaced run stay, after the new nodes. |
| 223 | const kept = [] |
| 224 | tr.doc.nodesBetween(gap.from, gap.to, (node, pos) => { |
| 225 | if (pos >= gap.from && childKey(node, schema) === '[]') kept.push(node) |
| 226 | return false |
| 227 | }) |
| 228 | tr.replaceWith(gap.from, gap.to, Fragment.from([...gap.nodes, ...kept])) |
| 229 | gap.size = [...gap.nodes, ...kept].reduce((size, node) => size + node.nodeSize, 0) |
| 230 | } |
| 231 | if (caret) { |
| 232 | const from = tr.mapping.map(caret.gap.from, -1) |
| 233 | const at = posBeforeEnd(tr.doc, from, from + caret.gap.size, caret.left) |
| 234 | tr.setSelection(TextSelection.near(tr.doc.resolve(at), -1)) |
| 235 | } |
| 236 | return tr |
| 237 | } |
| 238 | |
| 239 | // inlineLength counts the inline units (characters, breaks, atoms) |
| 240 | // between from and to. |
| 241 | function inlineLength (doc, from, to) { |
| 242 | let count = 0 |
| 243 | doc.nodesBetween(from, to, (node, pos) => { |
| 244 | if (node.isText) { |
| 245 | count += Math.min(pos + node.nodeSize, to) - Math.max(pos, from) |
| 246 | } else if (node.isInline) { |
| 247 | count += 1 |
| 248 | } |
| 249 | }) |
| 250 | return count |
| 251 | } |
| 252 | |
| 253 | // posBeforeEnd is the position left inline units before to, inside |
| 254 | // [from, to). |
| 255 | function posBeforeEnd (doc, from, to, left) { |
| 256 | let found = null |
| 257 | const textblocks = [] |
| 258 | doc.nodesBetween(from, to, (node, pos) => { |
| 259 | if (node.isTextblock) { |
| 260 | textblocks.push({ node, pos }) |
| 261 | return false |
| 262 | } |
| 263 | }) |
| 264 | for (const { node, pos } of textblocks.reverse()) { |
| 265 | const size = node.content.size |
| 266 | if (left <= size) { |
| 267 | found = pos + 1 + size - left |
| 268 | break |
| 269 | } |
| 270 | left -= size |
| 271 | } |
| 272 | if (found === null) found = textblocks.length ? textblocks[textblocks.length - 1].pos + 1 : from |
| 273 | return Math.min(Math.max(found, 0), doc.content.size) |
| 274 | } |
| 275 | |
| 276 | // applyBody makes the document say body, and rebuilds the table against |
| 277 | // it: adopting the parse (step 5's last resort), and applying a clean |
| 278 | // merge (§6.5's "Apply" and "Rebuild"). The content change is one |
| 279 | // ordinary transaction, so undo brings back the person's own text; the |
| 280 | // rebuild is not in history. |
| 281 | export function applyBody (view, fidelity, body) { |
| 282 | // Marked as the server's text, so an upload's box keeps its place in a |
| 283 | // block written again (upload.mjs, images build note I6). |
| 284 | const tr = adoptInto(view.state.tr, fidelity, body).setMeta('mapa-applied', true) |
| 285 | if (tr.docChanged) view.dispatch(tr.scrollIntoView()) |
| 286 | return rebuild(view, fidelity, body) |
| 287 | } |
| 288 | |
| 289 | // prepareSave is what autosave sends (step 5): the structure check, and, |
| 290 | // when even writing every block from its node cannot give a body that |
| 291 | // reloads as this document, the parse adopted as the document. Nothing |
| 292 | // is sent that would reload as a different document. |
| 293 | export function prepareSave (view, fidelity) { |
| 294 | const check = structureCheck(view.state.doc, fidelity) |
| 295 | if (check.ok) return { body: check.body, shapes: check.shapes, adopted: false } |
| 296 | applyBody(view, fidelity, check.body) |
| 297 | const again = structureCheck(view.state.doc, fidelity) |
| 298 | return { body: again.body, shapes: again.shapes, adopted: true } |
| 299 | } |
| 300 | |
| 301 | // The reparse rule (step 6). A block is written from its node and parsed |
| 302 | // again; when that is not exactly the block, the block becomes what the |
| 303 | // parse says. One block of the same kind is updated in place, so the |
| 304 | // caret stays where it was; anything else adopts the parse. |
| 305 | const kept = { |
| 306 | paragraph: ['marker'], |
| 307 | heading: ['level', 'marker'], |
| 308 | code_block: ['fence', 'info', 'closed', 'close'], |
| 309 | list_item: ['indent', 'bullet', 'number', 'delim', 'task', 'checked', 'marker'], |
| 310 | blockquote: ['prefix', 'marker'] |
| 311 | } |
| 312 | |
| 313 | function attrsOf (block) { |
| 314 | return block.kind === Item || block.kind === Quote ? block.holder : block.node |
| 315 | } |
| 316 | |
| 317 | export function reparseBlock (block, schema) { |
| 318 | if (block.kind === Rule || isFence(block.kind)) return null |
| 319 | const text = serialiseBlock(block) |
| 320 | if (text === '') return null |
| 321 | const parsed = parse(text) |
| 322 | if (parsed.length !== 1 || parsed[0].kind !== block.kind) return 'structural' |
| 323 | const ref = docBlocks(fromBlocks(schema, parsed, { trailing: false }))[0] |
| 324 | if (block.kind === Item && ref.list !== block.list) return 'structural' |
| 325 | const mine = attrsOf(block) |
| 326 | const theirs = attrsOf(ref) |
| 327 | const attrs = [] |
| 328 | for (const name of kept[mine.type.name] ?? []) { |
| 329 | if (JSON.stringify(mine.attrs[name]) !== JSON.stringify(theirs.attrs[name])) { |
| 330 | attrs.push([name, theirs.attrs[name]]) |
| 331 | } |
| 332 | } |
| 333 | const have = bareNode(block).content |
| 334 | const want = ref.node.content |
| 335 | const start = have.findDiffStart(want) |
| 336 | if (start === null && attrs.length === 0) return null |
| 337 | let diff = null |
| 338 | if (start !== null) { |
| 339 | let { a: endA, b: endB } = have.findDiffEnd(want) |
| 340 | const overlap = start - Math.min(endA, endB) |
| 341 | if (overlap > 0) { |
| 342 | endA += overlap |
| 343 | endB += overlap |
| 344 | } |
| 345 | diff = { from: start, to: endA, content: want.cut(start, endB) } |
| 346 | } |
| 347 | return { block, attrs, diff, text, node: ref.node } |
| 348 | } |
| 349 | |
| 350 | function applyReparse (tr, { block, attrs, diff }, origin) { |
| 351 | if (diff) { |
| 352 | const at = block.pos + 1 |
| 353 | tr.replaceWith(at + diff.from, at + diff.to, diff.content) |
| 354 | } |
| 355 | const pos = block.kind === Item || block.kind === Quote ? block.holderPos : block.pos |
| 356 | for (const [name, value] of attrs) tr.setNodeAttribute(pos, name, value) |
| 357 | tr.setNodeAttribute(block.pos, 'origin', origin) |
| 358 | } |
| 359 | |
| 360 | // reparse checks the blocks of state's document that are not in oldDoc |
| 361 | // (every block, without it) and returns the transaction that settles |
| 362 | // them, or null. |
| 363 | export function reparse (state, fidelity, oldDoc = null) { |
| 364 | const tr = state.tr |
| 365 | reparseInto(tr, fidelity, oldDoc) |
| 366 | return tr.docChanged ? tr : null |
| 367 | } |
| 368 | |
| 369 | // changedBlocks is the blocks of doc that oldDoc did not hold, in the |
| 370 | // same context (all of them without it), less the untouched ones: an |
| 371 | // untouched block re-emits its source, which is what the Markdown says by |
| 372 | // definition. Undo bringing a block back is not an edit to it; an item |
| 373 | // carried into a list of the other kind is. A later holder of an origin |
| 374 | // (a copy-drag's copy, which is the very node it copied) is always |
| 375 | // checked: it is written from its node, which need not say what its |
| 376 | // source said (review L). |
| 377 | function changedBlocks (detail, oldDoc) { |
| 378 | const blocks = detail.blocks.filter(block => !block.untouched) |
| 379 | if (!oldDoc) return blocks |
| 380 | const before = new Map(docBlocks(oldDoc).map(block => [block.node, contextKey(block)])) |
| 381 | return blocks.filter(block => !block.first || before.get(block.node) !== contextKey(block)) |
| 382 | } |
| 383 | |
| 384 | // reparseInto settles the changed blocks of tr's document. A block the |
| 385 | // reparse replaces takes a fresh origin, recorded with the Markdown it was |
| 386 | // written as (which is what it now is), its neighbours and the seams |
| 387 | // written beside it: so it re-emits those bytes, and a second reparse |
| 388 | // finds nothing to do, even where writing the parse back would not give |
| 389 | // the same parse (text holding a "*" inside a mark). |
| 390 | function reparseInto (tr, fidelity, oldDoc) { |
| 391 | const schema = tr.doc.type.schema |
| 392 | const detail = serialiseDetailed(tr.doc, fidelity) |
| 393 | const updates = [] |
| 394 | for (const block of changedBlocks(detail, oldDoc)) { |
| 395 | const update = reparseBlock(block, schema) |
| 396 | if (update === 'structural') { |
| 397 | // Inside a column, the column's own lines are parsed again, never |
| 398 | // the whole body: a layout is never adopted as text (§1.7 rule 4). |
| 399 | if (block.column > 0) adoptColumn(tr, fidelity, block) |
| 400 | else adoptInto(tr, fidelity, detail.body) |
| 401 | return |
| 402 | } |
| 403 | if (update) updates.push(update) |
| 404 | } |
| 405 | if (updates.length === 0) return |
| 406 | const fresh = new Map(updates.map(update => [update.block, fidelity.mint()])) |
| 407 | const originOf = block => fresh.get(block) ?? (block.first ? block.origin : null) |
| 408 | const { emitted } = detail |
| 409 | const entries = updates.map(({ block, text, node }) => { |
| 410 | const at = emitted.indexOf(block) |
| 411 | const before = emitted[at - 1] |
| 412 | const after = emitted[at + 1] |
| 413 | const origin = fresh.get(block) |
| 414 | return { |
| 415 | origin, |
| 416 | source: text, |
| 417 | node: node.type.create({ ...node.attrs, origin }, node.content, node.marks), |
| 418 | prev: before ? originOf(before) : null, |
| 419 | next: after ? originOf(after) : null, |
| 420 | before: before ? block.seam : null, |
| 421 | after: after ? after.seam : null, |
| 422 | leading: at === 0 ? block.entry?.leading ?? null : null, |
| 423 | trailing: at >= 0 && !after ? block.entry?.trailing ?? null : null |
| 424 | } |
| 425 | }) |
| 426 | for (const update of [...updates].reverse()) applyReparse(tr, update, fresh.get(update.block)) |
| 427 | const placed = new Map(docBlocks(tr.doc).map(block => [heldOrigin(block), block])) |
| 428 | for (const { origin, ...entry } of entries) { |
| 429 | fidelity.record(origin, { ...entry, context: contextKey(placed.get(origin)) }) |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // markerRule is step 1's: only the first holder keeps a marker. A marker |
| 434 | // held more often than before the edit (or than once) is taken from its |
| 435 | // newest holders, last first; markers a stored body already repeats are |
| 436 | // left as the body has them. The holder that keeps it is the first that |
| 437 | // held it before the edit, wherever a newcomer stands: a duplicate ^id |
| 438 | // typed above it never takes the id from the block links already name |
| 439 | // (review L). |
| 440 | function markerRule (tr, oldDoc) { |
| 441 | const count = doc => { |
| 442 | const counts = new Map() |
| 443 | for (const block of docBlocks(doc)) { |
| 444 | const marker = block.holder.attrs.marker |
| 445 | if (marker) counts.set(marker, (counts.get(marker) ?? 0) + 1) |
| 446 | } |
| 447 | return counts |
| 448 | } |
| 449 | const before = oldDoc ? count(oldDoc) : new Map() |
| 450 | const oldHolders = new Set(oldDoc ? docBlocks(oldDoc).map(block => block.holder) : []) |
| 451 | const blocks = docBlocks(tr.doc) |
| 452 | for (const [marker, held] of count(tr.doc)) { |
| 453 | let extra = held - Math.max(before.get(marker) ?? 0, 1) |
| 454 | if (extra <= 0) continue |
| 455 | const holders = blocks.filter(block => block.holder.attrs.marker === marker) |
| 456 | const keeper = holders.find(block => oldHolders.has(block.holder)) ?? holders[0] |
| 457 | const later = holders.filter(block => block !== keeper) |
| 458 | const order = [...later.filter(block => !oldHolders.has(block.holder)).reverse(), |
| 459 | ...later.filter(block => oldHolders.has(block.holder)).reverse()] |
| 460 | for (const block of order.slice(0, extra)) { |
| 461 | tr.setNodeAttribute(block.holderPos, 'marker', null) |
| 462 | } |
| 463 | |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | // indentLevel is markup's item level for an indent. |
| 468 | function indentLevel (indent) { |
| 469 | return Math.floor(String(indent ?? '').replaceAll('\t', ' ').length / 2) |
| 470 | } |
| 471 | |
| 472 | // listRule keeps each item's indent saying the depth it is drawn at |
| 473 | // (§6.3: a moved item's indent is two spaces per depth), so the body |
| 474 | // nests the way the document does; and joins two lists of one kind that |
| 475 | // have come to sit side by side, which the body would read as one. |
| 476 | function listRule (tr, fidelity) { |
| 477 | let previous = -1 |
| 478 | for (const block of serialiseDetailed(tr.doc, fidelity).emitted) { |
| 479 | if (block.kind !== Item) { |
| 480 | previous = -1 |
| 481 | continue |
| 482 | } |
| 483 | const level = indentLevel(block.holder.attrs.indent) |
| 484 | const indent = ' '.repeat(block.depth) |
| 485 | // An indent can say any depth up to one under the item above; an |
| 486 | // item drawn deeper (under an empty item, which is not written) is |
| 487 | // left to the structure check. |
| 488 | if (Math.min(level, previous + 1) !== block.depth && block.depth <= previous + 1 && |
| 489 | block.holder.attrs.indent !== indent) { |
| 490 | tr.setNodeAttribute(block.holderPos, 'indent', indent) |
| 491 | } |
| 492 | previous = block.depth |
| 493 | } |
| 494 | const joins = [] |
| 495 | const siblings = (node, start) => { |
| 496 | let offset = start |
| 497 | let last = null |
| 498 | node.forEach(child => { |
| 499 | if (last && last.type === child.type && (child.type.name === 'bullet_list' || |
| 500 | child.type.name === 'ordered_list')) joins.push(offset) |
| 501 | last = child |
| 502 | offset += child.nodeSize |
| 503 | }) |
| 504 | } |
| 505 | siblings(tr.doc, 0) |
| 506 | tr.doc.descendants((node, pos) => { |
| 507 | if (node.isTextblock) return false |
| 508 | siblings(node, pos + 1) |
| 509 | }) |
| 510 | for (const pos of joins.sort((a, b) => b - a)) tr.join(pos) |
| 511 | } |
| 512 | |
| 513 | // fenceRule is columns and icons spec §1.7's rule 1 (D16): typed text |
| 514 | // never makes or breaks a column layout. When the body would read |
| 515 | // fences the document does not hold as fences (or miss one it does), a |
| 516 | // line of text that looks like a fence is what did it: every such line |
| 517 | // takes U+200B before its first ":", as the importer writes it, and |
| 518 | // reads as the text it is. Only when needed, so a stored body that |
| 519 | // already holds such a line, read as text, is left as it is. |
| 520 | function fenceRule (tr, fidelity) { |
| 521 | const detail = serialiseDetailed(tr.doc, fidelity) |
| 522 | const held = detail.emitted.filter(block => isFence(block.kind)).map(block => block.kind) |
| 523 | const read = parse(detail.body).filter(block => isFence(block.kind)).map(block => block.kind) |
| 524 | if (held.join() === read.join()) return |
| 525 | const inserts = [] |
| 526 | tr.doc.descendants((node, pos) => { |
| 527 | if (!node.isTextblock) return true |
| 528 | if (node.type.name !== 'code_block') fenceLines(node, pos, inserts) |
| 529 | return false |
| 530 | }) |
| 531 | for (const at of inserts.reverse()) tr.insertText('\u200b', at) |
| 532 | } |
| 533 | |
| 534 | // fenceLines adds the position of the first ":" of each line of a |
| 535 | // textblock that looks like a fence: from its start, or after a break. |
| 536 | function fenceLines (node, pos, inserts) { |
| 537 | let line = '' |
| 538 | let start = pos + 1 |
| 539 | let lineStart = start |
| 540 | const close = () => { |
| 541 | if (isFenceLike(line)) inserts.push(lineStart + line.indexOf(':')) |
| 542 | } |
| 543 | node.forEach((child, offset) => { |
| 544 | if (child.type.name === 'hard_break') { |
| 545 | close() |
| 546 | line = '' |
| 547 | lineStart = start + offset + child.nodeSize |
| 548 | } else if (child.isText) { |
| 549 | line += child.text |
| 550 | } else { |
| 551 | line += '\ufffc' |
| 552 | } |
| 553 | }) |
| 554 | close() |
| 555 | } |
| 556 | |
| 557 | // The document always ends in a paragraph (§6.2). |
| 558 | function trailingRule (tr) { |
| 559 | const last = tr.doc.lastChild |
| 560 | if (!last || last.type.name !== 'paragraph') { |
| 561 | tr.insert(tr.doc.content.size, tr.doc.type.schema.nodes.paragraph.create()) |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | // settle is what follows an edit: the reparse, then the marker, list and |
| 566 | // trailing paragraph rules, repeated over what they changed until nothing |
| 567 | // changes (ProseMirror never shows a plugin its own appended transaction, |
| 568 | // so one call must finish the job). It returns a transaction, or null |
| 569 | // when the document already says what its Markdown says. |
| 570 | export function settle (state, fidelity, oldDoc = null) { |
| 571 | const tr = state.tr |
| 572 | for (let round = 0; round < 4; round++) { |
| 573 | const start = tr.doc |
| 574 | // Each round looks at every block the edit changed: a block a round |
| 575 | // has settled is untouched (or already says its parse) by then. |
| 576 | reparseInto(tr, fidelity, oldDoc) |
| 577 | fenceRule(tr, fidelity) |
| 578 | markerRule(tr, oldDoc) |
| 579 | listRule(tr, fidelity) |
| 580 | trailingRule(tr) |
| 581 | if (tr.doc === start) break |
| 582 | } |
| 583 | return tr.docChanged ? tr : null |
| 584 | } |
| 585 | |
| 586 | // fidelityPlugin runs settle after each transaction that changes the |
| 587 | // document, and holds it while an IME is composing (the reparse waits |
| 588 | // for compositionend, §6.11). options.composing replaces the view's |
| 589 | // flag, for tests. |
| 590 | export function fidelityPlugin (fidelity, options = {}) { |
| 591 | let editorView = null |
| 592 | let pending = null |
| 593 | const composing = () => options.composing ? options.composing() : editorView?.composing ?? false |
| 594 | return new Plugin({ |
| 595 | key: fidelityKey, |
| 596 | state: { init: () => fidelity, apply: (tr, value) => value }, |
| 597 | view (view) { |
| 598 | editorView = view |
| 599 | return { destroy () { editorView = null } } |
| 600 | }, |
| 601 | props: { |
| 602 | handleDOMEvents: { |
| 603 | compositionend (view) { |
| 604 | setTimeout(() => { |
| 605 | if (editorView === view && pending) { |
| 606 | view.dispatch(view.state.tr.setMeta(fidelityKey, { composed: true })) |
| 607 | } |
| 608 | }, 50) |
| 609 | return false |
| 610 | } |
| 611 | } |
| 612 | }, |
| 613 | appendTransaction (trs, oldState, newState) { |
| 614 | const changed = trs.some(tr => tr.docChanged && !tr.getMeta(fidelityKey)?.rebuilt) |
| 615 | if (!changed && !pending) return null |
| 616 | if (composing()) { |
| 617 | pending = pending ?? oldState.doc |
| 618 | return null |
| 619 | } |
| 620 | const since = pending ?? oldState.doc |
| 621 | pending = null |
| 622 | const tr = settle(newState, fidelity, since) |
| 623 | return tr ? tr.setMeta(fidelityKey, { settled: true }) : null |
| 624 | } |
| 625 | }) |
| 626 | } |
| 627 | |
| 628 | export { serialise, structureCheck } |
| 629 | |
| 630 | // adoptColumn is a structural reparse inside a column: the column's own |
| 631 | // blocks are written and parsed again as a body of their own, with |
| 632 | // every fence-like line neutralised so nothing in it can read as a |
| 633 | // layout, and they replace the column's content (§1.7 rule 4). A code |
| 634 | // fence left open runs only to the column's end, and is written closed, |
| 635 | // as the column's closer follows it. |
| 636 | function adoptColumn (tr, fidelity, block) { |
| 637 | const $at = tr.doc.resolve(block.pos) |
| 638 | let depth = $at.depth |
| 639 | while (depth > 0 && $at.node(depth).type.name !== 'column') depth-- |
| 640 | if (depth === 0) return |
| 641 | const column = $at.node(depth) |
| 642 | const start = $at.before(depth) + 1 |
| 643 | const schema = tr.doc.type.schema |
| 644 | const own = schema.topNodeType.create(null, column.content) |
| 645 | const text = neutralLines(serialiseDetailed(own, fidelity, { edges: false, raw: true }).body) |
| 646 | // By child, as at the top level: the column's blocks the parse still |
| 647 | // has stay as they are, origins and all, only the changed run is |
| 648 | // replaced, and the caret keeps its distance from that run's end |
| 649 | // (Fable on the build, round 3). |
| 650 | adoptInto(tr, fidelity, text, { node: column, start }) |
| 651 | const after = tr.doc.nodeAt(start - 1) |
| 652 | if (after && after.type.name === 'column' && after.childCount === 0) { |
| 653 | tr.insert(start, schema.nodes.paragraph.create()) |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | // neutralLines puts U+200B before the first ":" of every fence-like |
| 658 | // line of text, never inside code (§1.7 rule 1). |
| 659 | function neutralLines (text) { |
| 660 | let fence = null |
| 661 | return text.split('\n').map(line => { |
| 662 | if (fence) { |
| 663 | if (closesFence(line, fence)) fence = null |
| 664 | return line |
| 665 | } |
| 666 | const opened = fenceOf(line) |
| 667 | if (opened) { |
| 668 | fence = opened |
| 669 | return line |
| 670 | } |
| 671 | return isFenceLike(line) ? line.replace(/^([ \t]*):::/u, '$1\u200b:::') : line |
| 672 | }).join('\n') |
| 673 | } |
| 674 | |