// serialize.test.mjs — the serialiser's and the fidelity rules' cases, // one at a time (spec §6.3, §6.4, §6.6). The corpus-wide gates are in // fidelity.test.mjs. import { test } from 'node:test' import assert from 'node:assert/strict' import { TextSelection } from 'prosemirror-state' import { undo, undoDepth } from 'prosemirror-history' import { liftListItem } from 'prosemirror-schema-list' import { schema, editor } from './testkit.mjs' import { serialise, structureCheck, docBlocks } from './serialize.mjs' import { fromMarkdown } from './fromMarkdown.mjs' import { mount, settle, rebuild, applyBody, prepareSave } from './fidelity.mjs' import { copyData, pasteTransaction, textSlice } from './clipboard.mjs' import { EditorState } from 'prosemirror-state' const text = (words, ...marks) => schema.text(words, marks.map(name => schema.marks[name].create())) const paragraph = (...content) => schema.nodes.doc.create(null, [schema.nodes.paragraph.create(null, content)]) const write = doc => serialise(doc, null) // position of the end of the first textblock whose text is words. function at (doc, words, offset = words.length) { let found = null doc.descendants((node, pos) => { if (found === null && node.isTextblock && node.textContent === words) found = pos + 1 + offset }) assert.notEqual(found, null, `no block reads ${words}`) return found } test('marks: em outside strong, bold reopened around italics, edges outside', () => { const cases = [ [paragraph(text('a ', 'strong'), text('b', 'em', 'strong'), text(' c', 'strong')), '**a** ***b*** **c**'], [paragraph(text('a ', 'em'), text('b', 'em', 'strong'), text(' c', 'em')), '*a **b** c*'], [paragraph(text('x', 'em', 'strong')), '***x***'], [paragraph(text('x'), text(' a ', 'em'), text('y')), 'x *a* y'], [paragraph(text('one '), text('two three', 'strong'), text('.')), 'one **two three**.'] ] for (const [doc, want] of cases) { assert.equal(write(doc), want) // Read back, the marks are the same, give or take a space's. assert.equal(write(fromMarkdown(schema, want)), want, `${want} reads back`) assert.equal(fromMarkdown(schema, want).textContent, doc.textContent) } }) test('marks close before code, links and atoms, and reopen after', () => { const link = schema.marks.link.create({ href: 'https://x.y' }) const chip = schema.nodes.wikilink.create({ target: 'Acme' }) assert.equal(write(paragraph(text('a ', 'em'), text('c', 'code'), text(' b', 'em'))), '*a* `c` *b*') assert.equal(write(paragraph(text('a ', 'em'), schema.text('l', [link]), text(' b', 'em'))), '*a* [l](https://x.y) *b*') assert.equal(write(paragraph(text('a ', 'em'), chip, text(' b', 'em'))), '*a* [[Acme]] *b*') }) test('untouched blocks and atoms re-emit their source; edited atoms are written from attributes', () => { const body = '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide\n\n##\tTabbed ^h1' const { view, fidelity } = editor(body) assert.equal(serialise(view.state.doc, fidelity), body) view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'wide'))) assert.equal(serialise(view.state.doc, fidelity), '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed ^h1') view.dispatch(view.state.tr.insertText('?', at(view.state.doc, 'Tabbed'))) assert.equal(serialise(view.state.doc, fidelity), '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed? ^h1') }) test('empty blocks are written as nothing', () => { const { view, fidelity } = editor('# Title\n\n- a\n\npara\n\n## b') for (const words of ['a', 'para', 'b']) { const end = at(view.state.doc, words) view.dispatch(view.state.tr.delete(end - words.length, end)) } assert.equal(serialise(view.state.doc, fidelity), '# Title') assert.deepEqual(view.state.doc.content.content.map(node => node.content.size === 0), [false, false, true, true, true], 'the empty blocks stay on screen') }) test('an unclosed fence that is no longer last gets its closing fence', () => { const { view, fidelity } = editor('```js\nlet a = 1') const end = view.state.doc.content.size view.dispatch(view.state.tr.insertText('after', end - 1)) assert.equal(serialise(view.state.doc, fidelity), '```js\nlet a = 1\n```\n\nafter') assert.equal(structureCheck(view.state.doc, fidelity).ok, true) }) test('the structure check puts Join\'s seam where a kept one would merge two blocks', () => { const { view, fidelity } = editor('- a\n- b') view.dispatch(view.state.tr.setSelection( TextSelection.create(view.state.doc, at(view.state.doc, 'b')))) view.run(liftListItem(schema.nodes.list_item)) assert.equal(view.state.doc.child(1).type.name, 'paragraph') const check = structureCheck(view.state.doc, fidelity) assert.equal(check.ok, true) assert.equal(check.body, '- a\n\nb') }) test('prepareSave adopts the parse when no seam or rewrite can save the document', () => { // No settle plugin: a paragraph that says "- a" is left as it is. const { doc, fidelity } = mount(schema, 'x') const view = { state: EditorState.create({ doc }), dispatch (tr) { this.state = this.state.apply(tr) } } view.dispatch(view.state.tr.insertText('- a', 1, 2)) assert.equal(structureCheck(view.state.doc, fidelity).ok, false) const { body, adopted } = prepareSave(view, fidelity) assert.equal(adopted, true) assert.equal(body, '- a') assert.equal(view.state.doc.firstChild.type.name, 'bullet_list') assert.equal(serialise(view.state.doc, fidelity), body) }) test('reparse: typed emphasis becomes a mark, "- " after a break becomes an item', () => { const { view, fidelity } = editor('hello') view.dispatch(view.state.tr.insertText(' *word*', at(view.state.doc, 'hello'))) const marks = [] view.state.doc.firstChild.forEach(node => marks.push([node.text, node.marks.map(m => m.type.name)])) assert.deepEqual(marks, [['hello ', []], ['word', ['em']]]) view.dispatch(view.state.tr.insert(view.state.doc.firstChild.nodeSize - 1, schema.nodes.hard_break.create())) view.dispatch(view.state.tr.insertText('- item', view.state.doc.firstChild.nodeSize - 1)) assert.deepEqual(view.state.doc.content.content.map(node => node.type.name), ['paragraph', 'bullet_list', 'paragraph']) // The line typed is kept as typed: a list right under a paragraph. assert.equal(serialise(view.state.doc, fidelity), 'hello *word*\n- item') assert.ok(settle(view.state, fidelity) === null, 'reparse is idempotent') }) test('a trailing hard break stays on screen and is written as nothing', () => { const { view, fidelity } = editor('- item\n\nnext') view.dispatch(view.state.tr.insert(at(view.state.doc, 'item'), schema.nodes.hard_break.create())) let breaks = 0 view.state.doc.descendants(node => { if (node.type.name === 'hard_break') breaks++ }) assert.equal(breaks, 1) assert.equal(serialise(view.state.doc, fidelity), '- item\n\nnext', 'still untouched') }) test('the reparse waits while an IME is composing', () => { let composing = true const { view } = editor('hello', { composing: () => composing }) view.dispatch(view.state.tr.insertText(' *x*', at(view.state.doc, 'hello'))) assert.equal(view.state.doc.firstChild.textContent, 'hello *x*') composing = false view.dispatch(view.state.tr.setMeta('composed', true)) assert.equal(view.state.doc.firstChild.textContent, 'hello x') }) test('copied blocks paste with their bytes and seams; a cut and paste gives the body back', () => { const body = 'x\n\na ^m1\n\n\n\n- b\n- c\n\n# d' const { view, fidelity } = editor(body) const from = at(view.state.doc, 'a', 0) const to = at(view.state.doc, 'c') const { text, mapa } = copyData(view.state, fidelity, from, to) assert.equal(text, 'a ^m1\n\n\n\n- b\n- c') // Paste into the empty paragraph after the heading: the marker is // already in the document, so the copy loses it. const end = view.state.doc.content.size - 1 view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, end))) view.dispatch(pasteTransaction(view.state, fidelity, mapa)) assert.equal(serialise(view.state.doc, fidelity), body + '\n\na\n\n\n\n- b\n- c') // Cut the originals and paste them back: the same bytes, marker and all. const again = editor(body) const cutFrom = at(again.view.state.doc, 'a', 0) const cutTo = at(again.view.state.doc, 'c') const cut = copyData(again.view.state, again.fidelity, cutFrom, cutTo) again.view.dispatch(again.view.state.tr.setSelection( TextSelection.create(again.view.state.doc, cutFrom, cutTo)).deleteSelection()) assert.equal(serialise(again.view.state.doc, again.fidelity), 'x\n\n# d') again.view.dispatch(pasteTransaction(again.view.state, again.fidelity, cut.mapa)) assert.equal(serialise(again.view.state.doc, again.fidelity), body) }) test('a forged x-mapa slice is refused, and text from outside is read as Markdown', () => { const { view, fidelity } = editor('a') for (const forged of ['{', '{"v":1,"sources":["a\\n\\nb"],"seams":[]}', '{"v":1,"sources":["a","b"],"seams":["\\nx\\n"]}', '{"v":2,"sources":["a"],"seams":[]}']) { assert.equal(pasteTransaction(view.state, fidelity, forged), null, forged) } const slice = textSlice(schema, '- one\n- [two](javascript:alert(1))') let links = 0 slice.content.descendants(node => { if (node.marks.some(m => m.type.name === 'link')) links++ }) assert.equal(links, 0, 'an unsafe address is not a link') }) test('rebuild changes origins only, outside undo history', () => { const { view, fidelity } = editor('a\n\nb') view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'b'))) const depth = undoDepth(view.state) const body = serialise(view.state.doc, fidelity) const before = view.state.doc assert.equal(rebuild(view, fidelity, body).ok, true) assert.equal(undoDepth(view.state), depth) assert.ok(view.state.doc.content.size === before.content.size) view.run(undo) assert.equal(serialise(view.state.doc, fidelity), 'a\n\nb', 'undo undoes the edit, not the rebuild') }) test('applyBody takes a teammate\'s block, keeps the caret, and ends untouched', () => { const { view, fidelity } = editor('one\n\ntwo\n\nthree') view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'three'))) view.dispatch(view.state.tr.setSelection( TextSelection.create(view.state.doc, at(view.state.doc, 'three!')))) const caret = view.state.selection.head const merged = 'one\n\n\ntwo, said Bo\n\nthree!' assert.equal(applyBody(view, fidelity, merged).ok, true) assert.equal(serialise(view.state.doc, fidelity), merged) assert.equal(view.state.selection.head, caret + ', said Bo'.length) view.run(undo) assert.equal(serialise(view.state.doc, fidelity), 'one\n\ntwo\n\nthree!') }) // "Untouched" includes the block's context (§6.4 step 2): a block whose // own node is unchanged but whose item or quote attributes changed is // written from the document, not re-emitted. Without the context in the // rule a toggled task box saved as it was (review: only make browser's // task-box click caught that). test('a block whose context changed is written again: a task toggled, a bullet, a quote', () => { const holder = (doc, name) => { let found = null doc.descendants((node, pos) => { if (found === null && node.type.name === name) found = { node, pos } }) return found } const cases = [ ['- [ ] Send Tom the summary\n- [x] Book the room', 'list_item', { checked: 'x' }, '- [x] Send Tom the summary\n- [x] Book the room'], ['- one\n- two', 'list_item', { bullet: '*' }, '* one\n- two'], ['> quoted\n> twice', 'blockquote', { prefix: ['>', '>'] }, '>quoted\n>twice'] ] for (const [body, name, change, want] of cases) { const { view, fidelity } = editor(body) const { node, pos } = holder(view.state.doc, name) view.dispatch(view.state.tr.setNodeMarkup(pos, null, { ...node.attrs, ...change })) assert.equal(serialise(view.state.doc, fidelity), want, body) } }) // The marker rule keeps an ^id on the block that held it before the // edit: a duplicate typed above it is the one taken away (review L; it // once took the id from the block links already name). test('a duplicate ^id typed above its holder never takes the id from it', () => { const { view, fidelity } = editor('Alpha\n\nBeta ^abc') view.dispatch(view.state.tr.insertText(' ^abc', view.state.doc.firstChild.nodeSize - 1)) assert.equal(serialise(view.state.doc, fidelity), 'Alpha\n\nBeta ^abc') }) // A copy-dragged block is the very node it copied, a later holder of // its origin, written from its node: it is reparsed, so the document // says what its Markdown says (review L; it was never checked). test('a copy-dragged block is reparsed, and says what its Markdown says', () => { const { view, fidelity } = editor('A.\n\n/d docBlocks(doc).filter(block => block.node.content.size > 0) .map(block => JSON.stringify(block.node.content.toJSON())) assert.deepEqual(inline(view.state.doc), inline(editor(written).view.state.doc)) }) // Undo can throw inside prosemirror-transform after many edits (an // attribute step mapped onto a text node; 4 in 20,000 fuzzed bodies). // The editor's undo and redo are guarded: the step is refused, never // thrown out of a key or a menu (review L). test('a history command that throws is refused, never thrown', async () => { const { guarded, safeUndo } = await import('./commands.mjs') const { view } = editor('One.') const throwing = guarded(() => { throw new RangeError('Position 17 out of range') }) assert.equal(throwing(view.state, tr => view.dispatch(tr)), false) assert.equal(safeUndo(view.state, tr => view.dispatch(tr)), false, 'nothing to undo') }) // Images (images spec §2.3, L1 and L2): an untouched image re-emits its // source; editing its alt text changes only that span. test('an image re-emits its source, and an edited alt changes only its span', () => { const body = 'Before ![a whiteboard](/i/2kq9xw3m1ab) after\n\n![](/i/z13) ^lone\n\nnext' const { view, fidelity } = editor(body) assert.equal(serialise(view.state.doc, fidelity), body) let pos = null view.state.doc.descendants((node, at) => { if (pos === null && node.type.name === 'image') pos = at }) view.dispatch(view.state.tr.setNodeAttribute(pos, 'alt', 'the pilot review')) assert.equal(serialise(view.state.doc, fidelity), 'Before ![the pilot review](/i/2kq9xw3m1ab) after\n\n![](/i/z13) ^lone\n\nnext') }) // Fable L3 on 49d8df3: a paste from another page whose copy is refused // pastes nothing and says why, rather than addresses that would not // draw. A copy that works pastes the copies' addresses. test('a paste whose image copy is refused says why and pastes nothing', async () => { const { clipboardPlugin } = await import('./clipboard.mjs') const slice = JSON.stringify({ v: 1, sources: ['![a](/i/far1)'], seams: [], page: 'other' }) const paste = { preventDefault () {}, clipboardData: { getData: type => type === 'application/x-mapa' ? slice : '' } } for (const [status, json, want] of [ [507, { refused: 'Your image allowance of 1 GB is full. Remove an image before uploading again.' }, 'Here.'], [200, { far1: { id: 'near2', width: 1, height: 1 } }, 'Here.![a](/i/near2)'] ]) { const { view, fidelity } = editor('Here.') view.dispatch(view.state.tr.setSelection(TextSelection.atEnd(view.state.doc))) let said = null const plugin = clipboardPlugin(fidelity, { page: () => 'this', copy: async () => ({ status, json }), refused: why => { said = why } }) assert.equal(plugin.props.handlePaste(view, paste), true) await new Promise(resolve => setTimeout(resolve, 5)) assert.equal(serialise(view.state.doc, fidelity), want) if (status !== 200) assert.equal(said, 'Your image allowance of 1 GB is full. Remove an image before uploading again.') } })