// upload.mjs — getting an image in (images spec §4.1, §4.2). Paste or // drop image files, or choose one with Insert → Image…, / → Image or // the phone's image button. Each file uploads in order into its own // place. While it uploads, its place is a decoration, never a node: a // box with the file's name and a , at a fixed height, mapped // through every transaction. The document holds nothing until the // upload succeeds, so autosave, other tabs and teammates never see a // dangling address. On success the image atom goes in at the mapped // place, or at the end of the page if that place was deleted; if an // undo took the place away, the result is dropped (the pending image is // swept later). On failure the box says why and offers Retry and Remove. import { Plugin, PluginKey, TextSelection } from 'prosemirror-state' import { Decoration, DecorationSet } from 'prosemirror-view' export const accepted = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] export const acceptList = accepted.join(',') export const MAX_BYTES = 10 * 1024 * 1024 // LONG_SIDE is the longest side a JPEG keeps before it is sent (Q3). export const LONG_SIDE = 4096 export const uploadsKey = new PluginKey('mapa-uploads') // reasons are the box's words for each refusal the client can tell. const reasons = { type: 'Mapa takes PNG, JPEG, GIF and WebP images.', svg: 'Mapa takes PNG, JPEG, GIF and WebP images, not SVG.', size: 'An image can be at most 10 MB.', offline: 'Connection unavailable.', failed: 'The image could not be stored. Try again.' } // refusal is why a file is refused before it is sent, or null. A JPEG's // size is checked after it is scaled (§4.1, Fable N2): a 48 MP photo is // over 10 MB until then. export function refusal (file) { if (file.type === 'image/svg+xml' || /\.svg$/iu.test(file.name ?? '')) return reasons.svg if (!accepted.includes(file.type)) return reasons.type if (file.type !== 'image/jpeg' && file.size > MAX_BYTES) return reasons.size return null } // jpegShape is a JPEG's size and EXIF orientation, read from its first // bytes, or null. export function jpegShape (bytes) { if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null let orientation = 1 for (let at = 2; at + 4 <= bytes.length;) { if (bytes[at] !== 0xff) return null const marker = bytes[at + 1] const length = (bytes[at + 2] << 8) | bytes[at + 3] if (marker === 0xe1) orientation = exifOrientation(bytes, at + 4, at + 2 + length) ?? orientation if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) { const height = (bytes[at + 5] << 8) | bytes[at + 6] const width = (bytes[at + 7] << 8) | bytes[at + 8] return { width, height, orientation } } at += 2 + length } return null } function exifOrientation (bytes, start, end) { const text = String.fromCharCode(...bytes.slice(start, start + 6)) if (text !== 'Exif\0\0') return null const tiff = start + 6 const little = bytes[tiff] === 0x49 const u16 = at => little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1] const u32 = at => little ? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16)) + bytes[at + 3] * 0x1000000 : bytes[at] * 0x1000000 + ((bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) const ifd = tiff + u32(tiff + 4) if (ifd + 2 > end) return null for (let entry = 0; entry < u16(ifd); entry++) { const at = ifd + 2 + entry * 12 if (at + 12 > end) return null if (u16(at) === 0x0112) return u16(at + 8) } return null } // prepared is the file to send: a JPEG over LONG_SIDE on its long side // decoded upright and smaller, drawn to a canvas and sent at quality // 0.9 (a canvas drops EXIF, so the orientation is applied while // decoding); anything else, or a JPEG that will not decode, as it is. export async function prepared (file) { if (file.type !== 'image/jpeg' || typeof createImageBitmap !== 'function') return file let shape try { shape = jpegShape(new Uint8Array(await file.slice(0, 256 * 1024).arrayBuffer())) } catch { return file } if (!shape || Math.max(shape.width, shape.height) <= LONG_SIDE) return file const scale = LONG_SIDE / Math.max(shape.width, shape.height) const turned = shape.orientation >= 5 const width = Math.round((turned ? shape.height : shape.width) * scale) const height = Math.round((turned ? shape.width : shape.height) * scale) try { const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image', resizeWidth: width, resizeHeight: height, resizeQuality: 'high' }) const canvas = document.createElement('canvas') canvas.width = bitmap.width canvas.height = bitmap.height canvas.getContext('2d').drawImage(bitmap, 0, 0) bitmap.close?.() const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.9)) return blob ? new File([blob], file.name, { type: 'image/jpeg' }) : file } catch { return file } } // send uploads file with XMLHttpRequest, so progress is reported. It // answers { status, json }. export function send (file, progress) { return new Promise(resolve => { const request = new XMLHttpRequest() request.open('POST', '/images') request.setRequestHeader('Accept', 'application/json') request.responseType = 'json' request.upload.addEventListener('progress', event => { if (event.lengthComputable) progress(event.loaded / event.total) }) request.addEventListener('load', () => resolve({ status: request.status, json: request.response })) request.addEventListener('error', () => resolve({ status: 0, json: null })) request.addEventListener('abort', () => resolve({ status: 0, json: null })) const form = new FormData() form.append('file', file, file.name || 'image') request.send(form) }) } // box is an upload's placeholder: a group named for its file, with a // labelled , at a fixed height. On failure it says why and // offers Retry and Remove. function box (upload) { const group = document.createElement('span') group.setAttribute('mapa-upload', '') group.setAttribute('role', 'group') group.setAttribute('aria-label', `Uploading ${upload.name}`) group.contentEditable = 'false' const name = document.createElement('span') name.setAttribute('mapa-upload-name', '') name.textContent = upload.name const bar = document.createElement('progress') bar.max = 1 bar.setAttribute('aria-label', `Uploading ${upload.name}`) const why = document.createElement('span') why.setAttribute('mapa-upload-why', '') why.hidden = true group.append(name, bar, why) return { group, bar, why } } // mapped is each upload's place after tr. Edits beside the box move it // and nothing more: a Backspace before it, or undoing text typed just // before it (Fable M5). Only a box whose own place was deleted, with // text on both sides of it, is lost, and the image then goes at the // end; one an undo took away drops the result. A block the server's // text wrote again (a rebase, the inline choice) keeps the box at the // same offset in the block that replaced it (build note I6). function mapped (uploads, tr, before) { const undoing = Boolean(tr.getMeta('history$')) for (const upload of uploads.values()) { if (upload.dropped) continue follow(upload, tr) const result = tr.mapping.mapResult(upload.pos, -1) const old = upload.pos upload.pos = result.pos if (!result.deletedAcross || upload.lost) continue const kept = tr.getMeta('mapa-applied') ? rewritten(before, tr.doc, old, result.pos) : null if (kept !== null) upload.pos = kept else if (undoing) drop(upload) else upload.lost = true } return uploads } // follow maps the image a Replace… is replacing; gone, the new image // goes in at the box instead. function follow (upload, tr) { if (!upload.replacing) return const result = tr.mapping.mapResult(upload.replacing.pos, 1) upload.replacing.pos = result.pos if (result.deleted) upload.replacing.gone = true } // drop ends an upload an undo took away, and lets a failed one waiting // on Retry or Remove go, so the files after it still upload (Fable // L12). function drop (upload) { upload.dropped = true queueMicrotask(() => upload.onDrop?.()) } // rewritten is the place in a block written again: the same offset in // the textblock that now starts where the old one did, or null. function rewritten (before, after, old, mapped) { const $old = before.resolve(old) if (!$old.parent.inlineContent) return null let found = null after.nodesBetween(mapped, Math.min(after.content.size, mapped + 2), (node, pos) => { if (found === null && node.isTextblock) { found = pos + 1 + Math.min($old.parentOffset, node.content.size) } return found === null }) return found } export function uploadsPlugin () { return new Plugin({ key: uploadsKey, state: { init: () => ({ uploads: new Map(), moves: 0 }), apply (tr, value, before) { const meta = tr.getMeta(uploadsKey) const uploads = mapped(value.uploads, tr, before.doc) if (meta?.add) uploads.set(meta.add.id, meta.add) if (meta?.remove) uploads.delete(meta.remove) const moves = value.moves + (tr.selectionSet || tr.docChanged ? 1 : 0) return { uploads, moves } } }, props: { decorations (state) { const { uploads } = uploadsKey.getState(state) const shown = [...uploads.values()].filter(upload => !upload.dropped) return DecorationSet.create(state.doc, shown.map(upload => Decoration.widget(Math.min(upload.lost ? state.doc.content.size - 1 : upload.pos, state.doc.content.size), upload.dom.group, { key: upload.id, side: -1 }))) } } }) } let nextUpload = 0 // inFlight is how many uploads are running or waiting on the person. export function inFlight (state) { const value = uploadsKey.getState(state) return value ? [...value.uploads.values()].filter(upload => !upload.dropped).length : 0 } // uploadFiles uploads each file in order into its own place, starting // at pos, each after the one before it (Fable M6). hooks: answers // (ImageAnswers), say (the live region), alt (the alt field), notice (a // bar's sentence). export async function uploadFiles (view, files, pos, hooks) { for (const file of files) { const upload = start(view, file, pos) pos = (await run(view, upload, hooks)) ?? upload.pos } } // replaceImage is Replace…: the new file uploads in a box after the // image at pos, which stays until the new one is in; then the node takes // the new id and keeps its alt (Fable M4). A failed replace leaves the // old image as it was. export function replaceImage (view, pos, file, hooks, id = null) { const old = view.state.doc.nodeAt(pos) // The image chosen, by its id, or nothing (Fable N8): the document may // have moved while the picker was open. if (old?.type.name !== 'image' || (id !== null && old.attrs.id !== id)) { return Promise.resolve() } const upload = start(view, file, pos + 1, { pos, id: old.attrs.id, alt: old.attrs.alt }) return run(view, upload, hooks) } function start (view, file, pos, replacing = null) { const id = `upload-${++nextUpload}` const upload = { id, file, name: file.name || 'image', pos, replacing } upload.dom = box(upload) upload.dom.bar.value = 0 view.dispatch(view.state.tr.setMeta(uploadsKey, { add: upload }).setMeta('addToHistory', false)) upload.moves = uploadsKey.getState(view.state).moves return upload } function remove (view, upload) { view.dispatch(view.state.tr.setMeta(uploadsKey, { remove: upload.id }).setMeta('addToHistory', false)) } // run uploads one file and answers the place after its image, or // nothing when none went in. async function run (view, upload, hooks) { const early = refusal(upload.file) if (early) return failed(view, upload, early, hooks) const file = await prepared(upload.file) if (file.size > MAX_BYTES) return failed(view, upload, reasons.size, hooks) const reply = await send(file, share => { upload.dom.bar.value = share }) if (upload.dropped) return remove(view, upload) if (reply.status !== 200 || !reply.json?.id) { const why = reply.status === 0 ? reasons.offline : (reply.json?.refused ?? reasons.failed) return failed(view, upload, why, hooks) } return placed(view, upload, reply.json, hooks) } // swapped is Replace…'s success: the image it replaces takes the new // id, its alt kept; null when that image is gone. function swapped (view, upload, image) { const { pos, id, gone } = upload.replacing const node = view.state.doc.nodeAt(pos) if (gone || node?.type.name !== 'image' || node.attrs.id !== id) return null view.dispatch(view.state.tr.setMeta(uploadsKey, { remove: upload.id }) .setNodeMarkup(pos, null, { ...node.attrs, id: image.id, source: null })) return pos + 1 } // placed puts the image where its box was, or at the end of the page, // and answers the place after it. function placed (view, upload, image, hooks) { hooks.answers.set(image.id, { width: image.width, height: image.height }) if (upload.replacing) { const after = swapped(view, upload, image) if (after !== null) { hooks.say?.('Image replaced') return after } } const node = view.state.schema.nodes.image.create({ id: image.id, alt: upload.replacing?.alt ?? '' }) const still = uploadsKey.getState(view.state).moves === upload.moves let tr = view.state.tr.setMeta(uploadsKey, { remove: upload.id }) let at = upload.pos const inline = !upload.lost && tr.doc.resolve(at).parent.inlineContent && !tr.doc.resolve(at).parent.type.spec.code if (inline) { tr = tr.insert(at, node) } else { // A place between blocks, or one that was deleted: the image is a // paragraph of its own, there or at the end of the page. if (upload.lost) { at = tr.doc.content.size hooks.notice?.('Image added at the end of the page') } tr = tr.insert(at, view.state.schema.nodes.paragraph.create(null, node)) at += 1 } view.dispatch(tr) if (still && !upload.replacing) hooks.alt?.(view, at) else hooks.say?.(upload.replacing ? 'Image replaced' : 'Image added') return at + 1 } function failed (view, upload, why, hooks) { const { group, why: line, bar } = upload.dom bar.hidden = true line.hidden = false line.textContent = why group.setAttribute('aria-label', `Not uploaded: ${upload.name}`) group.setAttribute('mapa-upload', 'failed') hooks.say?.(`Not uploaded: ${why}`) const act = (label, fn) => { const button = document.createElement('button') button.type = 'button' button.setAttribute('rst-btn', '') button.textContent = label button.addEventListener('mousedown', event => event.preventDefault()) button.addEventListener('click', fn) group.append(button) return button } return new Promise(resolve => { // Undone away while it waits: the queue goes on (Fable L12). upload.onDrop = () => { remove(view, upload) resolve() } const retry = act('Retry', async () => { retry.remove() dismiss.remove() line.hidden = true bar.hidden = false group.setAttribute('mapa-upload', '') group.setAttribute('aria-label', `Uploading ${upload.name}`) upload.onDrop = null resolve(await run(view, upload, hooks)) }) const dismiss = act('Dismiss', () => { remove(view, upload) view.focus() resolve() }) }) } // imageFiles is the image files a paste or a drop carries. export function imageFiles (transfer) { return [...(transfer?.files ?? [])].filter(file => file.type.startsWith('image/') || /\.svg$/iu.test(file.name)) } // pastedFiles is the image files a paste uploads. A spreadsheet's // cells arrive as text, HTML and a picture of them, and the cells are // what was copied, so text wins (Fable M3). But a browser's Copy image // sends the picture with HTML that is one and nothing else (and // Firefox the address as text): there the picture wins (Fable N1). // With no HTML, text that is only the picture's own address (a web // address and nothing else) is Copy image's shape too; and text whose // every line is the name of one of the files is a file copied in // Finder (Chrome on macOS sends the name as text). export function pastedFiles (data) { const html = data?.getData?.('text/html') ?? '' const files = imageFiles(data) if (html) return loneImage(html) ? files : [] const text = (data?.getData?.('text/plain') ?? '').trim() if (!text || /^https?:\/\/[^\s]+$/u.test(text)) return files const names = new Set(files.map(file => file.name)) const lines = text.split(/\r?\n/u).map(line => line.trim()).filter(Boolean) return lines.every(line => names.has(line)) ? files : [] } // loneImage is HTML that holds one and no text: what a browser's // Copy image puts on the clipboard beside the picture. export function loneImage (html) { const bare = html .replace(//gu, '') .replace(/<\/?(?:html|head|body|meta)\b[^>]*>/giu, '') .trim() // An attribute may hold a > in quotes (Fable, round 5). return /^"'])*>$/iu.test(bare) } // choose opens the file picker (Insert → Image…, / → Image, the phone's // button) and uploads what is chosen at the caret. export function chooser (hooks) { return (state, dispatch, view) => { if (!view) return true const input = document.createElement('input') input.type = 'file' input.accept = acceptList input.multiple = true input.hidden = true input.setAttribute('mapa-image-input', '') input.addEventListener('change', () => { const files = [...input.files] input.remove() if (files.length) uploadFiles(view, files, view.state.selection.from, hooks) }) document.body.append(input) input.click() return true } } // dropping is paste and drop of image files: each uploads at the // caret, or where the drop cursor marked. export function droppingPlugin (hooks) { return new Plugin({ props: { handlePaste (view, event) { const files = pastedFiles(event.clipboardData) if (!files.length) return false event.preventDefault() uploadFiles(view, files, view.state.selection.from, hooks) return true }, handleDrop (view, event) { const files = imageFiles(event.dataTransfer) if (!files.length) return false event.preventDefault() const at = view.posAtCoords({ left: event.clientX, top: event.clientY }) const pos = at?.pos ?? view.state.selection.from view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(pos)))) uploadFiles(view, files, view.state.selection.from, hooks) return true } } }) }