oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// serialize.test.mjs — the serialiser's and the fidelity rules' cases,
2// one at a time (spec §6.3, §6.4, §6.6). The corpus-wide gates are in
3// fidelity.test.mjs.
4
5import { test } from 'node:test'
6import assert from 'node:assert/strict'
7import { TextSelection } from 'prosemirror-state'
8import { undo, undoDepth } from 'prosemirror-history'
9import { liftListItem } from 'prosemirror-schema-list'
10import { schema, editor } from './testkit.mjs'
11import { serialise, structureCheck, docBlocks } from './serialize.mjs'
12import { fromMarkdown } from './fromMarkdown.mjs'
13import { mount, settle, rebuild, applyBody, prepareSave } from './fidelity.mjs'
14import { copyData, pasteTransaction, textSlice } from './clipboard.mjs'
15import { EditorState } from 'prosemirror-state'
16
17const text = (words, ...marks) =>
18 schema.text(words, marks.map(name => schema.marks[name].create()))
19const paragraph = (...content) =>
20 schema.nodes.doc.create(null, [schema.nodes.paragraph.create(null, content)])
21const write = doc => serialise(doc, null)
22
23// position of the end of the first textblock whose text is words.
24function at (doc, words, offset = words.length) {
25 let found = null
26 doc.descendants((node, pos) => {
27 if (found === null && node.isTextblock && node.textContent === words) found = pos + 1 + offset
28 })
29 assert.notEqual(found, null, `no block reads ${words}`)
30 return found
31}
32
33test('marks: em outside strong, bold reopened around italics, edges outside', () => {
34 const cases = [
35 [paragraph(text('a ', 'strong'), text('b', 'em', 'strong'), text(' c', 'strong')),
36 '**a** ***b*** **c**'],
37 [paragraph(text('a ', 'em'), text('b', 'em', 'strong'), text(' c', 'em')), '*a **b** c*'],
38 [paragraph(text('x', 'em', 'strong')), '***x***'],
39 [paragraph(text('x'), text(' a ', 'em'), text('y')), 'x *a* y'],
40 [paragraph(text('one '), text('two three', 'strong'), text('.')), 'one **two three**.']
41 ]
42 for (const [doc, want] of cases) {
43 assert.equal(write(doc), want)
44 // Read back, the marks are the same, give or take a space's.
45 assert.equal(write(fromMarkdown(schema, want)), want, `${want} reads back`)
46 assert.equal(fromMarkdown(schema, want).textContent, doc.textContent)
47 }
48})
49
50test('marks close before code, links and atoms, and reopen after', () => {
51 const link = schema.marks.link.create({ href: 'https://x.y' })
52 const chip = schema.nodes.wikilink.create({ target: 'Acme' })
53 assert.equal(write(paragraph(text('a ', 'em'), text('c', 'code'), text(' b', 'em'))),
54 '*a* `c` *b*')
55 assert.equal(write(paragraph(text('a ', 'em'), schema.text('l', [link]), text(' b', 'em'))),
56 '*a* [l](https://x.y) *b*')
57 assert.equal(write(paragraph(text('a ', 'em'), chip, text(' b', 'em'))), '*a* [[Acme]] *b*')
58})
59
60test('untouched blocks and atoms re-emit their source; edited atoms are written from attributes', () => {
61 const body = '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide\n\n##\tTabbed ^h1'
62 const { view, fidelity } = editor(body)
63 assert.equal(serialise(view.state.doc, fidelity), body)
64 view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'wide')))
65 assert.equal(serialise(view.state.doc, fidelity),
66 '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed ^h1')
67 view.dispatch(view.state.tr.insertText('?', at(view.state.doc, 'Tabbed')))
68 assert.equal(serialise(view.state.doc, fidelity),
69 '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed? ^h1')
70})
71
72test('empty blocks are written as nothing', () => {
73 const { view, fidelity } = editor('# Title\n\n- a\n\npara\n\n## b')
74 for (const words of ['a', 'para', 'b']) {
75 const end = at(view.state.doc, words)
76 view.dispatch(view.state.tr.delete(end - words.length, end))
77 }
78 assert.equal(serialise(view.state.doc, fidelity), '# Title')
79 assert.deepEqual(view.state.doc.content.content.map(node => node.content.size === 0),
80 [false, false, true, true, true], 'the empty blocks stay on screen')
81})
82
83test('an unclosed fence that is no longer last gets its closing fence', () => {
84 const { view, fidelity } = editor('```js\nlet a = 1')
85 const end = view.state.doc.content.size
86 view.dispatch(view.state.tr.insertText('after', end - 1))
87 assert.equal(serialise(view.state.doc, fidelity), '```js\nlet a = 1\n```\n\nafter')
88 assert.equal(structureCheck(view.state.doc, fidelity).ok, true)
89})
90
91test('the structure check puts Join\'s seam where a kept one would merge two blocks', () => {
92 const { view, fidelity } = editor('- a\n- b')
93 view.dispatch(view.state.tr.setSelection(
94 TextSelection.create(view.state.doc, at(view.state.doc, 'b'))))
95 view.run(liftListItem(schema.nodes.list_item))
96 assert.equal(view.state.doc.child(1).type.name, 'paragraph')
97 const check = structureCheck(view.state.doc, fidelity)
98 assert.equal(check.ok, true)
99 assert.equal(check.body, '- a\n\nb')
100})
101
102test('prepareSave adopts the parse when no seam or rewrite can save the document', () => {
103 // No settle plugin: a paragraph that says "- a" is left as it is.
104 const { doc, fidelity } = mount(schema, 'x')
105 const view = {
106 state: EditorState.create({ doc }),
107 dispatch (tr) { this.state = this.state.apply(tr) }
108 }
109 view.dispatch(view.state.tr.insertText('- a', 1, 2))
110 assert.equal(structureCheck(view.state.doc, fidelity).ok, false)
111 const { body, adopted } = prepareSave(view, fidelity)
112 assert.equal(adopted, true)
113 assert.equal(body, '- a')
114 assert.equal(view.state.doc.firstChild.type.name, 'bullet_list')
115 assert.equal(serialise(view.state.doc, fidelity), body)
116})
117
118test('reparse: typed emphasis becomes a mark, "- " after a break becomes an item', () => {
119 const { view, fidelity } = editor('hello')
120 view.dispatch(view.state.tr.insertText(' *word*', at(view.state.doc, 'hello')))
121 const marks = []
122 view.state.doc.firstChild.forEach(node => marks.push([node.text, node.marks.map(m => m.type.name)]))
123 assert.deepEqual(marks, [['hello ', []], ['word', ['em']]])
124 view.dispatch(view.state.tr.insert(view.state.doc.firstChild.nodeSize - 1,
125 schema.nodes.hard_break.create()))
126 view.dispatch(view.state.tr.insertText('- item', view.state.doc.firstChild.nodeSize - 1))
127 assert.deepEqual(view.state.doc.content.content.map(node => node.type.name),
128 ['paragraph', 'bullet_list', 'paragraph'])
129 // The line typed is kept as typed: a list right under a paragraph.
130 assert.equal(serialise(view.state.doc, fidelity), 'hello *word*\n- item')
131 assert.ok(settle(view.state, fidelity) === null, 'reparse is idempotent')
132})
133
134test('a trailing hard break stays on screen and is written as nothing', () => {
135 const { view, fidelity } = editor('- item\n\nnext')
136 view.dispatch(view.state.tr.insert(at(view.state.doc, 'item'), schema.nodes.hard_break.create()))
137 let breaks = 0
138 view.state.doc.descendants(node => { if (node.type.name === 'hard_break') breaks++ })
139 assert.equal(breaks, 1)
140 assert.equal(serialise(view.state.doc, fidelity), '- item\n\nnext', 'still untouched')
141})
142
143test('the reparse waits while an IME is composing', () => {
144 let composing = true
145 const { view } = editor('hello', { composing: () => composing })
146 view.dispatch(view.state.tr.insertText(' *x*', at(view.state.doc, 'hello')))
147 assert.equal(view.state.doc.firstChild.textContent, 'hello *x*')
148 composing = false
149 view.dispatch(view.state.tr.setMeta('composed', true))
150 assert.equal(view.state.doc.firstChild.textContent, 'hello x')
151})
152
153test('copied blocks paste with their bytes and seams; a cut and paste gives the body back', () => {
154 const body = 'x\n\na ^m1\n\n\n\n- b\n- c\n\n# d'
155 const { view, fidelity } = editor(body)
156 const from = at(view.state.doc, 'a', 0)
157 const to = at(view.state.doc, 'c')
158 const { text, mapa } = copyData(view.state, fidelity, from, to)
159 assert.equal(text, 'a ^m1\n\n\n\n- b\n- c')
160 // Paste into the empty paragraph after the heading: the marker is
161 // already in the document, so the copy loses it.
162 const end = view.state.doc.content.size - 1
163 view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, end)))
164 view.dispatch(pasteTransaction(view.state, fidelity, mapa))
165 assert.equal(serialise(view.state.doc, fidelity), body + '\n\na\n\n\n\n- b\n- c')
166 // Cut the originals and paste them back: the same bytes, marker and all.
167 const again = editor(body)
168 const cutFrom = at(again.view.state.doc, 'a', 0)
169 const cutTo = at(again.view.state.doc, 'c')
170 const cut = copyData(again.view.state, again.fidelity, cutFrom, cutTo)
171 again.view.dispatch(again.view.state.tr.setSelection(
172 TextSelection.create(again.view.state.doc, cutFrom, cutTo)).deleteSelection())
173 assert.equal(serialise(again.view.state.doc, again.fidelity), 'x\n\n# d')
174 again.view.dispatch(pasteTransaction(again.view.state, again.fidelity, cut.mapa))
175 assert.equal(serialise(again.view.state.doc, again.fidelity), body)
176})
177
178test('a forged x-mapa slice is refused, and text from outside is read as Markdown', () => {
179 const { view, fidelity } = editor('a')
180 for (const forged of ['{', '{"v":1,"sources":["a\\n\\nb"],"seams":[]}',
181 '{"v":1,"sources":["a","b"],"seams":["\\nx\\n"]}', '{"v":2,"sources":["a"],"seams":[]}']) {
182 assert.equal(pasteTransaction(view.state, fidelity, forged), null, forged)
183 }
184 const slice = textSlice(schema, '- one\n- [two](javascript:alert(1))')
185 let links = 0
186 slice.content.descendants(node => { if (node.marks.some(m => m.type.name === 'link')) links++ })
187 assert.equal(links, 0, 'an unsafe address is not a link')
188})
189
190test('rebuild changes origins only, outside undo history', () => {
191 const { view, fidelity } = editor('a\n\nb')
192 view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'b')))
193 const depth = undoDepth(view.state)
194 const body = serialise(view.state.doc, fidelity)
195 const before = view.state.doc
196 assert.equal(rebuild(view, fidelity, body).ok, true)
197 assert.equal(undoDepth(view.state), depth)
198 assert.ok(view.state.doc.content.size === before.content.size)
199 view.run(undo)
200 assert.equal(serialise(view.state.doc, fidelity), 'a\n\nb', 'undo undoes the edit, not the rebuild')
201})
202
203test('applyBody takes a teammate\'s block, keeps the caret, and ends untouched', () => {
204 const { view, fidelity } = editor('one\n\ntwo\n\nthree')
205 view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'three')))
206 view.dispatch(view.state.tr.setSelection(
207 TextSelection.create(view.state.doc, at(view.state.doc, 'three!'))))
208 const caret = view.state.selection.head
209 const merged = 'one\n\n\ntwo, said Bo\n\nthree!'
210 assert.equal(applyBody(view, fidelity, merged).ok, true)
211 assert.equal(serialise(view.state.doc, fidelity), merged)
212 assert.equal(view.state.selection.head, caret + ', said Bo'.length)
213 view.run(undo)
214 assert.equal(serialise(view.state.doc, fidelity), 'one\n\ntwo\n\nthree!')
215})
216
217// "Untouched" includes the block's context (§6.4 step 2): a block whose
218// own node is unchanged but whose item or quote attributes changed is
219// written from the document, not re-emitted. Without the context in the
220// rule a toggled task box saved as it was (review: only make browser's
221// task-box click caught that).
222test('a block whose context changed is written again: a task toggled, a bullet, a quote', () => {
223 const holder = (doc, name) => {
224 let found = null
225 doc.descendants((node, pos) => {
226 if (found === null && node.type.name === name) found = { node, pos }
227 })
228 return found
229 }
230 const cases = [
231 ['- [ ] Send Tom the summary\n- [x] Book the room', 'list_item', { checked: 'x' },
232 '- [x] Send Tom the summary\n- [x] Book the room'],
233 ['- one\n- two', 'list_item', { bullet: '*' }, '* one\n- two'],
234 ['> quoted\n> twice', 'blockquote', { prefix: ['>', '>'] }, '>quoted\n>twice']
235 ]
236 for (const [body, name, change, want] of cases) {
237 const { view, fidelity } = editor(body)
238 const { node, pos } = holder(view.state.doc, name)
239 view.dispatch(view.state.tr.setNodeMarkup(pos, null, { ...node.attrs, ...change }))
240 assert.equal(serialise(view.state.doc, fidelity), want, body)
241 }
242})
243
244// The marker rule keeps an ^id on the block that held it before the
245// edit: a duplicate typed above it is the one taken away (review L; it
246// once took the id from the block links already name).
247test('a duplicate ^id typed above its holder never takes the id from it', () => {
248 const { view, fidelity } = editor('Alpha\n\nBeta ^abc')
249 view.dispatch(view.state.tr.insertText(' ^abc', view.state.doc.firstChild.nodeSize - 1))
250 assert.equal(serialise(view.state.doc, fidelity), 'Alpha\n\nBeta ^abc')
251})
252
253// A copy-dragged block is the very node it copied, a later holder of
254// its origin, written from its node: it is reparsed, so the document
255// says what its Markdown says (review L; it was never checked).
256test('a copy-dragged block is reparsed, and says what its Markdown says', () => {
257 const { view, fidelity } = editor('A.\n\n/d</*su*m**mary*****eta*****ils**')
258 const copied = view.state.doc.child(1)
259 view.dispatch(view.state.tr.insert(view.state.doc.content.size - view.state.doc.lastChild.nodeSize, copied))
260 const written = serialise(view.state.doc, fidelity)
261 const inline = doc => docBlocks(doc).filter(block => block.node.content.size > 0)
262 .map(block => JSON.stringify(block.node.content.toJSON()))
263 assert.deepEqual(inline(view.state.doc), inline(editor(written).view.state.doc))
264})
265
266// Undo can throw inside prosemirror-transform after many edits (an
267// attribute step mapped onto a text node; 4 in 20,000 fuzzed bodies).
268// The editor's undo and redo are guarded: the step is refused, never
269// thrown out of a key or a menu (review L).
270test('a history command that throws is refused, never thrown', async () => {
271 const { guarded, safeUndo } = await import('./commands.mjs')
272 const { view } = editor('One.')
273 const throwing = guarded(() => { throw new RangeError('Position 17 out of range') })
274 assert.equal(throwing(view.state, tr => view.dispatch(tr)), false)
275 assert.equal(safeUndo(view.state, tr => view.dispatch(tr)), false, 'nothing to undo')
276})
277
278// Images (images spec §2.3, L1 and L2): an untouched image re-emits its
279// source; editing its alt text changes only that span.
280test('an image re-emits its source, and an edited alt changes only its span', () => {
281 const body = 'Before ![a whiteboard](/i/2kq9xw3m1ab) after\n\n![](/i/z13) ^lone\n\nnext'
282 const { view, fidelity } = editor(body)
283 assert.equal(serialise(view.state.doc, fidelity), body)
284 let pos = null
285 view.state.doc.descendants((node, at) => {
286 if (pos === null && node.type.name === 'image') pos = at
287 })
288 view.dispatch(view.state.tr.setNodeAttribute(pos, 'alt', 'the pilot review'))
289 assert.equal(serialise(view.state.doc, fidelity),
290 'Before ![the pilot review](/i/2kq9xw3m1ab) after\n\n![](/i/z13) ^lone\n\nnext')
291})
292
293// Fable L3 on 49d8df3: a paste from another page whose copy is refused
294// pastes nothing and says why, rather than addresses that would not
295// draw. A copy that works pastes the copies' addresses.
296test('a paste whose image copy is refused says why and pastes nothing', async () => {
297 const { clipboardPlugin } = await import('./clipboard.mjs')
298 const slice = JSON.stringify({ v: 1, sources: ['![a](/i/far1)'], seams: [], page: 'other' })
299 const paste = { preventDefault () {}, clipboardData: { getData: type => type === 'application/x-mapa' ? slice : '' } }
300 for (const [status, json, want] of [
301 [507, { refused: 'Your image allowance of 1 GB is full. Remove an image before uploading again.' }, 'Here.'],
302 [200, { far1: { id: 'near2', width: 1, height: 1 } }, 'Here.![a](/i/near2)']
303 ]) {
304 const { view, fidelity } = editor('Here.')
305 view.dispatch(view.state.tr.setSelection(TextSelection.atEnd(view.state.doc)))
306 let said = null
307 const plugin = clipboardPlugin(fidelity, {
308 page: () => 'this', copy: async () => ({ status, json }), refused: why => { said = why }
309 })
310 assert.equal(plugin.props.handlePaste(view, paste), true)
311 await new Promise(resolve => setTimeout(resolve, 5))
312 assert.equal(serialise(view.state.doc, fidelity), want)
313 if (status !== 200) assert.equal(said, 'Your image allowance of 1 GB is full. Remove an image before uploading again.')
314 }
315})
316