oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// upload.mjs — getting an image in (images spec §4.1, §4.2). Paste or
2// drop image files, or choose one with Insert → Image…, / → Image or
3// the phone's image button. Each file uploads in order into its own
4// place. While it uploads, its place is a decoration, never a node: a
5// box with the file's name and a <progress>, at a fixed height, mapped
6// through every transaction. The document holds nothing until the
7// upload succeeds, so autosave, other tabs and teammates never see a
8// dangling address. On success the image atom goes in at the mapped
9// place, or at the end of the page if that place was deleted; if an
10// undo took the place away, the result is dropped (the pending image is
11// swept later). On failure the box says why and offers Retry and Remove.
12
13import { Plugin, PluginKey, TextSelection } from 'prosemirror-state'
14import { Decoration, DecorationSet } from 'prosemirror-view'
15
16export const accepted = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']
17export const acceptList = accepted.join(',')
18export const MAX_BYTES = 10 * 1024 * 1024
19// LONG_SIDE is the longest side a JPEG keeps before it is sent (Q3).
20export const LONG_SIDE = 4096
21
22export const uploadsKey = new PluginKey('mapa-uploads')
23
24// reasons are the box's words for each refusal the client can tell.
25const reasons = {
26 type: 'Mapa takes PNG, JPEG, GIF and WebP images.',
27 svg: 'Mapa takes PNG, JPEG, GIF and WebP images, not SVG.',
28 size: 'An image can be at most 10 MB.',
29 offline: 'Connection unavailable.',
30 failed: 'The image could not be stored. Try again.'
31}
32
33// refusal is why a file is refused before it is sent, or null. A JPEG's
34// size is checked after it is scaled (§4.1, Fable N2): a 48 MP photo is
35// over 10 MB until then.
36export function refusal (file) {
37 if (file.type === 'image/svg+xml' || /\.svg$/iu.test(file.name ?? '')) return reasons.svg
38 if (!accepted.includes(file.type)) return reasons.type
39 if (file.type !== 'image/jpeg' && file.size > MAX_BYTES) return reasons.size
40 return null
41}
42
43// jpegShape is a JPEG's size and EXIF orientation, read from its first
44// bytes, or null.
45export function jpegShape (bytes) {
46 if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null
47 let orientation = 1
48 for (let at = 2; at + 4 <= bytes.length;) {
49 if (bytes[at] !== 0xff) return null
50 const marker = bytes[at + 1]
51 const length = (bytes[at + 2] << 8) | bytes[at + 3]
52 if (marker === 0xe1) orientation = exifOrientation(bytes, at + 4, at + 2 + length) ?? orientation
53 if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
54 const height = (bytes[at + 5] << 8) | bytes[at + 6]
55 const width = (bytes[at + 7] << 8) | bytes[at + 8]
56 return { width, height, orientation }
57 }
58 at += 2 + length
59 }
60 return null
61}
62
63function exifOrientation (bytes, start, end) {
64 const text = String.fromCharCode(...bytes.slice(start, start + 6))
65 if (text !== 'Exif\0\0') return null
66 const tiff = start + 6
67 const little = bytes[tiff] === 0x49
68 const u16 = at => little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]
69 const u32 = at => little
70 ? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16)) + bytes[at + 3] * 0x1000000
71 : bytes[at] * 0x1000000 + ((bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3])
72 const ifd = tiff + u32(tiff + 4)
73 if (ifd + 2 > end) return null
74 for (let entry = 0; entry < u16(ifd); entry++) {
75 const at = ifd + 2 + entry * 12
76 if (at + 12 > end) return null
77 if (u16(at) === 0x0112) return u16(at + 8)
78 }
79 return null
80}
81
82// prepared is the file to send: a JPEG over LONG_SIDE on its long side
83// decoded upright and smaller, drawn to a canvas and sent at quality
84// 0.9 (a canvas drops EXIF, so the orientation is applied while
85// decoding); anything else, or a JPEG that will not decode, as it is.
86export async function prepared (file) {
87 if (file.type !== 'image/jpeg' || typeof createImageBitmap !== 'function') return file
88 let shape
89 try {
90 shape = jpegShape(new Uint8Array(await file.slice(0, 256 * 1024).arrayBuffer()))
91 } catch {
92 return file
93 }
94 if (!shape || Math.max(shape.width, shape.height) <= LONG_SIDE) return file
95 const scale = LONG_SIDE / Math.max(shape.width, shape.height)
96 const turned = shape.orientation >= 5
97 const width = Math.round((turned ? shape.height : shape.width) * scale)
98 const height = Math.round((turned ? shape.width : shape.height) * scale)
99 try {
100 const bitmap = await createImageBitmap(file, {
101 imageOrientation: 'from-image', resizeWidth: width, resizeHeight: height, resizeQuality: 'high'
102 })
103 const canvas = document.createElement('canvas')
104 canvas.width = bitmap.width
105 canvas.height = bitmap.height
106 canvas.getContext('2d').drawImage(bitmap, 0, 0)
107 bitmap.close?.()
108 const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.9))
109 return blob ? new File([blob], file.name, { type: 'image/jpeg' }) : file
110 } catch {
111 return file
112 }
113}
114
115// send uploads file with XMLHttpRequest, so progress is reported. It
116// answers { status, json }.
117export function send (file, progress) {
118 return new Promise(resolve => {
119 const request = new XMLHttpRequest()
120 request.open('POST', '/images')
121 request.setRequestHeader('Accept', 'application/json')
122 request.responseType = 'json'
123 request.upload.addEventListener('progress', event => {
124 if (event.lengthComputable) progress(event.loaded / event.total)
125 })
126 request.addEventListener('load', () => resolve({ status: request.status, json: request.response }))
127 request.addEventListener('error', () => resolve({ status: 0, json: null }))
128 request.addEventListener('abort', () => resolve({ status: 0, json: null }))
129 const form = new FormData()
130 form.append('file', file, file.name || 'image')
131 request.send(form)
132 })
133}
134
135// box is an upload's placeholder: a group named for its file, with a
136// labelled <progress>, at a fixed height. On failure it says why and
137// offers Retry and Remove.
138function box (upload) {
139 const group = document.createElement('span')
140 group.setAttribute('mapa-upload', '')
141 group.setAttribute('role', 'group')
142 group.setAttribute('aria-label', `Uploading ${upload.name}`)
143 group.contentEditable = 'false'
144 const name = document.createElement('span')
145 name.setAttribute('mapa-upload-name', '')
146 name.textContent = upload.name
147 const bar = document.createElement('progress')
148 bar.max = 1
149 bar.setAttribute('aria-label', `Uploading ${upload.name}`)
150 const why = document.createElement('span')
151 why.setAttribute('mapa-upload-why', '')
152 why.hidden = true
153 group.append(name, bar, why)
154 return { group, bar, why }
155}
156
157// mapped is each upload's place after tr. Edits beside the box move it
158// and nothing more: a Backspace before it, or undoing text typed just
159// before it (Fable M5). Only a box whose own place was deleted, with
160// text on both sides of it, is lost, and the image then goes at the
161// end; one an undo took away drops the result. A block the server's
162// text wrote again (a rebase, the inline choice) keeps the box at the
163// same offset in the block that replaced it (build note I6).
164function mapped (uploads, tr, before) {
165 const undoing = Boolean(tr.getMeta('history$'))
166 for (const upload of uploads.values()) {
167 if (upload.dropped) continue
168 follow(upload, tr)
169 const result = tr.mapping.mapResult(upload.pos, -1)
170 const old = upload.pos
171 upload.pos = result.pos
172 if (!result.deletedAcross || upload.lost) continue
173 const kept = tr.getMeta('mapa-applied') ? rewritten(before, tr.doc, old, result.pos) : null
174 if (kept !== null) upload.pos = kept
175 else if (undoing) drop(upload)
176 else upload.lost = true
177 }
178 return uploads
179}
180
181// follow maps the image a Replace… is replacing; gone, the new image
182// goes in at the box instead.
183function follow (upload, tr) {
184 if (!upload.replacing) return
185 const result = tr.mapping.mapResult(upload.replacing.pos, 1)
186 upload.replacing.pos = result.pos
187 if (result.deleted) upload.replacing.gone = true
188}
189
190// drop ends an upload an undo took away, and lets a failed one waiting
191// on Retry or Remove go, so the files after it still upload (Fable
192// L12).
193function drop (upload) {
194 upload.dropped = true
195 queueMicrotask(() => upload.onDrop?.())
196}
197
198// rewritten is the place in a block written again: the same offset in
199// the textblock that now starts where the old one did, or null.
200function rewritten (before, after, old, mapped) {
201 const $old = before.resolve(old)
202 if (!$old.parent.inlineContent) return null
203 let found = null
204 after.nodesBetween(mapped, Math.min(after.content.size, mapped + 2), (node, pos) => {
205 if (found === null && node.isTextblock) {
206 found = pos + 1 + Math.min($old.parentOffset, node.content.size)
207 }
208 return found === null
209 })
210 return found
211}
212
213export function uploadsPlugin () {
214 return new Plugin({
215 key: uploadsKey,
216 state: {
217 init: () => ({ uploads: new Map(), moves: 0 }),
218 apply (tr, value, before) {
219 const meta = tr.getMeta(uploadsKey)
220 const uploads = mapped(value.uploads, tr, before.doc)
221 if (meta?.add) uploads.set(meta.add.id, meta.add)
222 if (meta?.remove) uploads.delete(meta.remove)
223 const moves = value.moves + (tr.selectionSet || tr.docChanged ? 1 : 0)
224 return { uploads, moves }
225 }
226 },
227 props: {
228 decorations (state) {
229 const { uploads } = uploadsKey.getState(state)
230 const shown = [...uploads.values()].filter(upload => !upload.dropped)
231 return DecorationSet.create(state.doc, shown.map(upload =>
232 Decoration.widget(Math.min(upload.lost ? state.doc.content.size - 1 : upload.pos,
233 state.doc.content.size), upload.dom.group, { key: upload.id, side: -1 })))
234 }
235 }
236 })
237}
238
239let nextUpload = 0
240
241// inFlight is how many uploads are running or waiting on the person.
242export function inFlight (state) {
243 const value = uploadsKey.getState(state)
244 return value ? [...value.uploads.values()].filter(upload => !upload.dropped).length : 0
245}
246
247// uploadFiles uploads each file in order into its own place, starting
248// at pos, each after the one before it (Fable M6). hooks: answers
249// (ImageAnswers), say (the live region), alt (the alt field), notice (a
250// bar's sentence).
251export async function uploadFiles (view, files, pos, hooks) {
252 for (const file of files) {
253 const upload = start(view, file, pos)
254 pos = (await run(view, upload, hooks)) ?? upload.pos
255 }
256}
257
258// replaceImage is Replace…: the new file uploads in a box after the
259// image at pos, which stays until the new one is in; then the node takes
260// the new id and keeps its alt (Fable M4). A failed replace leaves the
261// old image as it was.
262export function replaceImage (view, pos, file, hooks, id = null) {
263 const old = view.state.doc.nodeAt(pos)
264 // The image chosen, by its id, or nothing (Fable N8): the document may
265 // have moved while the picker was open.
266 if (old?.type.name !== 'image' || (id !== null && old.attrs.id !== id)) {
267 return Promise.resolve()
268 }
269 const upload = start(view, file, pos + 1, { pos, id: old.attrs.id, alt: old.attrs.alt })
270 return run(view, upload, hooks)
271}
272
273function start (view, file, pos, replacing = null) {
274 const id = `upload-${++nextUpload}`
275 const upload = { id, file, name: file.name || 'image', pos, replacing }
276 upload.dom = box(upload)
277 upload.dom.bar.value = 0
278 view.dispatch(view.state.tr.setMeta(uploadsKey, { add: upload }).setMeta('addToHistory', false))
279 upload.moves = uploadsKey.getState(view.state).moves
280 return upload
281}
282
283function remove (view, upload) {
284 view.dispatch(view.state.tr.setMeta(uploadsKey, { remove: upload.id }).setMeta('addToHistory', false))
285}
286
287// run uploads one file and answers the place after its image, or
288// nothing when none went in.
289async function run (view, upload, hooks) {
290 const early = refusal(upload.file)
291 if (early) return failed(view, upload, early, hooks)
292 const file = await prepared(upload.file)
293 if (file.size > MAX_BYTES) return failed(view, upload, reasons.size, hooks)
294 const reply = await send(file, share => { upload.dom.bar.value = share })
295 if (upload.dropped) return remove(view, upload)
296 if (reply.status !== 200 || !reply.json?.id) {
297 const why = reply.status === 0 ? reasons.offline : (reply.json?.refused ?? reasons.failed)
298 return failed(view, upload, why, hooks)
299 }
300 return placed(view, upload, reply.json, hooks)
301}
302
303// swapped is Replace…'s success: the image it replaces takes the new
304// id, its alt kept; null when that image is gone.
305function swapped (view, upload, image) {
306 const { pos, id, gone } = upload.replacing
307 const node = view.state.doc.nodeAt(pos)
308 if (gone || node?.type.name !== 'image' || node.attrs.id !== id) return null
309 view.dispatch(view.state.tr.setMeta(uploadsKey, { remove: upload.id })
310 .setNodeMarkup(pos, null, { ...node.attrs, id: image.id, source: null }))
311 return pos + 1
312}
313
314// placed puts the image where its box was, or at the end of the page,
315// and answers the place after it.
316function placed (view, upload, image, hooks) {
317 hooks.answers.set(image.id, { width: image.width, height: image.height })
318 if (upload.replacing) {
319 const after = swapped(view, upload, image)
320 if (after !== null) {
321 hooks.say?.('Image replaced')
322 return after
323 }
324 }
325 const node = view.state.schema.nodes.image.create({ id: image.id, alt: upload.replacing?.alt ?? '' })
326 const still = uploadsKey.getState(view.state).moves === upload.moves
327 let tr = view.state.tr.setMeta(uploadsKey, { remove: upload.id })
328 let at = upload.pos
329 const inline = !upload.lost && tr.doc.resolve(at).parent.inlineContent &&
330 !tr.doc.resolve(at).parent.type.spec.code
331 if (inline) {
332 tr = tr.insert(at, node)
333 } else {
334 // A place between blocks, or one that was deleted: the image is a
335 // paragraph of its own, there or at the end of the page.
336 if (upload.lost) {
337 at = tr.doc.content.size
338 hooks.notice?.('Image added at the end of the page')
339 }
340 tr = tr.insert(at, view.state.schema.nodes.paragraph.create(null, node))
341 at += 1
342 }
343 view.dispatch(tr)
344 if (still && !upload.replacing) hooks.alt?.(view, at)
345 else hooks.say?.(upload.replacing ? 'Image replaced' : 'Image added')
346 return at + 1
347}
348
349function failed (view, upload, why, hooks) {
350 const { group, why: line, bar } = upload.dom
351 bar.hidden = true
352 line.hidden = false
353 line.textContent = why
354 group.setAttribute('aria-label', `Not uploaded: ${upload.name}`)
355 group.setAttribute('mapa-upload', 'failed')
356 hooks.say?.(`Not uploaded: ${why}`)
357 const act = (label, fn) => {
358 const button = document.createElement('button')
359 button.type = 'button'
360 button.setAttribute('rst-btn', '')
361 button.textContent = label
362 button.addEventListener('mousedown', event => event.preventDefault())
363 button.addEventListener('click', fn)
364 group.append(button)
365 return button
366 }
367 return new Promise(resolve => {
368 // Undone away while it waits: the queue goes on (Fable L12).
369 upload.onDrop = () => {
370 remove(view, upload)
371 resolve()
372 }
373 const retry = act('Retry', async () => {
374 retry.remove()
375 dismiss.remove()
376 line.hidden = true
377 bar.hidden = false
378 group.setAttribute('mapa-upload', '')
379 group.setAttribute('aria-label', `Uploading ${upload.name}`)
380 upload.onDrop = null
381 resolve(await run(view, upload, hooks))
382 })
383 const dismiss = act('Dismiss', () => {
384 remove(view, upload)
385 view.focus()
386 resolve()
387 })
388 })
389}
390
391// imageFiles is the image files a paste or a drop carries.
392export function imageFiles (transfer) {
393 return [...(transfer?.files ?? [])].filter(file => file.type.startsWith('image/') || /\.svg$/iu.test(file.name))
394}
395
396// pastedFiles is the image files a paste uploads. A spreadsheet's
397// cells arrive as text, HTML and a picture of them, and the cells are
398// what was copied, so text wins (Fable M3). But a browser's Copy image
399// sends the picture with HTML that is one <img> and nothing else (and
400// Firefox the address as text): there the picture wins (Fable N1).
401// With no HTML, text that is only the picture's own address (a web
402// address and nothing else) is Copy image's shape too; and text whose
403// every line is the name of one of the files is a file copied in
404// Finder (Chrome on macOS sends the name as text).
405export function pastedFiles (data) {
406 const html = data?.getData?.('text/html') ?? ''
407 const files = imageFiles(data)
408 if (html) return loneImage(html) ? files : []
409 const text = (data?.getData?.('text/plain') ?? '').trim()
410 if (!text || /^https?:\/\/[^\s]+$/u.test(text)) return files
411 const names = new Set(files.map(file => file.name))
412 const lines = text.split(/\r?\n/u).map(line => line.trim()).filter(Boolean)
413 return lines.every(line => names.has(line)) ? files : []
414}
415
416// loneImage is HTML that holds one <img> and no text: what a browser's
417// Copy image puts on the clipboard beside the picture.
418export function loneImage (html) {
419 const bare = html
420 .replace(/<!--[^]*?-->/gu, '')
421 .replace(/<\/?(?:html|head|body|meta)\b[^>]*>/giu, '')
422 .trim()
423 // An attribute may hold a > in quotes (Fable, round 5).
424 return /^<img\b(?:"[^"]*"|'[^']*'|[^<>"'])*>$/iu.test(bare)
425}
426
427// choose opens the file picker (Insert → Image…, / → Image, the phone's
428// button) and uploads what is chosen at the caret.
429export function chooser (hooks) {
430 return (state, dispatch, view) => {
431 if (!view) return true
432 const input = document.createElement('input')
433 input.type = 'file'
434 input.accept = acceptList
435 input.multiple = true
436 input.hidden = true
437 input.setAttribute('mapa-image-input', '')
438 input.addEventListener('change', () => {
439 const files = [...input.files]
440 input.remove()
441 if (files.length) uploadFiles(view, files, view.state.selection.from, hooks)
442 })
443 document.body.append(input)
444 input.click()
445 return true
446 }
447}
448
449// dropping is paste and drop of image files: each uploads at the
450// caret, or where the drop cursor marked.
451export function droppingPlugin (hooks) {
452 return new Plugin({
453 props: {
454 handlePaste (view, event) {
455 const files = pastedFiles(event.clipboardData)
456 if (!files.length) return false
457 event.preventDefault()
458 uploadFiles(view, files, view.state.selection.from, hooks)
459 return true
460 },
461 handleDrop (view, event) {
462 const files = imageFiles(event.dataTransfer)
463 if (!files.length) return false
464 event.preventDefault()
465 const at = view.posAtCoords({ left: event.clientX, top: event.clientY })
466 const pos = at?.pos ?? view.state.selection.from
467 view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(pos))))
468 uploadFiles(view, files, view.state.selection.from, hooks)
469 return true
470 }
471 }
472 })
473}
474