oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// serialize.mjs — the editor's document as Mapa Markdown (spec §6.4).
2//
3// A block nobody touched is written back from the source it was read
4// from, byte for byte, and the bytes between two blocks that were
5// neighbours when they were read are kept. Everything else is written
6// from its node, with the syntax its kept attributes record. The side
7// table that holds sources and seams is fidelity.mjs's; this file only
8// reads it, through table.get(origin).
9//
10// A Mapa block is one textblock, or one rule (§6.3). docBlocks lists
11// them in document order, which is the order markup.parse gives them.
12
13import {
14 parse, cleanBody, normalise, goTrimSpace, spans, isDate, isRuleLine,
15 isFenceLine, fenceOf, closesFence,
16 Paragraph, Heading, Item, Code, Quote, Rule, WikiLink, Embed, Image, ImagePrefix,
17 Columns, Column, ColumnEnd, ColumnsEnd, isFence
18} from './markup.mjs'
19import { fromBlocks } from './fromMarkdown.mjs'
20
21const lists = new Set(['bullet_list', 'ordered_list'])
22
23// docBlocks is a document's Mapa blocks, each with:
24// - kind, as markup names it, and node, the textblock (or rule) that
25// holds its origin, at pos;
26// - holder, the node that holds its ^id (the list_item or blockquote
27// around an item's or quote's paragraph), at holderPos;
28// - for an item: depth, list (its list's type), listPos and listStart.
29export function docBlocks (doc) {
30 const out = []
31 doc.forEach((child, offset) => topBlock(child, offset, out))
32 return out
33}
34
35function push (out, block) {
36 block.index = out.length
37 out.push(block)
38}
39
40// originAttr is the attribute that holds a block's origin: a textblock's
41// (or rule's) own origin, or, for a column layout's fence line, the
42// openOrigin or closeOrigin of the layout or column it opens or closes
43// (columns and icons spec §1.7).
44export function originAttr (block) {
45 if (block.kind === Columns || block.kind === Column) return 'openOrigin'
46 if (block.kind === ColumnEnd || block.kind === ColumnsEnd) return 'closeOrigin'
47 return 'origin'
48}
49
50export function originOf (block) {
51 return block.node.attrs[originAttr(block)] ?? null
52}
53
54// layoutBlocks is a layout's blocks: its fences, each column's fences,
55// and each column's own blocks between them, each with its column.
56function layoutBlocks (node, pos, out) {
57 push(out, { kind: Columns, node, pos, holder: node, holderPos: pos, column: 0 })
58 node.forEach((column, offset, index) => {
59 const at = pos + 1 + offset
60 const number = index + 1
61 push(out, { kind: Column, node: column, pos: at, holder: column, holderPos: at, column: number })
62 const from = out.length
63 column.forEach((child, childOffset) => topBlock(child, at + 1 + childOffset, out))
64 for (const inside of out.slice(from)) inside.column = number
65 push(out, { kind: ColumnEnd, node: column, pos: at, holder: column, holderPos: at, column: number })
66 })
67 push(out, { kind: ColumnsEnd, node, pos, holder: node, holderPos: pos, column: 0 })
68}
69
70function topBlock (node, pos, out) {
71 switch (node.type.name) {
72 case 'columns':
73 return layoutBlocks(node, pos, out)
74 case 'paragraph':
75 return push(out, { kind: Paragraph, node, pos, holder: node, holderPos: pos })
76 case 'heading':
77 return push(out, { kind: Heading, node, pos, holder: node, holderPos: pos })
78 case 'code_block':
79 return push(out, { kind: Code, node, pos, holder: node, holderPos: pos })
80 case 'horizontal_rule':
81 return push(out, { kind: Rule, node, pos, holder: node, holderPos: pos })
82 case 'blockquote':
83 if (node.firstChild?.type.name === 'paragraph') {
84 push(out, {
85 kind: Quote, node: node.firstChild, pos: pos + 1, holder: node, holderPos: pos
86 })
87 }
88 return
89 }
90 if (lists.has(node.type.name)) listBlocks(node, pos, 0, out)
91}
92
93function listBlocks (list, pos, depth, out) {
94 list.forEach((item, offset, index) => {
95 const itemPos = pos + 1 + offset
96 item.forEach((child, childOffset, childIndex) => {
97 const childPos = itemPos + 1 + childOffset
98 if (childIndex === 0 && child.type.name === 'paragraph') {
99 push(out, {
100 kind: Item, node: child, pos: childPos, holder: item, holderPos: itemPos,
101 depth, list: list.type.name, listPos: pos, listStart: index === 0
102 })
103 } else if (lists.has(child.type.name)) {
104 listBlocks(child, childPos, depth + 1, out)
105 }
106 })
107 })
108}
109
110// contextKey is what, besides its own node, decides how a block is
111// written: its kind, and an item's list attributes, depth and list kind,
112// or a quote's prefixes and ^id (§6.4 step 1).
113export function contextKey (block) {
114 const attrs = block.holder.attrs
115 if (isFence(block.kind)) return JSON.stringify([block.kind, attrs.fence])
116 switch (block.kind) {
117 case Item:
118 return JSON.stringify([Item, block.depth, block.list, attrs.indent,
119 attrs.bullet, attrs.number, attrs.delim, attrs.task, attrs.checked,
120 attrs.marker])
121 case Quote:
122 return JSON.stringify([Quote, attrs.prefix, attrs.marker])
123 }
124 return block.kind
125}
126
127// The tail: a textblock's trailing hard breaks, and the blank text after
128// them, have no Markdown form outside a quote (a blank line ends a
129// block). Like an empty block, the editor keeps them on screen while you
130// type and writes nothing for them.
131function tailStart (node) {
132 let pos = node.content.size
133 let start = null
134 for (let index = node.childCount - 1; index >= 0; index--) {
135 const child = node.child(index)
136 if (child.type.name === 'hard_break') start = pos - child.nodeSize
137 else if (!(child.isText && goTrimSpace(child.text) === '')) break
138 pos -= child.nodeSize
139 }
140 return start
141}
142
143// bareNode is a block's node without its tail.
144export function bareNode (block) {
145 if (block.kind === Quote || block.kind === Code || block.kind === Rule) {
146 return block.node
147 }
148 const start = tailStart(block.node)
149 if (start === null) return block.node
150 return block.node.copy(block.node.content.cut(0, start))
151}
152
153// isUntouched is §6.4 step 2: the first holder of its origin (decided by
154// the caller), equal to the node its entry recorded, in the same context.
155// A tail added since does not count as a change: it is written as
156// nothing either way. Nor does a heading's source attribute, which
157// records the line it was read from and is never drawn or reparsed.
158export function isUntouched (block, entry) {
159 if (!entry) return false
160 if (isFence(block.kind)) {
161 return entry.node.type === block.node.type && contextKey(block) === entry.context
162 }
163 const node = block.node
164 if (node !== entry.node && !node.eq(entry.node) &&
165 !sameNode(bareNode(block), entry.node)) return false
166 return contextKey(block) === entry.context
167}
168
169// sameNode is eq, except that origins and a heading's source are not
170// compared (the caller has already matched origins, or is assigning one).
171export function sameNode (node, other) {
172 if (node.type !== other.type || !node.content.eq(other.content)) return false
173 for (const name of Object.keys(node.attrs)) {
174 if (name === 'origin') continue
175 if (name === 'source' && node.type.name === 'heading') continue
176 if (JSON.stringify(node.attrs[name]) !== JSON.stringify(other.attrs[name])) {
177 return false
178 }
179 }
180 return true
181}
182
183// serialiseBlock writes one block from its node (§6.4 step 4). last says
184// whether nothing follows it: a fence that is not last must be closed.
185// An empty block is written as nothing ('').
186export function serialiseBlock (block, { last = true } = {}) {
187 const node = block.node
188 switch (block.kind) {
189 case Paragraph: {
190 const text = inline(bareNode(block))
191 return blank(text) ? '' : text + markerTail(block)
192 }
193 case Heading: {
194 const text = inline(bareNode(block))
195 return blank(text) ? '' : headingPrefix(node.attrs) + text + markerTail(block)
196 }
197 case Item:
198 return itemText(block)
199 case Quote:
200 return quoteText(block)
201 case Code:
202 return codeText(node, last)
203 case Rule:
204 return isRuleLine(node.attrs.source ?? '') ? node.attrs.source : '---'
205 case Columns:
206 case Column:
207 case ColumnEnd:
208 case ColumnsEnd:
209 return fenceText(block)
210 }
211 return ''
212}
213
214// fenceText writes a layout's fence line from its node: a layout's own
215// colons, when they are four or more, else four; a column's always three,
216// fewer than any layout's, so a column written from its node always
217// closes inside its layout (an untouched one re-emits its source).
218function fenceText (block) {
219 const outer = block.kind === Columns || block.kind === ColumnsEnd
220 const own = Number(block.node.attrs.fence)
221 const colons = outer ? (Number.isInteger(own) && own >= 4 ? own : 4) : 3
222 const word = block.kind === Columns ? ' columns' : block.kind === Column ? ' column' : ''
223 return ':'.repeat(colons) + word
224}
225
226function blank (text) { return goTrimSpace(text) === '' }
227
228function markerTail (block) {
229 const marker = block.holder.attrs.marker
230 return marker && /^[A-Za-z0-9-]{1,40}$/u.test(marker) ? ` ^${marker}` : ''
231}
232
233function headingPrefix (attrs) {
234 const level = Math.min(Math.max(attrs.level ?? 1, 1), 6)
235 const kept = /^(#{1,6})([ \t]+)/u.exec(attrs.source ?? '')
236 if (kept && kept[1].length === level) return kept[0]
237 return '#'.repeat(level) + ' '
238}
239
240function itemText (block) {
241 const attrs = block.holder.attrs
242 const text = inline(bareNode(block))
243 if (blank(text)) return ''
244 const indent = /^[ \t]*$/u.test(attrs.indent ?? '') ? attrs.indent ?? '' : ''
245 let mark
246 if (block.list === 'ordered_list') {
247 const number = /^[0-9]{1,9}$/u.test(attrs.number ?? '') ? attrs.number : '1'
248 mark = number + (attrs.delim === ')' ? ')' : '.')
249 } else {
250 mark = ['-', '*', '+'].includes(attrs.bullet) ? attrs.bullet : '-'
251 }
252 const box = attrs.task
253 ? `[${[' ', 'x', 'X'].includes(attrs.checked) ? attrs.checked : ' '}] `
254 : ''
255 return `${indent}${mark} ${box}${text}${markerTail(block)}`
256}
257
258// quoteText puts each line's own prefix back. A quote keeps its tail: a
259// line of only ">" is a line of the quote.
260function quoteText (block) {
261 const text = inline(block.node)
262 if (text === '') return ''
263 const prefixes = Array.isArray(block.holder.attrs.prefix)
264 ? block.holder.attrs.prefix
265 : []
266 return (text + markerTail(block)).split('\n').map((line, index) => {
267 let prefix = prefixes[index] ?? prefixes[0] ?? '> '
268 if (!/^ *> ?$/u.test(prefix)) prefix = '> '
269 // quoteText drops one space after the ">": a line that starts with
270 // a space needs that space written.
271 if (!prefix.endsWith(' ') && line.startsWith(' ')) prefix += ' '
272 return prefix + line
273 }).join('\n')
274}
275
276function codeText (node, last) {
277 const attrs = node.attrs
278 const open = /^ {0,3}(?:`{3,}|~{3,})$/u.test(attrs.fence ?? '') ? attrs.fence : '```'
279 let out = open + String(attrs.info ?? '').split('\n')[0]
280 if (node.textContent !== '') out += '\n' + node.textContent
281 if (attrs.close != null && isFenceLine(attrs.close)) out += '\n' + attrs.close
282 if (!last && !fenceClosed(out)) out += '\n' + open.trimStart()
283 return out
284}
285
286// fenceClosed is whether a fence's source ends with its closing line.
287export function fenceClosed (source) {
288 const lines = source.split('\n')
289 return lines.length > 1 && closesFence(lines[lines.length - 1], fenceOf(lines[0]))
290}
291
292// inline writes a textblock's content. Marks follow §6.3: a mark never
293// spans code, a link or an atom, so each run of plain text between them
294// takes its emphasis on its own; em goes outside strong; whitespace at a
295// mark's edge goes outside its delimiters.
296export function inline (node) {
297 const pieces = []
298 node.forEach(child => {
299 const has = name => child.marks.some(mark => mark.type.name === name)
300 if (child.isText) {
301 const link = child.marks.find(mark => mark.type.name === 'link')
302 const last = pieces[pieces.length - 1]
303 if (has('code')) {
304 if (last?.kind === 'code') last.text += child.text
305 else pieces.push({ kind: 'code', text: child.text })
306 } else if (link) {
307 if (last?.kind === 'link' && last.mark.eq(link)) last.text += child.text
308 else pieces.push({ kind: 'link', text: child.text, mark: link })
309 } else {
310 pieces.push({ kind: 'text', text: child.text, em: has('em'), strong: has('strong') })
311 }
312 } else if (child.type.name === 'hard_break') {
313 const indent = /^[ \t]*/u.exec(child.attrs.indent ?? '')[0]
314 pieces.push({ kind: 'text', text: '\n' + indent, em: has('em'), strong: has('strong') })
315 } else {
316 pieces.push({ kind: 'atom', text: atomSource(child) })
317 }
318 })
319 let out = ''
320 for (let index = 0; index < pieces.length;) {
321 const piece = pieces[index]
322 if (piece.kind === 'text') {
323 let end = index
324 while (end < pieces.length && pieces[end].kind === 'text') end++
325 out += emphasis(pieces.slice(index, end))
326 index = end
327 continue
328 }
329 if (piece.kind === 'code') out += '`' + piece.text + '`'
330 else if (piece.kind === 'link') out += linkText(piece)
331 else out += piece.text
332 index++
333 }
334 return normalise(out)
335}
336
337function linkText ({ text, mark }) {
338 if (mark.attrs.bare && text === mark.attrs.href) return text
339 return `[${text}](${mark.attrs.href})`
340}
341
342function emphasis (run) {
343 return groups(run, 'em', part => strongs(part), '*')
344}
345
346function strongs (run) {
347 return groups(run, 'strong', part => part.map(piece => piece.text).join(''), '**')
348}
349
350// groups wraps each stretch of run that has the mark in delim.
351function groups (run, mark, inner, delim) {
352 let out = ''
353 for (let index = 0; index < run.length;) {
354 let end = index
355 while (end < run.length && run[end][mark] === run[index][mark]) end++
356 const text = inner(run.slice(index, end))
357 out += run[index][mark] ? wrap(text, delim) : text
358 index = end
359 }
360 return out
361}
362
363// wrap puts text in delim with its edge whitespace (Go's ASCII \s)
364// outside, because a delimiter needs a non-space beside it.
365function wrap (text, delim) {
366 const parts = /^([\t\n\f\r ]*)([^]*?)([\t\n\f\r ]*)$/u.exec(text)
367 if (parts[2] === '') return text
368 return parts[1] + delim + parts[2] + delim + parts[3]
369}
370
371// atomSource is an atom's Markdown: its source while that still says
372// exactly what the atom holds, otherwise written from its attributes.
373export function atomSource (node) {
374 const attrs = node.attrs
375 if (attrs.source != null && atomSays(node, attrs.source)) return attrs.source
376 if (node.type.name === 'embed') return `![[${attrs.ref}]]`
377 if (node.type.name === 'image') return `![${attrs.alt ?? ''}](${ImagePrefix}${attrs.id})`
378 const target = node.type.name === 'datelink' ? attrs.date : attrs.target
379 return `[[${target}${attrs.anchor ? '#^' + attrs.anchor : ''}` +
380 `${attrs.shown ? '|' + attrs.shown : ''}]]`
381}
382
383function atomSays (node, source) {
384 const found = spans(source)
385 if (found.length !== 1 || found[0].source !== source) return false
386 const span = found[0]
387 if (node.type.name === 'embed') {
388 return span.kind === Embed && span.text.slice(3, -2) === node.attrs.ref
389 }
390 if (node.type.name === 'image') {
391 return span.kind === Image && span.target === node.attrs.id &&
392 span.text === (node.attrs.alt ?? '')
393 }
394 if (span.kind !== WikiLink) return false
395 const date = node.type.name === 'datelink'
396 return isDate(span.target) === date &&
397 span.target === (date ? node.attrs.date : node.attrs.target) &&
398 span.anchor === (node.attrs.anchor ?? '') &&
399 span.text === (node.attrs.shown ?? '')
400}
401
402// serialiseDetailed is serialise with its working: every block, with
403// first (first holder of its origin), entry, untouched and text, and for
404// each written block after the first, the seam written before it.
405//
406// options:
407// - fresh: block indexes written from their nodes whatever the table says;
408// - joins: block indexes whose seam before them follows Join;
409// - edges: false leaves out the leading and trailing bytes (a copied slice);
410// - raw: true skips cleanBody's rule.
411export function serialiseDetailed (doc, table, options = {}) {
412 const fresh = options.fresh ?? new Set()
413 const joins = options.joins ?? new Set()
414 const blocks = docBlocks(doc)
415 const holders = new Set()
416 for (const block of blocks) {
417 const origin = originOf(block)
418 block.origin = origin
419 block.first = origin != null && !holders.has(origin)
420 if (origin != null) holders.add(origin)
421 block.entry = block.first ? table?.get(origin) : undefined
422 block.untouched = !fresh.has(block.index) && isUntouched(block, block.entry)
423 block.text = block.untouched ? block.entry.source : serialiseBlock(block)
424 }
425 // A fence that is no longer last is closed: an untouched one whose
426 // source runs to the end is written from its node instead (step 5).
427 let last = -1
428 blocks.forEach((block, index) => { if (block.text !== '') last = index })
429 for (const block of blocks.slice(0, Math.max(last, 0))) {
430 if (block.kind !== Code) continue
431 if (block.untouched && fenceClosed(block.text)) continue
432 block.untouched = false
433 block.text = serialiseBlock(block, { last: false })
434 }
435 const emitted = blocks.filter(block => block.text !== '')
436 let out = ''
437 emitted.forEach((block, index) => {
438 if (index === 0) {
439 if (options.edges !== false && block.entry?.leading != null) {
440 out += block.entry.leading
441 }
442 } else {
443 block.seam = seam(emitted[index - 1], block, joins.has(block.index))
444 out += block.seam
445 }
446 out += block.text
447 })
448 const end = emitted[emitted.length - 1]
449 if (options.edges !== false && end?.entry?.trailing != null) {
450 out += end.entry.trailing
451 }
452 return { body: options.raw ? normalise(out) : cleanBody(out), blocks, emitted }
453}
454
455// serialise is the document's Mapa Markdown (§6.4).
456export function serialise (doc, table, options) {
457 return serialiseDetailed(doc, table, options).body
458}
459
460// seam is step 3: the bytes recorded between two blocks the table says
461// were neighbours, else Join's rule.
462function seam (before, after, forced) {
463 if (!forced && before.first && after.first) {
464 if (before.entry && before.entry.next === after.origin &&
465 before.entry.after != null) return before.entry.after
466 if (after.entry && after.entry.prev === before.origin &&
467 after.entry.before != null) return after.entry.before
468 }
469 return joinSeam(before.kind, after.kind)
470}
471
472// joinSeam is markup.Join's: one blank line, or one newline between two
473// list items.
474export function joinSeam (before, after) {
475 if (before === Column) return '\n'
476 return before === Item && after === Item ? '\n' : '\n\n'
477}
478
479// shape is what the structure check compares (step 5): kind, a heading's
480// level, and where an item sits: its list kind, its depth, and whether it
481// opens a list. listStart counts only blocks that are written.
482function shapes (emitted) {
483 const seenLists = new Set()
484 return emitted.map(block => {
485 if (block.kind === Heading) {
486 return `${Heading}:${Math.min(Math.max(block.node.attrs.level, 1), 6)}`
487 }
488 if (block.kind !== Item) return block.kind
489 const start = !seenLists.has(block.listPos)
490 seenLists.add(block.listPos)
491 return `${Item}:${block.list}:${block.depth}:${start}`
492 })
493}
494
495// bodyShapes is the shape of the document a body would reload as.
496export function bodyShapes (schema, body) {
497 // An empty column's paragraph, which fromBlocks puts there to type in,
498 // writes nothing, so it is no block of the body.
499 const blocks = docBlocks(fromBlocks(schema, parse(body), { trailing: false }))
500 return shapes(blocks.filter(block => !(block.kind === Paragraph &&
501 block.column > 0 && block.node.childCount === 0)))
502}
503
504export function docShapes (emitted) { return shapes(emitted) }
505
506function firstMismatch (want, got) {
507 const length = Math.min(want.length, got.length)
508 for (let index = 0; index < length; index++) {
509 if (want[index] !== got[index]) return index
510 }
511 return want.length === got.length ? -1 : length
512}
513
514// structureCheck is step 5, before every autosave: parse(serialise(doc))
515// must give the document's blocks (empty blocks and the trailing
516// paragraph, which are written as nothing, left out). Failing that, the
517// offending blocks' seams follow Join, then those blocks are written from
518// their nodes, then every block is. ok false means even that failed and
519// the caller adopts the parse (fidelity.prepareSave). shapes are the
520// document's blocks as checked: what the body must parse as.
521export function structureCheck (doc, table) {
522 const schema = doc.type.schema
523 const attempt = options => {
524 const result = serialiseDetailed(doc, table, options)
525 result.shapes = shapes(result.emitted)
526 result.mismatch = firstMismatch(result.shapes, bodyShapes(schema, result.body))
527 return result
528 }
529 const fresh = new Set()
530 const joins = new Set()
531 let result = attempt({})
532 for (let round = 0; result.mismatch >= 0 && round < 4; round++) {
533 const near = [-1, 0, 1, 2].map(step => result.emitted[result.mismatch + step])
534 for (const block of near) {
535 if (!block) continue
536 joins.add(block.index)
537 if (round >= 2) fresh.add(block.index)
538 }
539 result = attempt({ fresh, joins })
540 }
541 if (result.mismatch >= 0) {
542 const every = new Set(result.blocks.map(block => block.index))
543 result = attempt({ fresh: every, joins: every })
544 }
545 return {
546 ok: result.mismatch < 0, body: result.body, shapes: result.shapes, fixed: joins.size > 0
547 }
548}
549