oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fidelity.test.mjs — gates L1, L2 and L3 (spec §7), over every body in
2// Go's golden file (MAPA_GOLDEN points them at another, as make
3// corpus-local does).
4//
5// L3's Go half: the bodies L3 saves, with the blocks the document held,
6// are written to internal/mapa/markup/testdata/editor.json, which
7// markup's TestEditorBodies parses with Go's Parse. This test fails when
8// that file is stale; make editor-golden rewrites it.
9
10import { test } from 'node:test'
11import assert from 'node:assert/strict'
12import { createHash } from 'node:crypto'
13import { readFileSync, writeFileSync } from 'node:fs'
14import { dirname, join } from 'node:path'
15import { fileURLToPath } from 'node:url'
16import { TextSelection } from 'prosemirror-state'
17import { undo, redo, undoDepth } from 'prosemirror-history'
18import { splitBlock, joinBackward } from 'prosemirror-commands'
19import { splitListItem, sinkListItem, liftListItem } from 'prosemirror-schema-list'
20import { corpus, random, schema, editor, localCorpus } from './testkit.mjs'
21import { parse, cleanBody, Rule, Item, Code, isFence } from './markup.mjs'
22import { fromBlocks } from './fromMarkdown.mjs'
23import {
24 docBlocks, serialise, serialiseDetailed, structureCheck, sameNode, bareNode,
25 fenceClosed, joinSeam
26} from './serialize.mjs'
27import { mount, settle, rebuild, prepareSave } from './fidelity.mjs'
28import { copyData, pasteTransaction } from './clipboard.mjs'
29import { linkable, linkSelection, pageLinkSource, readsBack } from './pagelink.mjs'
30import { dateInsertion } from './commands.mjs'
31
32const here = dirname(fileURLToPath(import.meta.url))
33const editorGolden = join(here, '..', 'internal', 'mapa', 'markup', 'testdata', 'editor.json')
34// MAPA_L3_ONLY narrows the gates to bodies whose name starts with it,
35// for working on one case; the editor golden file is then not compared.
36const only = process.env.MAPA_L3_ONLY
37const bodies = corpus().filter(({ name }) => !only || name.startsWith(only))
38
39function report (failed, of) {
40 assert.equal(failed.length, 0,
41 `${failed.length} of ${of} differ:\n${failed.slice(0, 5).join('\n\n')}`)
42}
43
44// each runs check on every body and collects the failures by name.
45function each (check) {
46 const failed = []
47 for (const body of bodies) {
48 try {
49 check(body)
50 } catch (error) {
51 failed.push(`${body.name}: ${error.stack.split('\n').slice(0, 3).join('\n')}`)
52 }
53 }
54 return failed
55}
56
57test('L1: mounting then serialising gives cleanBody(body), byte for byte', t => {
58 report(each(({ body }) => {
59 const { doc, fidelity } = mount(schema, body)
60 assert.equal(serialise(doc, fidelity), cleanBody(body))
61 }), bodies.length)
62 t.diagnostic(`${bodies.length} bodies`)
63})
64
65test('L1: mounting a stored body adds nothing, and saving it writes nothing new', () => {
66 report(each(({ body }) => {
67 const stored = cleanBody(body)
68 const { view, fidelity } = editor(stored)
69 // The rules that run after every edit change nothing on a mounted
70 // document (only edited blocks are reparsed).
71 assert.ok(settle(view.state, fidelity, view.state.doc) === null, 'settle changes nothing')
72 const check = structureCheck(view.state.doc, fidelity)
73 assert.ok(check.ok, 'the structure check passes')
74 assert.equal(check.body, stored)
75 }), bodies.length)
76})
77
78// childBlocks maps each top-level node to the blocks it holds.
79function childBlocks (doc) {
80 const blocks = docBlocks(doc)
81 const children = []
82 doc.forEach((node, offset) => {
83 children.push({
84 node, offset, blocks: blocks.filter(block => block.pos >= offset && block.pos < offset + node.nodeSize)
85 })
86 })
87 // The trailing paragraph mounting adds holds no block of the body.
88 const last = children[children.length - 1]
89 if (last && last.node.content.size === 0 && last.node.type.name === 'paragraph') children.pop()
90 return children
91}
92
93function undoAll (view) {
94 while (undoDepth(view.state) > 0) {
95 if (!view.run(undo)) throw new Error('undo did not apply')
96 }
97}
98
99test('L2: one edited block changes only that block\'s bytes; undo gives the body back', t => {
100 let edits = 0
101 report(each(({ name, body }) => {
102 const stored = cleanBody(body)
103 const parsed = parse(stored)
104 if (parsed.length === 0) return
105 const rng = random(`L2 ${name}`)
106 const { view, fidelity } = editor(stored)
107 const blocks = docBlocks(view.state.doc)
108 .filter(block => block.kind !== Rule && !isFence(block.kind) &&
109 block.index < parsed.length)
110 if (blocks.length === 0) return
111 const block = rng.pick(blocks)
112 const pos = block.pos + 1 + rng.int(block.node.content.size + 1)
113 view.dispatch(view.state.tr.insertText('x', pos))
114 const after = serialise(view.state.doc, fidelity)
115 const { from, to } = parsed[block.index]
116 // An edit that would make text lines read as a column layout
117 // neutralises them, wherever they are (spec D16): not local.
118 const neutralised = after.split('\u200b').length > stored.split('\u200b').length
119 assert.ok(neutralised || after.startsWith(stored.slice(0, from)), 'the bytes before the block are kept')
120 assert.ok(neutralised || after.endsWith(stored.slice(to)), 'the bytes after the block are kept')
121 assert.notEqual(after, stored)
122 edits++
123 undoAll(view)
124 assert.equal(serialise(view.state.doc, fidelity), stored, 'undo gives the body back')
125 }), bodies.length)
126 t.diagnostic(`${edits} single-block edits`)
127})
128
129test('L2: inserting or deleting a block changes bytes only at the new seams, by Join', t => {
130 let inserts = 0
131 let deletes = 0
132 report(each(({ name, body }) => {
133 const stored = cleanBody(body)
134 const parsed = parse(stored)
135 const rng = random(`L2 seams ${name}`)
136 const sourceOf = block => parsed[block.index]
137 {
138 const { view, fidelity } = editor(stored)
139 const children = childBlocks(view.state.doc)
140 const gap = rng.int(children.length + 1)
141 const before = children[gap - 1]?.blocks.at(-1)
142 const next = children[gap]?.blocks[0]
143 // A fence that runs to the end is closed when something follows it:
144 // the one case where an insert rewrites a neighbour (step 5).
145 if (!(before?.kind === Code && !fenceClosed(sourceOf(before).source))) {
146 const at = gap < children.length ? children[gap].offset
147 : (children.length ? children[gap - 1].offset + children[gap - 1].node.nodeSize : 0)
148 view.dispatch(view.state.tr.insert(at,
149 schema.nodes.paragraph.create(null, schema.text('new'))))
150 const want = (before ? stored.slice(0, sourceOf(before).to) + '\n\n' : '') + 'new' +
151 (next ? '\n\n' + stored.slice(sourceOf(next).from) : '')
152 assert.equal(serialise(view.state.doc, fidelity), cleanBody(want), 'insert')
153 inserts++
154 undoAll(view)
155 assert.equal(serialise(view.state.doc, fidelity), stored, 'undo the insert')
156 }
157 }
158 {
159 const { view, fidelity } = editor(stored)
160 const children = childBlocks(view.state.doc)
161 const single = children.map((child, index) => index)
162 .filter(index => children[index].blocks.length === 1 && children[index].blocks[0].kind !== Item)
163 if (single.length === 0) return
164 const index = rng.pick(single)
165 const before = children[index - 1]?.blocks.at(-1)
166 const next = children[index + 1]?.blocks[0]
167 // Two lists brought together nest by indent; an indented item would
168 // move under the list above, so its indent is rewritten (§6.3).
169 if (before?.kind === Item && next?.kind === Item && sourceOf(next).level > 0) return
170 const child = children[index]
171 view.dispatch(view.state.tr.delete(child.offset, child.offset + child.node.nodeSize))
172 const want = before && next
173 ? stored.slice(0, sourceOf(before).to) + joinSeam(before.kind, next.kind) +
174 stored.slice(sourceOf(next).from)
175 : before ? stored.slice(0, sourceOf(before).to)
176 : next ? stored.slice(sourceOf(next).from) : ''
177 assert.equal(serialise(view.state.doc, fidelity), cleanBody(want), 'delete')
178 deletes++
179 undoAll(view)
180 assert.equal(serialise(view.state.doc, fidelity), stored, 'undo the delete')
181 }
182 }), bodies.length)
183 t.diagnostic(`${inserts} inserts, ${deletes} deletes`)
184})
185
186// L3's edits. Each takes the editor and the generator and dispatches at
187// most a few transactions; a command that does not apply does nothing.
188function textblocks (doc, { code = true } = {}) {
189 const out = []
190 doc.descendants((node, pos) => {
191 if (node.isTextblock) {
192 if (code || node.type.name !== 'code_block') out.push({ node, pos })
193 return false
194 }
195 })
196 return out
197}
198
199function somewhere (rng, doc, options) {
200 const blocks = textblocks(doc, options)
201 if (blocks.length === 0) return null
202 const { node, pos } = rng.pick(blocks)
203 return { node, pos, at: pos + 1 + rng.int(node.content.size + 1) }
204}
205
206function caret (view, pos, head = pos) {
207 view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, pos, head)))
208}
209
210const typed = ['a', 'word ', ' ', '*', '**', '`', '- ', '# ', '> ', '1. ', '[[Acme]]',
211 '[x](https://x.y)', ' ^ab', '~~~', '```', '---', 'é', '👋', '[ ] ', '|']
212
213function someRange (rng, doc) {
214 const one = somewhere(rng, doc)
215 const two = somewhere(rng, doc)
216 if (!one || !two) return null
217 return [Math.min(one.at, two.at), Math.max(one.at, two.at)]
218}
219
220const edits = {
221 type (view, rng) {
222 const place = somewhere(rng, view.state.doc)
223 if (!place) return
224 if (rng() < 0.2) {
225 if (place.node.type.name === 'code_block') view.dispatch(view.state.tr.insertText('\n', place.at))
226 else view.dispatch(view.state.tr.insert(place.at, schema.nodes.hard_break.create()))
227 return
228 }
229 view.dispatch(view.state.tr.insertText(rng.pick(typed), place.at))
230 },
231 mark (view, rng) {
232 const place = somewhere(rng, view.state.doc, { code: false })
233 if (!place || place.node.content.size === 0) return
234 const from = place.pos + 1 + rng.int(place.node.content.size)
235 const to = from + 1 + rng.int(place.pos + 1 + place.node.content.size - from)
236 const mark = schema.marks[rng.pick(['em', 'strong', 'code', 'em', 'strong'])].create()
237 view.dispatch(rng() < 0.7 ? view.state.tr.addMark(from, to, mark)
238 : view.state.tr.removeMark(from, to, mark.type))
239 },
240 split (view, rng) {
241 const place = somewhere(rng, view.state.doc)
242 if (!place) return
243 caret(view, place.at)
244 view.run(splitListItem(schema.nodes.list_item)) || view.run(splitBlock)
245 },
246 join (view, rng) {
247 const place = somewhere(rng, view.state.doc)
248 if (!place) return
249 caret(view, place.pos + 1)
250 view.run(joinBackward)
251 },
252 move (view, rng) {
253 const items = docBlocks(view.state.doc).filter(block => block.kind === Item)
254 if (items.length === 0) return
255 const item = rng.pick(items)
256 caret(view, item.pos + 1)
257 view.run(rng() < 0.5 ? sinkListItem(schema.nodes.list_item) : liftListItem(schema.nodes.list_item))
258 },
259 chip (view, rng) {
260 const place = somewhere(rng, view.state.doc, { code: false })
261 if (!place) return
262 const chip = rng.pick([
263 () => schema.nodes.wikilink.create({ target: rng.pick(['Acme', 'Halden Robotics']) }),
264 () => schema.nodes.wikilink.create({ target: 'Acme', anchor: 'b1', shown: 'that' }),
265 () => schema.nodes.datelink.create({ date: '2026-11-12' }),
266 () => schema.nodes.embed.create({ ref: 'fichas:c1' })
267 ])()
268 view.dispatch(view.state.tr.insert(place.at, chip))
269 },
270 // Images (images spec §2.3): insert, move and edit the alt text of an
271 // image atom. unchip removes one; paste carries the corpus's images.
272 image (view, rng) {
273 const place = somewhere(rng, view.state.doc, { code: false })
274 if (!place) return
275 const id = rng.pick(['a1', 'k9', '2kq9xw3m1ab', 'z13'])
276 const alt = rng.pick(['', 'a whiteboard', 'a *b* `c`', 'é'.repeat(20)])
277 view.dispatch(view.state.tr.insert(place.at, schema.nodes.image.create({ id, alt })))
278 },
279 moveImage (view, rng) {
280 const found = images(view.state.doc)
281 if (found.length === 0) return
282 const { node, pos } = rng.pick(found)
283 const tr = view.state.tr.delete(pos, pos + 1)
284 const place = somewhere(rng, tr.doc, { code: false })
285 if (!place) return
286 view.dispatch(tr.insert(place.at, node))
287 },
288 alt (view, rng) {
289 const found = images(view.state.doc)
290 if (found.length === 0) return
291 const { pos } = rng.pick(found)
292 const alt = rng.pick(['', 'changed', 'two words', '**bold** words'])
293 view.dispatch(view.state.tr.setNodeAttribute(pos, 'alt', alt))
294 },
295 unchip (view, rng) {
296 const atoms = []
297 view.state.doc.descendants((node, pos) => { if (node.isAtom && node.isInline) atoms.push(pos) })
298 if (atoms.length === 0) return
299 const pos = rng.pick(atoms)
300 view.dispatch(view.state.tr.delete(pos, pos + 1))
301 },
302 undo (view) { view.run(undo) },
303 redo (view) { view.run(redo) },
304 copyDrag (view, rng) {
305 const children = []
306 view.state.doc.forEach((node, offset) => children.push({ node, offset }))
307 const { node } = rng.pick(children)
308 const target = rng.pick(children)
309 view.dispatch(view.state.tr.insert(rng() < 0.5 ? target.offset : target.offset + target.node.nodeSize, node))
310 },
311 paste (view, rng, fidelity) {
312 const range = someRange(rng, view.state.doc)
313 if (!range) return
314 const { mapa } = copyData(view.state, fidelity, ...range)
315 const into = rng() < 0.7 ? somewhere(rng, view.state.doc) : null
316 if (into) caret(view, into.at)
317 else {
318 const other = someRange(rng, view.state.doc)
319 if (other) caret(view, ...other)
320 }
321 const tr = pasteTransaction(view.state, fidelity, mapa)
322 if (tr) view.dispatch(tr)
323 },
324 cutAndPaste (view, rng, fidelity) {
325 const range = someRange(rng, view.state.doc)
326 if (!range || range[0] === range[1]) return
327 const { mapa } = copyData(view.state, fidelity, ...range)
328 caret(view, ...range)
329 view.dispatch(view.state.tr.deleteSelection())
330 const into = somewhere(rng, view.state.doc)
331 if (into) caret(view, into.at)
332 const tr = pasteTransaction(view.state, fidelity, mapa)
333 if (tr) view.dispatch(tr)
334 },
335 rebuild (view, rng, fidelity) {
336 const depth = undoDepth(view.state)
337 const { body } = prepareSave(view, fidelity)
338 const saved = undoDepth(view.state)
339 rebuild(view, fidelity, body)
340 assert.equal(undoDepth(view.state), saved, 'a rebuild is not in undo history')
341 assert.ok(saved >= depth)
342 },
343 task (view, rng) {
344 const items = docBlocks(view.state.doc).filter(block => block.kind === Item)
345 if (items.length === 0) return
346 const item = rng.pick(items)
347 const on = !item.holder.attrs.task
348 view.dispatch(view.state.tr.setNodeAttribute(item.holderPos, 'task', on)
349 .setNodeAttribute(item.holderPos, 'checked', on ? rng.pick([' ', 'x']) : null))
350 },
351 level (view, rng) {
352 const headings = docBlocks(view.state.doc).filter(block => block.node.type.name === 'heading')
353 if (headings.length === 0) return
354 view.dispatch(view.state.tr.setNodeAttribute(rng.pick(headings).pos, 'level', 1 + rng.int(6)))
355 },
356 remove (view, rng) {
357 const range = someRange(rng, view.state.doc)
358 if (!range) return
359 caret(view, ...range)
360 view.dispatch(view.state.tr.deleteSelection())
361 }
362}
363
364const weights = Object.entries({
365 type: 8, mark: 3, split: 3, join: 3, move: 2, chip: 2, unchip: 1, undo: 3, redo: 1,
366 copyDrag: 1, paste: 2, cutAndPaste: 1, rebuild: 1, task: 1, level: 1, remove: 2,
367 image: 1, moveImage: 1, alt: 1
368}).flatMap(([name, weight]) => Array(weight).fill(name))
369
370function images (doc) {
371 const found = []
372 doc.descendants((node, pos) => { if (node.type.name === 'image') found.push({ node, pos }) })
373 return found
374}
375
376function markerCounts (doc) {
377 const counts = new Map()
378 for (const block of docBlocks(doc)) {
379 const marker = block.holder.attrs.marker
380 if (marker) counts.set(marker, (counts.get(marker) ?? 0) + 1)
381 }
382 return counts
383}
384
385// stable is everything L3 holds after an edit. It returns what was saved.
386function stable (view, fidelity, before, mounted) {
387 const unsettled = settle(view.state, fidelity, before)
388 if (unsettled) {
389 assert.fail(`the reparse is not idempotent: ${JSON.stringify(serialise(view.state.doc, fidelity))} ` +
390 `settles again to ${JSON.stringify(serialise(unsettled.doc, fidelity))} by ` +
391 JSON.stringify(unsettled.steps.map(step => step.toJSON())).slice(0, 600))
392 }
393 const { body, shapes } = prepareSave(view, fidelity)
394 const check = structureCheck(view.state.doc, fidelity)
395 assert.ok(check.ok, 'the saved body reloads as this document')
396 assert.equal(check.body, body)
397 const again = mount(schema, body)
398 assert.equal(serialise(again.doc, again.fidelity), body, 'serialise(parse(serialise)) = serialise')
399 for (const [marker, count] of markerCounts(view.state.doc)) {
400 assert.ok(count <= Math.max(1, mounted.get(marker) ?? 0), `^${marker} held ${count} times`)
401 }
402 for (const block of serialiseDetailed(view.state.doc, fidelity).blocks) {
403 // A fence line is no block on its own: its entry is its layout's.
404 if (!block.untouched || isFence(block.kind)) continue
405 const read = docBlocks(fromBlocks(schema, parse(block.entry.source), { trailing: false }))
406 assert.equal(read.length, 1, 'an entry\'s source is one block')
407 assert.ok(sameNode(read[0].node, block.entry.node), `an entry's node is its source's: ${block.kind} ${JSON.stringify(block.entry.source)} ${read[0].kind}`)
408 assert.ok(sameNode(block.node, block.entry.node) ||
409 sameNode(bareNode(block), block.entry.node), 'an untouched block is its entry\'s node')
410 }
411 return { body, shapes }
412}
413
414const l3Steps = 24
415
416test('L3: seeded edits keep the document and its Markdown saying the same thing', t => {
417 const saved = []
418 let steps = 0
419 report(each(({ name, body }) => {
420 const rng = random(`L3 ${name}`)
421 const { view, fidelity } = editor(cleanBody(body))
422 const mounted = markerCounts(view.state.doc)
423 let last = null
424 for (let step = 0; step < l3Steps; step++) {
425 const edit = rng.pick(weights)
426 const before = view.state.doc
427 try {
428 edits[edit](view, rng, fidelity)
429 last = stable(view, fidelity, before, mounted)
430 } catch (error) {
431 error.message = `step ${step} (${edit}): ${error.message}`
432 throw error
433 }
434 steps++
435 }
436 saved.push({ name, body: last.body, blocks: last.shapes })
437 const before = view.state.doc
438 undoAll(view)
439 stable(view, fidelity, before, mounted)
440 }), bodies.length)
441 t.diagnostic(`${steps} edits over ${bodies.length} bodies`)
442 if (localCorpus || only) return
443 const clean = createHash('sha256')
444 for (const { body } of bodies) clean.update(cleanBody(body) + '\u0000')
445 const encoded = '{"clean":' + JSON.stringify(clean.digest('hex')) + ',"bodies":[\n' +
446 saved.map(entry => JSON.stringify(entry)).join(',\n') + '\n]}\n'
447 if (process.env.MAPA_EDITOR_UPDATE) {
448 writeFileSync(editorGolden, encoded)
449 return
450 }
451 assert.equal(readFileSync(editorGolden, 'utf8') === encoded, true,
452 `${editorGolden} is stale: run make editor-golden and commit it`)
453})
454
455// Link to a page over the corpus (build note 81): in each body, seeded
456// selections of words in one block become a chip showing those words.
457// Everything L3 holds still holds, and per link (review M3) the
458// document says what it said, less the words, plus exactly one chip
459// showing them: no embed, no code span, no other link made or lost.
460// Undo gives the body back byte for byte.
461function chipsOf (doc) {
462 const out = []
463 doc.descendants(node => {
464 if (node.type.name === 'wikilink' || node.type.name === 'datelink') {
465 out.push(`${node.attrs.target ?? node.attrs.date}|${node.attrs.shown}`)
466 }
467 if (node.type.name === 'embed') out.push(`embed ${node.attrs.ref}`)
468 })
469 return out.sort()
470}
471
472test('L3: Link to a page makes exactly one chip, and changes nothing else', t => {
473 let linked = 0
474 const refused = {}
475 report(each(({ name, body }) => {
476 const rng = random(`link ${name}`)
477 const clean = cleanBody(body)
478 const { view, fidelity } = editor(clean)
479 const mounted = markerCounts(view.state.doc)
480 for (let tries = 0; tries < 8; tries++) {
481 const place = somewhere(rng, view.state.doc, { code: false })
482 if (!place || place.node.content.size === 0) continue
483 const from = place.pos + 1 + rng.int(place.node.content.size)
484 const to = from + 1 + rng.int(place.pos + 1 + place.node.content.size - from)
485 caret(view, from, to)
486 const found = linkable(view.state)
487 if (!found || found.refuse) {
488 if (found) refused[found.refuse] = (refused[found.refuse] ?? 0) + 1
489 continue
490 }
491 const target = rng.pick(['Acme', 'Halden Robotics', '2026-11-12', found.words])
492 const shown = target === found.words ? '' : found.words
493 if (pageLinkSource(target, shown) === null) {
494 // Words holding # or | cannot be a title as typed: no row offers it.
495 assert.equal(view.run(linkSelection(target, found.words)), false)
496 continue
497 }
498 const before = view.state.doc
499 const at = before.textBetween(0, found.from, '', '').length
500 const text = before.textContent
501 assert.equal(view.run(linkSelection(target, found.words)), true)
502 const { body: saved } = stable(view, fidelity, before, mounted)
503 const again = mount(schema, saved).doc
504 for (const doc of [view.state.doc, again]) {
505 // A line that came to read as a fence is neutralised (spec D16).
506 const want = text.slice(0, at) + text.slice(at + found.words.length)
507 const zw = value => doc.textContent === want ? value : value.replaceAll('\u200b', '')
508 assert.equal(zw(doc.textContent), zw(want),
509 `the text is the text less the words: ${JSON.stringify(saved)}`)
510 const chip = `${target}|${shown}`
511 assert.deepEqual(chipsOf(doc), [...chipsOf(before), chip].sort(),
512 `exactly one more chip: ${JSON.stringify(saved)}`)
513 }
514 linked++
515 view.run(undo)
516 assert.equal(serialise(view.state.doc, fidelity), clean, 'undo gives the body back')
517 }
518 }), bodies.length)
519 t.diagnostic(`${linked} links over ${bodies.length} bodies; refused: ${JSON.stringify(refused)}`)
520})
521
522// The date picker over the corpus (build note 83, review M1 and M2): in
523// each body, the picked day goes in at seeded carets outside code, as
524// dateInsertion puts it. Each insert is refused, or reads back as
525// exactly one more date chip with the text unchanged (a space before it
526// when it was spaced). No threshold: where either is not so, or the
527// insert is refused, a plain letter must fare the same (typing "x" at
528// the same caret does not read back either), so the chip is never the
529// only thing the place cannot hold. Everything L3 holds still holds, the
530// Markdown holds [[date]], and undo gives the body back byte for byte.
531function textAt (doc, pos) {
532 return doc.textBetween(0, pos, '', '').length
533}
534
535// letterReadsBack is the control: whether typing "x" at pos in body
536// leaves a document whose text, and whose saved Markdown read again,
537// is the body's text with the x in it. Where it does not, the body was
538// already one the Markdown reads differently (an empty "##" heading,
539// an unclosed fence beside another kind), whatever goes in there.
540function letterReadsBack (body, pos) {
541 const { view, fidelity } = editor(body)
542 const text = view.state.doc.textContent
543 const at = textAt(view.state.doc, pos)
544 view.dispatch(view.state.tr.insertText('x', pos))
545 const want = text.slice(0, at) + 'x' + text.slice(at)
546 const again = mount(schema, prepareSave(view, fidelity).body).doc
547 return view.state.doc.textContent === want && again.textContent === want
548}
549
550test('L3: a picked date is one more date chip, or refused where a letter would be too', t => {
551 const tally = { inserted: 0, spaced: 0, refused: 0, unstable: 0 }
552 report(each(({ name, body }) => {
553 const rng = random(`date ${name}`)
554 const clean = cleanBody(body)
555 const { view, fidelity } = editor(clean)
556 const mounted = markerCounts(view.state.doc)
557 for (let tries = 0; tries < 6; tries++) {
558 const place = somewhere(rng, view.state.doc, { code: false })
559 if (!place) continue
560 caret(view, place.at)
561 const date = rng.pick(['2026-11-20', '2025-02-28', '2028-02-29'])
562 const before = view.state.doc
563 const made = dateInsertion(view.state, date)
564 if (made.refuse) {
565 const control = view.state.tr.insertText('x', place.at)
566 assert.equal(readsBack(control.doc.resolve(place.at).parent), false,
567 `refused where a letter reads back: ${JSON.stringify(clean)} at ${place.at}`)
568 tally.refused++
569 continue
570 }
571 const at = textAt(before, place.at)
572 const text = before.textContent
573 const want = text.slice(0, at) + (made.spaced ? ' ' : '') + text.slice(at)
574 view.dispatch(made.tr)
575 const { body: saved } = stable(view, fidelity, before, mounted)
576 const again = mount(schema, saved).doc
577 const chips = JSON.stringify([...chipsOf(before), `${date}|`].sort())
578 const exact = [view.state.doc, again].every(doc =>
579 doc.textContent === want && JSON.stringify(chipsOf(doc)) === chips)
580 if (!exact) {
581 assert.equal(letterReadsBack(clean, place.at), false,
582 `the date reads differently where a letter does not: ${JSON.stringify(saved)}`)
583 tally.unstable++
584 }
585 assert.ok(saved.includes(`[[${date}]]`), `the Markdown holds [[${date}]]: ${JSON.stringify(saved)}`)
586 tally[made.spaced ? 'spaced' : 'inserted']++
587 view.run(undo)
588 assert.equal(serialise(view.state.doc, fidelity), clean, 'undo gives the body back')
589 }
590 }), bodies.length)
591 t.diagnostic(`over ${bodies.length} bodies: ${JSON.stringify(tally)}`)
592 assert.ok(tally.inserted + tally.spaced > 3000, JSON.stringify(tally))
593})
594