// serialize.mjs — the editor's document as Mapa Markdown (spec §6.4). // // A block nobody touched is written back from the source it was read // from, byte for byte, and the bytes between two blocks that were // neighbours when they were read are kept. Everything else is written // from its node, with the syntax its kept attributes record. The side // table that holds sources and seams is fidelity.mjs's; this file only // reads it, through table.get(origin). // // A Mapa block is one textblock, or one rule (§6.3). docBlocks lists // them in document order, which is the order markup.parse gives them. import { parse, cleanBody, normalise, goTrimSpace, spans, isDate, isRuleLine, isFenceLine, fenceOf, closesFence, Paragraph, Heading, Item, Code, Quote, Rule, WikiLink, Embed, Image, ImagePrefix, Columns, Column, ColumnEnd, ColumnsEnd, isFence } from './markup.mjs' import { fromBlocks } from './fromMarkdown.mjs' const lists = new Set(['bullet_list', 'ordered_list']) // docBlocks is a document's Mapa blocks, each with: // - kind, as markup names it, and node, the textblock (or rule) that // holds its origin, at pos; // - holder, the node that holds its ^id (the list_item or blockquote // around an item's or quote's paragraph), at holderPos; // - for an item: depth, list (its list's type), listPos and listStart. export function docBlocks (doc) { const out = [] doc.forEach((child, offset) => topBlock(child, offset, out)) return out } function push (out, block) { block.index = out.length out.push(block) } // originAttr is the attribute that holds a block's origin: a textblock's // (or rule's) own origin, or, for a column layout's fence line, the // openOrigin or closeOrigin of the layout or column it opens or closes // (columns and icons spec §1.7). export function originAttr (block) { if (block.kind === Columns || block.kind === Column) return 'openOrigin' if (block.kind === ColumnEnd || block.kind === ColumnsEnd) return 'closeOrigin' return 'origin' } export function originOf (block) { return block.node.attrs[originAttr(block)] ?? null } // layoutBlocks is a layout's blocks: its fences, each column's fences, // and each column's own blocks between them, each with its column. function layoutBlocks (node, pos, out) { push(out, { kind: Columns, node, pos, holder: node, holderPos: pos, column: 0 }) node.forEach((column, offset, index) => { const at = pos + 1 + offset const number = index + 1 push(out, { kind: Column, node: column, pos: at, holder: column, holderPos: at, column: number }) const from = out.length column.forEach((child, childOffset) => topBlock(child, at + 1 + childOffset, out)) for (const inside of out.slice(from)) inside.column = number push(out, { kind: ColumnEnd, node: column, pos: at, holder: column, holderPos: at, column: number }) }) push(out, { kind: ColumnsEnd, node, pos, holder: node, holderPos: pos, column: 0 }) } function topBlock (node, pos, out) { switch (node.type.name) { case 'columns': return layoutBlocks(node, pos, out) case 'paragraph': return push(out, { kind: Paragraph, node, pos, holder: node, holderPos: pos }) case 'heading': return push(out, { kind: Heading, node, pos, holder: node, holderPos: pos }) case 'code_block': return push(out, { kind: Code, node, pos, holder: node, holderPos: pos }) case 'horizontal_rule': return push(out, { kind: Rule, node, pos, holder: node, holderPos: pos }) case 'blockquote': if (node.firstChild?.type.name === 'paragraph') { push(out, { kind: Quote, node: node.firstChild, pos: pos + 1, holder: node, holderPos: pos }) } return } if (lists.has(node.type.name)) listBlocks(node, pos, 0, out) } function listBlocks (list, pos, depth, out) { list.forEach((item, offset, index) => { const itemPos = pos + 1 + offset item.forEach((child, childOffset, childIndex) => { const childPos = itemPos + 1 + childOffset if (childIndex === 0 && child.type.name === 'paragraph') { push(out, { kind: Item, node: child, pos: childPos, holder: item, holderPos: itemPos, depth, list: list.type.name, listPos: pos, listStart: index === 0 }) } else if (lists.has(child.type.name)) { listBlocks(child, childPos, depth + 1, out) } }) }) } // contextKey is what, besides its own node, decides how a block is // written: its kind, and an item's list attributes, depth and list kind, // or a quote's prefixes and ^id (§6.4 step 1). export function contextKey (block) { const attrs = block.holder.attrs if (isFence(block.kind)) return JSON.stringify([block.kind, attrs.fence]) switch (block.kind) { case Item: return JSON.stringify([Item, block.depth, block.list, attrs.indent, attrs.bullet, attrs.number, attrs.delim, attrs.task, attrs.checked, attrs.marker]) case Quote: return JSON.stringify([Quote, attrs.prefix, attrs.marker]) } return block.kind } // The tail: a textblock's trailing hard breaks, and the blank text after // them, have no Markdown form outside a quote (a blank line ends a // block). Like an empty block, the editor keeps them on screen while you // type and writes nothing for them. function tailStart (node) { let pos = node.content.size let start = null for (let index = node.childCount - 1; index >= 0; index--) { const child = node.child(index) if (child.type.name === 'hard_break') start = pos - child.nodeSize else if (!(child.isText && goTrimSpace(child.text) === '')) break pos -= child.nodeSize } return start } // bareNode is a block's node without its tail. export function bareNode (block) { if (block.kind === Quote || block.kind === Code || block.kind === Rule) { return block.node } const start = tailStart(block.node) if (start === null) return block.node return block.node.copy(block.node.content.cut(0, start)) } // isUntouched is §6.4 step 2: the first holder of its origin (decided by // the caller), equal to the node its entry recorded, in the same context. // A tail added since does not count as a change: it is written as // nothing either way. Nor does a heading's source attribute, which // records the line it was read from and is never drawn or reparsed. export function isUntouched (block, entry) { if (!entry) return false if (isFence(block.kind)) { return entry.node.type === block.node.type && contextKey(block) === entry.context } const node = block.node if (node !== entry.node && !node.eq(entry.node) && !sameNode(bareNode(block), entry.node)) return false return contextKey(block) === entry.context } // sameNode is eq, except that origins and a heading's source are not // compared (the caller has already matched origins, or is assigning one). export function sameNode (node, other) { if (node.type !== other.type || !node.content.eq(other.content)) return false for (const name of Object.keys(node.attrs)) { if (name === 'origin') continue if (name === 'source' && node.type.name === 'heading') continue if (JSON.stringify(node.attrs[name]) !== JSON.stringify(other.attrs[name])) { return false } } return true } // serialiseBlock writes one block from its node (§6.4 step 4). last says // whether nothing follows it: a fence that is not last must be closed. // An empty block is written as nothing (''). export function serialiseBlock (block, { last = true } = {}) { const node = block.node switch (block.kind) { case Paragraph: { const text = inline(bareNode(block)) return blank(text) ? '' : text + markerTail(block) } case Heading: { const text = inline(bareNode(block)) return blank(text) ? '' : headingPrefix(node.attrs) + text + markerTail(block) } case Item: return itemText(block) case Quote: return quoteText(block) case Code: return codeText(node, last) case Rule: return isRuleLine(node.attrs.source ?? '') ? node.attrs.source : '---' case Columns: case Column: case ColumnEnd: case ColumnsEnd: return fenceText(block) } return '' } // fenceText writes a layout's fence line from its node: a layout's own // colons, when they are four or more, else four; a column's always three, // fewer than any layout's, so a column written from its node always // closes inside its layout (an untouched one re-emits its source). function fenceText (block) { const outer = block.kind === Columns || block.kind === ColumnsEnd const own = Number(block.node.attrs.fence) const colons = outer ? (Number.isInteger(own) && own >= 4 ? own : 4) : 3 const word = block.kind === Columns ? ' columns' : block.kind === Column ? ' column' : '' return ':'.repeat(colons) + word } function blank (text) { return goTrimSpace(text) === '' } function markerTail (block) { const marker = block.holder.attrs.marker return marker && /^[A-Za-z0-9-]{1,40}$/u.test(marker) ? ` ^${marker}` : '' } function headingPrefix (attrs) { const level = Math.min(Math.max(attrs.level ?? 1, 1), 6) const kept = /^(#{1,6})([ \t]+)/u.exec(attrs.source ?? '') if (kept && kept[1].length === level) return kept[0] return '#'.repeat(level) + ' ' } function itemText (block) { const attrs = block.holder.attrs const text = inline(bareNode(block)) if (blank(text)) return '' const indent = /^[ \t]*$/u.test(attrs.indent ?? '') ? attrs.indent ?? '' : '' let mark if (block.list === 'ordered_list') { const number = /^[0-9]{1,9}$/u.test(attrs.number ?? '') ? attrs.number : '1' mark = number + (attrs.delim === ')' ? ')' : '.') } else { mark = ['-', '*', '+'].includes(attrs.bullet) ? attrs.bullet : '-' } const box = attrs.task ? `[${[' ', 'x', 'X'].includes(attrs.checked) ? attrs.checked : ' '}] ` : '' return `${indent}${mark} ${box}${text}${markerTail(block)}` } // quoteText puts each line's own prefix back. A quote keeps its tail: a // line of only ">" is a line of the quote. function quoteText (block) { const text = inline(block.node) if (text === '') return '' const prefixes = Array.isArray(block.holder.attrs.prefix) ? block.holder.attrs.prefix : [] return (text + markerTail(block)).split('\n').map((line, index) => { let prefix = prefixes[index] ?? prefixes[0] ?? '> ' if (!/^ *> ?$/u.test(prefix)) prefix = '> ' // quoteText drops one space after the ">": a line that starts with // a space needs that space written. if (!prefix.endsWith(' ') && line.startsWith(' ')) prefix += ' ' return prefix + line }).join('\n') } function codeText (node, last) { const attrs = node.attrs const open = /^ {0,3}(?:`{3,}|~{3,})$/u.test(attrs.fence ?? '') ? attrs.fence : '```' let out = open + String(attrs.info ?? '').split('\n')[0] if (node.textContent !== '') out += '\n' + node.textContent if (attrs.close != null && isFenceLine(attrs.close)) out += '\n' + attrs.close if (!last && !fenceClosed(out)) out += '\n' + open.trimStart() return out } // fenceClosed is whether a fence's source ends with its closing line. export function fenceClosed (source) { const lines = source.split('\n') return lines.length > 1 && closesFence(lines[lines.length - 1], fenceOf(lines[0])) } // inline writes a textblock's content. Marks follow §6.3: a mark never // spans code, a link or an atom, so each run of plain text between them // takes its emphasis on its own; em goes outside strong; whitespace at a // mark's edge goes outside its delimiters. export function inline (node) { const pieces = [] node.forEach(child => { const has = name => child.marks.some(mark => mark.type.name === name) if (child.isText) { const link = child.marks.find(mark => mark.type.name === 'link') const last = pieces[pieces.length - 1] if (has('code')) { if (last?.kind === 'code') last.text += child.text else pieces.push({ kind: 'code', text: child.text }) } else if (link) { if (last?.kind === 'link' && last.mark.eq(link)) last.text += child.text else pieces.push({ kind: 'link', text: child.text, mark: link }) } else { pieces.push({ kind: 'text', text: child.text, em: has('em'), strong: has('strong') }) } } else if (child.type.name === 'hard_break') { const indent = /^[ \t]*/u.exec(child.attrs.indent ?? '')[0] pieces.push({ kind: 'text', text: '\n' + indent, em: has('em'), strong: has('strong') }) } else { pieces.push({ kind: 'atom', text: atomSource(child) }) } }) let out = '' for (let index = 0; index < pieces.length;) { const piece = pieces[index] if (piece.kind === 'text') { let end = index while (end < pieces.length && pieces[end].kind === 'text') end++ out += emphasis(pieces.slice(index, end)) index = end continue } if (piece.kind === 'code') out += '`' + piece.text + '`' else if (piece.kind === 'link') out += linkText(piece) else out += piece.text index++ } return normalise(out) } function linkText ({ text, mark }) { if (mark.attrs.bare && text === mark.attrs.href) return text return `[${text}](${mark.attrs.href})` } function emphasis (run) { return groups(run, 'em', part => strongs(part), '*') } function strongs (run) { return groups(run, 'strong', part => part.map(piece => piece.text).join(''), '**') } // groups wraps each stretch of run that has the mark in delim. function groups (run, mark, inner, delim) { let out = '' for (let index = 0; index < run.length;) { let end = index while (end < run.length && run[end][mark] === run[index][mark]) end++ const text = inner(run.slice(index, end)) out += run[index][mark] ? wrap(text, delim) : text index = end } return out } // wrap puts text in delim with its edge whitespace (Go's ASCII \s) // outside, because a delimiter needs a non-space beside it. function wrap (text, delim) { const parts = /^([\t\n\f\r ]*)([^]*?)([\t\n\f\r ]*)$/u.exec(text) if (parts[2] === '') return text return parts[1] + delim + parts[2] + delim + parts[3] } // atomSource is an atom's Markdown: its source while that still says // exactly what the atom holds, otherwise written from its attributes. export function atomSource (node) { const attrs = node.attrs if (attrs.source != null && atomSays(node, attrs.source)) return attrs.source if (node.type.name === 'embed') return `![[${attrs.ref}]]` if (node.type.name === 'image') return `![${attrs.alt ?? ''}](${ImagePrefix}${attrs.id})` const target = node.type.name === 'datelink' ? attrs.date : attrs.target return `[[${target}${attrs.anchor ? '#^' + attrs.anchor : ''}` + `${attrs.shown ? '|' + attrs.shown : ''}]]` } function atomSays (node, source) { const found = spans(source) if (found.length !== 1 || found[0].source !== source) return false const span = found[0] if (node.type.name === 'embed') { return span.kind === Embed && span.text.slice(3, -2) === node.attrs.ref } if (node.type.name === 'image') { return span.kind === Image && span.target === node.attrs.id && span.text === (node.attrs.alt ?? '') } if (span.kind !== WikiLink) return false const date = node.type.name === 'datelink' return isDate(span.target) === date && span.target === (date ? node.attrs.date : node.attrs.target) && span.anchor === (node.attrs.anchor ?? '') && span.text === (node.attrs.shown ?? '') } // serialiseDetailed is serialise with its working: every block, with // first (first holder of its origin), entry, untouched and text, and for // each written block after the first, the seam written before it. // // options: // - fresh: block indexes written from their nodes whatever the table says; // - joins: block indexes whose seam before them follows Join; // - edges: false leaves out the leading and trailing bytes (a copied slice); // - raw: true skips cleanBody's rule. export function serialiseDetailed (doc, table, options = {}) { const fresh = options.fresh ?? new Set() const joins = options.joins ?? new Set() const blocks = docBlocks(doc) const holders = new Set() for (const block of blocks) { const origin = originOf(block) block.origin = origin block.first = origin != null && !holders.has(origin) if (origin != null) holders.add(origin) block.entry = block.first ? table?.get(origin) : undefined block.untouched = !fresh.has(block.index) && isUntouched(block, block.entry) block.text = block.untouched ? block.entry.source : serialiseBlock(block) } // A fence that is no longer last is closed: an untouched one whose // source runs to the end is written from its node instead (step 5). let last = -1 blocks.forEach((block, index) => { if (block.text !== '') last = index }) for (const block of blocks.slice(0, Math.max(last, 0))) { if (block.kind !== Code) continue if (block.untouched && fenceClosed(block.text)) continue block.untouched = false block.text = serialiseBlock(block, { last: false }) } const emitted = blocks.filter(block => block.text !== '') let out = '' emitted.forEach((block, index) => { if (index === 0) { if (options.edges !== false && block.entry?.leading != null) { out += block.entry.leading } } else { block.seam = seam(emitted[index - 1], block, joins.has(block.index)) out += block.seam } out += block.text }) const end = emitted[emitted.length - 1] if (options.edges !== false && end?.entry?.trailing != null) { out += end.entry.trailing } return { body: options.raw ? normalise(out) : cleanBody(out), blocks, emitted } } // serialise is the document's Mapa Markdown (§6.4). export function serialise (doc, table, options) { return serialiseDetailed(doc, table, options).body } // seam is step 3: the bytes recorded between two blocks the table says // were neighbours, else Join's rule. function seam (before, after, forced) { if (!forced && before.first && after.first) { if (before.entry && before.entry.next === after.origin && before.entry.after != null) return before.entry.after if (after.entry && after.entry.prev === before.origin && after.entry.before != null) return after.entry.before } return joinSeam(before.kind, after.kind) } // joinSeam is markup.Join's: one blank line, or one newline between two // list items. export function joinSeam (before, after) { if (before === Column) return '\n' return before === Item && after === Item ? '\n' : '\n\n' } // shape is what the structure check compares (step 5): kind, a heading's // level, and where an item sits: its list kind, its depth, and whether it // opens a list. listStart counts only blocks that are written. function shapes (emitted) { const seenLists = new Set() return emitted.map(block => { if (block.kind === Heading) { return `${Heading}:${Math.min(Math.max(block.node.attrs.level, 1), 6)}` } if (block.kind !== Item) return block.kind const start = !seenLists.has(block.listPos) seenLists.add(block.listPos) return `${Item}:${block.list}:${block.depth}:${start}` }) } // bodyShapes is the shape of the document a body would reload as. export function bodyShapes (schema, body) { // An empty column's paragraph, which fromBlocks puts there to type in, // writes nothing, so it is no block of the body. const blocks = docBlocks(fromBlocks(schema, parse(body), { trailing: false })) return shapes(blocks.filter(block => !(block.kind === Paragraph && block.column > 0 && block.node.childCount === 0))) } export function docShapes (emitted) { return shapes(emitted) } function firstMismatch (want, got) { const length = Math.min(want.length, got.length) for (let index = 0; index < length; index++) { if (want[index] !== got[index]) return index } return want.length === got.length ? -1 : length } // structureCheck is step 5, before every autosave: parse(serialise(doc)) // must give the document's blocks (empty blocks and the trailing // paragraph, which are written as nothing, left out). Failing that, the // offending blocks' seams follow Join, then those blocks are written from // their nodes, then every block is. ok false means even that failed and // the caller adopts the parse (fidelity.prepareSave). shapes are the // document's blocks as checked: what the body must parse as. export function structureCheck (doc, table) { const schema = doc.type.schema const attempt = options => { const result = serialiseDetailed(doc, table, options) result.shapes = shapes(result.emitted) result.mismatch = firstMismatch(result.shapes, bodyShapes(schema, result.body)) return result } const fresh = new Set() const joins = new Set() let result = attempt({}) for (let round = 0; result.mismatch >= 0 && round < 4; round++) { const near = [-1, 0, 1, 2].map(step => result.emitted[result.mismatch + step]) for (const block of near) { if (!block) continue joins.add(block.index) if (round >= 2) fresh.add(block.index) } result = attempt({ fresh, joins }) } if (result.mismatch >= 0) { const every = new Set(result.blocks.map(block => block.index)) result = attempt({ fresh: every, joins: every }) } return { ok: result.mismatch < 0, body: result.body, shapes: result.shapes, fixed: joins.size > 0 } }