| 1 | // imageview.mjs — an image in the editor (images spec §2.1, §4.5, §4.6). |
| 2 | // Its size and state come from ImageAnswers, never from the node: the |
| 3 | // island carries an answer for every image in the text the editor |
| 4 | // mounts over, so the NodeView draws exactly the server's markup and |
| 5 | // nothing moves (L5); an image typed or pasted later is asked of POST |
| 6 | // /links/resolve, and an upload's or a copy's reply gives its own. The |
| 7 | // class alone is a node decoration, recomputed for each changed block. |
| 8 | |
| 9 | import { Plugin, PluginKey } from 'prosemirror-state' |
| 10 | import { Decoration, DecorationSet } from 'prosemirror-view' |
| 11 | import { DOMSerializer } from 'prosemirror-model' |
| 12 | import { isAlone } from './imagedom.mjs' |
| 13 | import { isImageID } from './markup.mjs' |
| 14 | import { badge, showAlt, describe, closeFor, closeOn, closeOpen } from './altinset.mjs' |
| 15 | |
| 16 | const batch = 32 |
| 17 | |
| 18 | // ImageAnswers is each image id's state on this page for this viewer. |
| 19 | export class ImageAnswers { |
| 20 | // known is the island's images; ask(ids) answers /links/resolve's |
| 21 | // images for up to 32 ids. |
| 22 | constructor (known = {}, ask = null) { |
| 23 | this.known = new Map(Object.entries(known ?? {})) |
| 24 | this.ask = ask |
| 25 | this.asked = new Set() |
| 26 | this.waiting = new Set() |
| 27 | this.watchers = new Set() |
| 28 | this.timer = null |
| 29 | } |
| 30 | |
| 31 | // answer is an id's state now; an id never answered is asked for once |
| 32 | // and drawn as not available meanwhile. |
| 33 | answer (id) { |
| 34 | const known = this.known.get(id) |
| 35 | if (known) return known |
| 36 | if (this.ask && isImageID(id) && !this.asked.has(id)) { |
| 37 | this.waiting.add(id) |
| 38 | this.soon() |
| 39 | } |
| 40 | return { available: false } |
| 41 | } |
| 42 | |
| 43 | // set records an answer the editor already has (an upload, a copy). |
| 44 | set (id, answer) { |
| 45 | this.known.set(id, { available: true, ...answer }) |
| 46 | this.tell(new Set([id])) |
| 47 | } |
| 48 | |
| 49 | soon () { |
| 50 | if (this.timer !== null) return |
| 51 | this.timer = setTimeout(() => { |
| 52 | this.timer = null |
| 53 | this.flush() |
| 54 | }, 0) |
| 55 | } |
| 56 | |
| 57 | async flush () { |
| 58 | const ids = [...this.waiting].slice(0, batch) |
| 59 | if (ids.length === 0) return |
| 60 | for (const id of ids) { |
| 61 | this.waiting.delete(id) |
| 62 | this.asked.add(id) |
| 63 | } |
| 64 | if (this.waiting.size) this.soon() |
| 65 | let reply |
| 66 | try { |
| 67 | reply = await this.ask(ids) |
| 68 | } catch { |
| 69 | for (const id of ids) this.asked.delete(id) |
| 70 | return |
| 71 | } |
| 72 | const changed = new Set() |
| 73 | for (const [id, state] of Object.entries(reply ?? {})) { |
| 74 | this.known.set(id, state) |
| 75 | changed.add(id) |
| 76 | } |
| 77 | this.tell(changed) |
| 78 | } |
| 79 | |
| 80 | tell (changed) { |
| 81 | if (changed.size) for (const watcher of this.watchers) watcher(changed) |
| 82 | } |
| 83 | |
| 84 | watch (fn) { |
| 85 | this.watchers.add(fn) |
| 86 | return () => this.watchers.delete(fn) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // named is an image's accessible name (§4.6). |
| 91 | export function imageName (alt) { |
| 92 | return alt ? `Image: ${alt}` : 'Image with no description' |
| 93 | } |
| 94 | |
| 95 | function draw (node) { |
| 96 | const dom = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)).dom |
| 97 | dom.setAttribute('aria-label', dom.nodeName === 'IMG' |
| 98 | ? imageName(node.attrs.alt) : `${imageName(node.attrs.alt)}, not available`) |
| 99 | return dom |
| 100 | } |
| 101 | |
| 102 | // retryAfter is how long a failed image waits before it is loaded again, |
| 103 | // once (§1.4: a busy server answers 503). |
| 104 | const retryAfter = 2000 |
| 105 | |
| 106 | // views finds the view drawing a frame, for describeAt. |
| 107 | const views = new WeakMap() |
| 108 | |
| 109 | // ImageView draws an image in a frame: the server's markup inside a |
| 110 | // span that holds it exactly (the frame's box is the picture's, so the |
| 111 | // mount moves nothing, L5), with the ALT badge and the description |
| 112 | // field laid over it (altinset.mjs, build note I22). |
| 113 | export class ImageView { |
| 114 | constructor (node, answers, view, getPos, hooks = {}) { |
| 115 | Object.assign(this, { node, answers, view, getPos, hooks }) |
| 116 | this.dom = document.createElement('span') |
| 117 | this.dom.setAttribute('mapa-image-frame', '') |
| 118 | views.set(this.dom, this) |
| 119 | this.paint() |
| 120 | } |
| 121 | |
| 122 | // paint draws the image afresh: the <img> and its badge, or the box. |
| 123 | paint () { |
| 124 | this.dom.replaceChildren() |
| 125 | this.inner = draw(this.node) |
| 126 | this.drawn = drawnAs(this.answers.answer(this.node.attrs.id)) |
| 127 | this.retried = false |
| 128 | this.dom.append(this.inner) |
| 129 | this.badge = null |
| 130 | if (this.inner.nodeName !== 'IMG') return |
| 131 | this.badge = badge(this.node.attrs.alt, () => this.describe('badge')) |
| 132 | this.dom.append(this.badge) |
| 133 | this.listen() |
| 134 | } |
| 135 | |
| 136 | listen () { |
| 137 | const img = this.inner |
| 138 | img.addEventListener('error', () => { |
| 139 | if (this.retried) return |
| 140 | this.retried = true |
| 141 | setTimeout(() => { |
| 142 | const src = img.getAttribute('src') |
| 143 | img.setAttribute('src', `${src}?again=1`) |
| 144 | }, retryAfter) |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | describe (from) { |
| 149 | if (!this.view || !this.getPos) return null |
| 150 | // The badge pressed again closes its own field (Fable L8). |
| 151 | if (from === 'badge' && closeOn(this.dom)) return null |
| 152 | // Keeping a field open elsewhere may draw this block again: then |
| 153 | // the image's new view opens it. |
| 154 | const pos = this.getPos() |
| 155 | closeOpen() |
| 156 | if (!this.dom.isConnected) { |
| 157 | const fresh = views.get(this.view.nodeDOM(pos)) |
| 158 | return fresh && fresh !== this && fresh.node.attrs.id === this.node.attrs.id |
| 159 | ? fresh.describe(from) : null |
| 160 | } |
| 161 | const { say, save } = this.hooks |
| 162 | return describe(this.view, this.dom, this.getPos, { from, say, save, closed: () => this.closed() }) |
| 163 | } |
| 164 | |
| 165 | // closed draws the picture again if an answer came while the field |
| 166 | // was open (Fable L7). |
| 167 | closed () { |
| 168 | if (!this.pending) return |
| 169 | this.pending = false |
| 170 | this.paint() |
| 171 | } |
| 172 | |
| 173 | // update keeps this frame for the same image. A new kind of answer |
| 174 | // draws the picture again inside it; a new alt changes its names. |
| 175 | update (node) { |
| 176 | if (node.type !== this.node.type || node.attrs.id !== this.node.attrs.id) return false |
| 177 | const alt = node.attrs.alt !== this.node.attrs.alt |
| 178 | this.node = node |
| 179 | if (drawnAs(this.answers.answer(node.attrs.id)) !== this.drawn) { |
| 180 | if (this.dom.hasAttribute('mapa-alt-open')) this.pending = true |
| 181 | else this.paint() |
| 182 | return true |
| 183 | } |
| 184 | if (alt) { |
| 185 | const fresh = draw(node) |
| 186 | for (const name of ['alt', 'aria-label']) { |
| 187 | if (fresh.hasAttribute(name)) this.inner.setAttribute(name, fresh.getAttribute(name)) |
| 188 | } |
| 189 | if (this.badge) showAlt(this.badge, node.attrs.alt) |
| 190 | } |
| 191 | return true |
| 192 | } |
| 193 | |
| 194 | selectNode () { this.dom.setAttribute('mapa-image-selected', '') } |
| 195 | deselectNode () { this.dom.removeAttribute('mapa-image-selected') } |
| 196 | // The badge and the field are the page's own controls, not the text. |
| 197 | stopEvent (event) { |
| 198 | return Boolean(event.target?.closest?.('[mapa-alt-badge], [mapa-alt]')) |
| 199 | } |
| 200 | |
| 201 | ignoreMutation () { return true } |
| 202 | destroy () { closeFor(this.dom) } |
| 203 | } |
| 204 | |
| 205 | // describeAt opens the description field on the image at pos: the |
| 206 | // bubble's Alt text, and a finished upload. |
| 207 | export function describeAt (view, pos, from) { |
| 208 | const frame = view.nodeDOM(pos) |
| 209 | return frame ? views.get(frame)?.describe(from) ?? null : null |
| 210 | } |
| 211 | |
| 212 | export function imageViews (answers, hooks = {}) { |
| 213 | return { image: (node, view, getPos) => new ImageView(node, answers, view, getPos, hooks) } |
| 214 | } |
| 215 | |
| 216 | // drawnAs is how an answer draws: an <img>, or the fixed box. |
| 217 | const drawnAs = answer => answer?.available ? 'image' : 'box' |
| 218 | |
| 219 | // The images' decorations: the class alone on a textblock's only image, |
| 220 | // as the server draws it (§2.1), recomputed for each changed block; and |
| 221 | // data-mapa-drawn, the answer it is drawn from, so that when an answer |
| 222 | // arrives the decoration changes and the view draws the image again. |
| 223 | export const imagesKey = new PluginKey('mapa-images') |
| 224 | |
| 225 | function decorate (doc, from, to, answers, out) { |
| 226 | doc.nodesBetween(from, to, (node, pos) => { |
| 227 | if (!node.isTextblock) return true |
| 228 | const alone = isAlone(node) |
| 229 | node.forEach((child, offset) => { |
| 230 | if (child.type.name !== 'image') return |
| 231 | const attrs = { 'data-mapa-drawn': drawnAs(answers.answer(child.attrs.id)) } |
| 232 | if (alone) attrs.class = 'alone' |
| 233 | const at = pos + 1 + offset |
| 234 | out.push(Decoration.node(at, at + 1, attrs)) |
| 235 | }) |
| 236 | return false |
| 237 | }) |
| 238 | return out |
| 239 | } |
| 240 | |
| 241 | // changedBlocks is each top-level range a transaction touched. |
| 242 | function changedBlocks (tr, each) { |
| 243 | tr.mapping.maps.forEach((map, index) => { |
| 244 | map.forEach((oldStart, oldEnd, newStart, newEnd) => { |
| 245 | const rest = tr.mapping.slice(index + 1) |
| 246 | const from = Math.max(0, rest.map(newStart, -1) - 1) |
| 247 | const to = Math.min(tr.doc.content.size, rest.map(newEnd, 1) + 1) |
| 248 | const $from = tr.doc.resolve(from) |
| 249 | const $to = tr.doc.resolve(to) |
| 250 | each($from.depth ? $from.before(1) : from, $to.depth ? $to.after(1) : to) |
| 251 | }) |
| 252 | }) |
| 253 | } |
| 254 | |
| 255 | export function imagesPlugin (answers) { |
| 256 | const whole = doc => DecorationSet.create(doc, decorate(doc, 0, doc.content.size, answers, [])) |
| 257 | return new Plugin({ |
| 258 | key: imagesKey, |
| 259 | state: { |
| 260 | init: (config, state) => whole(state.doc), |
| 261 | apply (tr, set) { |
| 262 | if (tr.getMeta(imagesKey)) return whole(tr.doc) |
| 263 | if (!tr.docChanged) return set |
| 264 | let next = set.map(tr.mapping, tr.doc) |
| 265 | changedBlocks(tr, (start, end) => { |
| 266 | next = next.remove(next.find(start, end)) |
| 267 | next = next.add(tr.doc, decorate(tr.doc, start, end, answers, [])) |
| 268 | }) |
| 269 | return next |
| 270 | } |
| 271 | }, |
| 272 | view (view) { |
| 273 | const unwatch = answers.watch(() => view.dispatch(view.state.tr.setMeta(imagesKey, true))) |
| 274 | return { destroy: unwatch } |
| 275 | }, |
| 276 | props: { decorations: state => imagesKey.getState(state) } |
| 277 | }) |
| 278 | } |
| 279 | |