oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// upload.test.mjs — the upload queue (images spec §4.2), without a
2// browser: a fake document for the box, a fake XMLHttpRequest the test
3// answers, and a view that is an EditorState. Fable's round on 49d8df3:
4// M3 (text on the clipboard wins), M4 (Replace… keeps the old image
5// until the new one is in, and its alt), M5 (a box survives edits next
6// to it), M6 (several files in order), L12 (an undone failure does not
7// stall the queue).
8
9import { test } from 'node:test'
10import assert from 'node:assert/strict'
11import { EditorState } from 'prosemirror-state'
12import { history, undo } from 'prosemirror-history'
13import { schema } from './testkit.mjs'
14import { fromMarkdown } from './fromMarkdown.mjs'
15import { serialise } from './serialize.mjs'
16import { uploadsPlugin, uploadFiles, droppingPlugin, replaceImage, inFlight, refusal } from './upload.mjs'
17
18class Element {
19 constructor (tag) {
20 this.tagName = tag
21 this.attributes = {}
22 this.listeners = {}
23 this.children = []
24 this.hidden = false
25 this.textContent = ''
26 this.value = 0
27 }
28
29 setAttribute (name, value) { this.attributes[name] = String(value) }
30 getAttribute (name) { return this.attributes[name] ?? null }
31 removeAttribute (name) { delete this.attributes[name] }
32 append (...children) { this.children.push(...children) }
33 remove () {}
34 addEventListener (type, fn) { (this.listeners[type] ??= []).push(fn) }
35 querySelector (tag) { return this.children.find(child => child.tagName === tag) ?? null }
36 click () { for (const fn of this.listeners.click ?? []) fn({ preventDefault () {} }) }
37}
38globalThis.document = { createElement: tag => new Element(tag) }
39
40// replies are the uploads waiting for an answer, in order.
41const replies = []
42globalThis.XMLHttpRequest = class {
43 constructor () {
44 this.listeners = {}
45 this.upload = { addEventListener () {} }
46 }
47
48 open () {}
49 setRequestHeader () {}
50 addEventListener (type, fn) { this.listeners[type] = fn }
51 send () {
52 replies.push((status, json) => {
53 this.status = status
54 this.response = json
55 this.listeners.load?.()
56 })
57 }
58}
59
60// answer replies to the oldest upload waiting, once one is.
61async function answer (status, json) {
62 for (let tries = 0; replies.length === 0 && tries < 200; tries++) {
63 await new Promise(resolve => setTimeout(resolve, 1))
64 }
65 assert.ok(replies.length, 'no upload was sent')
66 replies.shift()(status, json)
67 await new Promise(resolve => setTimeout(resolve, 5))
68}
69
70const image = id => ({ id, src: `/i/${id}`, width: 10, height: 10 })
71const png = name => new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], name, { type: 'image/png' })
72
73function view (body) {
74 const doc = fromMarkdown(schema, body)
75 const holder = {
76 state: EditorState.create({ doc, plugins: [uploadsPlugin(), history()] }),
77 dispatch (tr) { holder.state = holder.state.apply(tr) },
78 focus () {}
79 }
80 return holder
81}
82
83const hooks = () => ({ answers: { set () {} }, say () {}, notice () {}, alt () {} })
84const text = v => serialise(v.state.doc, null)
85
86// end is the position at the end of the first paragraph's text.
87const end = v => v.state.doc.firstChild.nodeSize - 1
88
89test('M6: several files land in the order they were chosen', async () => {
90 const v = view('Pictures:')
91 const done = uploadFiles(v, [png('one.png'), png('two.png')], end(v), hooks())
92 await answer(200, image('aa1'))
93 await answer(200, image('bb2'))
94 await done
95 assert.equal(text(v), 'Pictures:![](/i/aa1)![](/i/bb2)')
96})
97
98test('M5: one Backspace before the box keeps the image where the box is', async () => {
99 const v = view('Pictures: ')
100 const done = uploadFiles(v, [png('one.png')], end(v), hooks())
101 await new Promise(resolve => setTimeout(resolve, 5))
102 v.dispatch(v.state.tr.delete(end(v) - 1, end(v)))
103 await answer(200, image('aa1'))
104 await done
105 assert.equal(text(v), 'Pictures:![](/i/aa1)')
106})
107
108test('M5: undoing text typed just before the box keeps the upload', async () => {
109 const v = view('Pictures')
110 v.dispatch(v.state.tr.insertText(' here', end(v)))
111 const done = uploadFiles(v, [png('one.png')], end(v), hooks())
112 await new Promise(resolve => setTimeout(resolve, 5))
113 assert.ok(undo(v.state, tr => v.dispatch(tr)), 'nothing to undo')
114 await answer(200, image('aa1'))
115 await done
116 assert.equal(text(v), 'Pictures![](/i/aa1)')
117})
118
119test('L12: a failed upload an undo takes away does not stall the next', async () => {
120 const v = view('One')
121 v.dispatch(v.state.tr.insertText(' Hello world', end(v)))
122 const middle = end(v) - ' world'.length
123 const done = uploadFiles(v, [png('one.png'), png('two.png')], middle, hooks())
124 await answer(500, { refused: 'no' })
125 // The typing the box sits in is undone, box and all.
126 assert.ok(undo(v.state, tr => v.dispatch(tr)), 'nothing to undo')
127 await answer(200, image('bb2'))
128 await Promise.race([done, new Promise((resolve, reject) =>
129 setTimeout(() => reject(new Error('the queue stalled')), 500))])
130 assert.match(text(v), /bb2/u)
131 assert.equal(inFlight(v.state), 0)
132})
133
134test('M4: Replace… keeps the old image until the new one is in, and its alt', async () => {
135 const v = view('A ![the plan](/i/old1) here')
136 const at = 3
137 assert.equal(v.state.doc.nodeAt(at)?.attrs.id, 'old1')
138 const failing = replaceImage(v, at, png('new.png'), hooks())
139 await answer(500, { refused: 'no' })
140 assert.equal(text(v), 'A ![the plan](/i/old1) here', 'a failed replace leaves the old image')
141 assert.equal(inFlight(v.state), 1)
142 void failing
143 const v2 = view('A ![the plan](/i/old1) here')
144 const working = replaceImage(v2, at, png('new.png'), hooks())
145 await answer(200, image('new2'))
146 await working
147 assert.equal(text(v2), 'A ![the plan](/i/new2) here')
148})
149
150test('M3 and N1: text wins, except over a picture copied from a page', () => {
151 const v = view('Cells:')
152 const plugin = droppingPlugin(hooks())
153 const event = (types) => ({
154 preventDefault () {},
155 clipboardData: {
156 files: [png('cells.png')],
157 getData: type => types[type] ?? ''
158 }
159 })
160 const pastes = [
161 // Spreadsheet cells: text, HTML and a picture of them. The cells win.
162 [{ 'text/plain': 'a\tb', 'text/html': '<table><tr><td>a</td><td>b</td></tr></table>' }, false],
163 // Text alone beside a picture: the text wins.
164 [{ 'text/plain': 'a line' }, false],
165 // Chrome's Copy image: the picture and a lone <img>.
166 [{ 'text/html': '<meta charset="utf-8"><img src="https://example.com/a.png" alt="a">' }, true],
167 // Firefox's: the same, with the address as text.
168 [{ 'text/html': '<img src="https://example.com/a.png">', 'text/plain': 'https://example.com/a.png' }, true],
169 // An <img> inside other HTML is not a lone picture.
170 [{ 'text/html': '<p>See <img src="x"></p>' }, false],
171 // The picture and its address, no HTML.
172 [{ 'text/plain': 'https://example.com/a.png' }, true],
173 // A file copied in Finder (Chrome on macOS): the file and its name.
174 [{ 'text/plain': 'cells.png' }, true],
175 // Chrome's Copy image with a > inside an attribute.
176 [{ 'text/html': '<img src="https://example.com/a.png" alt="a > b">' }, true],
177 // A bare picture: a screenshot.
178 [{}, true]
179 ]
180 for (const [types, uploads] of pastes) {
181 assert.equal(plugin.props.handlePaste(v, event(types)), uploads, JSON.stringify(types))
182 }
183})
184
185test('N2: a JPEG over 10 MB is scaled before its size is checked', () => {
186 const big = size => new File([new Uint8Array(size)], 'photo.jpg', { type: 'image/jpeg' })
187 assert.equal(refusal(big(12 * 1024 * 1024)), null)
188 const png = new File([new Uint8Array(12 * 1024 * 1024)], 'shot.png', { type: 'image/png' })
189 assert.match(refusal(png), /10 MB/u)
190})
191