// imageview.mjs — an image in the editor (images spec §2.1, §4.5, §4.6).
// Its size and state come from ImageAnswers, never from the node: the
// island carries an answer for every image in the text the editor
// mounts over, so the NodeView draws exactly the server's markup and
// nothing moves (L5); an image typed or pasted later is asked of POST
// /links/resolve, and an upload's or a copy's reply gives its own. The
// class alone is a node decoration, recomputed for each changed block.
import { Plugin, PluginKey } from 'prosemirror-state'
import { Decoration, DecorationSet } from 'prosemirror-view'
import { DOMSerializer } from 'prosemirror-model'
import { isAlone } from './imagedom.mjs'
import { isImageID } from './markup.mjs'
import { badge, showAlt, describe, closeFor, closeOn, closeOpen } from './altinset.mjs'
const batch = 32
// ImageAnswers is each image id's state on this page for this viewer.
export class ImageAnswers {
// known is the island's images; ask(ids) answers /links/resolve's
// images for up to 32 ids.
constructor (known = {}, ask = null) {
this.known = new Map(Object.entries(known ?? {}))
this.ask = ask
this.asked = new Set()
this.waiting = new Set()
this.watchers = new Set()
this.timer = null
}
// answer is an id's state now; an id never answered is asked for once
// and drawn as not available meanwhile.
answer (id) {
const known = this.known.get(id)
if (known) return known
if (this.ask && isImageID(id) && !this.asked.has(id)) {
this.waiting.add(id)
this.soon()
}
return { available: false }
}
// set records an answer the editor already has (an upload, a copy).
set (id, answer) {
this.known.set(id, { available: true, ...answer })
this.tell(new Set([id]))
}
soon () {
if (this.timer !== null) return
this.timer = setTimeout(() => {
this.timer = null
this.flush()
}, 0)
}
async flush () {
const ids = [...this.waiting].slice(0, batch)
if (ids.length === 0) return
for (const id of ids) {
this.waiting.delete(id)
this.asked.add(id)
}
if (this.waiting.size) this.soon()
let reply
try {
reply = await this.ask(ids)
} catch {
for (const id of ids) this.asked.delete(id)
return
}
const changed = new Set()
for (const [id, state] of Object.entries(reply ?? {})) {
this.known.set(id, state)
changed.add(id)
}
this.tell(changed)
}
tell (changed) {
if (changed.size) for (const watcher of this.watchers) watcher(changed)
}
watch (fn) {
this.watchers.add(fn)
return () => this.watchers.delete(fn)
}
}
// named is an image's accessible name (§4.6).
export function imageName (alt) {
return alt ? `Image: ${alt}` : 'Image with no description'
}
function draw (node) {
const dom = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)).dom
dom.setAttribute('aria-label', dom.nodeName === 'IMG'
? imageName(node.attrs.alt) : `${imageName(node.attrs.alt)}, not available`)
return dom
}
// retryAfter is how long a failed image waits before it is loaded again,
// once (§1.4: a busy server answers 503).
const retryAfter = 2000
// views finds the view drawing a frame, for describeAt.
const views = new WeakMap()
// ImageView draws an image in a frame: the server's markup inside a
// span that holds it exactly (the frame's box is the picture's, so the
// mount moves nothing, L5), with the ALT badge and the description
// field laid over it (altinset.mjs, build note I22).
export class ImageView {
constructor (node, answers, view, getPos, hooks = {}) {
Object.assign(this, { node, answers, view, getPos, hooks })
this.dom = document.createElement('span')
this.dom.setAttribute('mapa-image-frame', '')
views.set(this.dom, this)
this.paint()
}
// paint draws the image afresh: the
and its badge, or the box.
paint () {
this.dom.replaceChildren()
this.inner = draw(this.node)
this.drawn = drawnAs(this.answers.answer(this.node.attrs.id))
this.retried = false
this.dom.append(this.inner)
this.badge = null
if (this.inner.nodeName !== 'IMG') return
this.badge = badge(this.node.attrs.alt, () => this.describe('badge'))
this.dom.append(this.badge)
this.listen()
}
listen () {
const img = this.inner
img.addEventListener('error', () => {
if (this.retried) return
this.retried = true
setTimeout(() => {
const src = img.getAttribute('src')
img.setAttribute('src', `${src}?again=1`)
}, retryAfter)
})
}
describe (from) {
if (!this.view || !this.getPos) return null
// The badge pressed again closes its own field (Fable L8).
if (from === 'badge' && closeOn(this.dom)) return null
// Keeping a field open elsewhere may draw this block again: then
// the image's new view opens it.
const pos = this.getPos()
closeOpen()
if (!this.dom.isConnected) {
const fresh = views.get(this.view.nodeDOM(pos))
return fresh && fresh !== this && fresh.node.attrs.id === this.node.attrs.id
? fresh.describe(from) : null
}
const { say, save } = this.hooks
return describe(this.view, this.dom, this.getPos, { from, say, save, closed: () => this.closed() })
}
// closed draws the picture again if an answer came while the field
// was open (Fable L7).
closed () {
if (!this.pending) return
this.pending = false
this.paint()
}
// update keeps this frame for the same image. A new kind of answer
// draws the picture again inside it; a new alt changes its names.
update (node) {
if (node.type !== this.node.type || node.attrs.id !== this.node.attrs.id) return false
const alt = node.attrs.alt !== this.node.attrs.alt
this.node = node
if (drawnAs(this.answers.answer(node.attrs.id)) !== this.drawn) {
if (this.dom.hasAttribute('mapa-alt-open')) this.pending = true
else this.paint()
return true
}
if (alt) {
const fresh = draw(node)
for (const name of ['alt', 'aria-label']) {
if (fresh.hasAttribute(name)) this.inner.setAttribute(name, fresh.getAttribute(name))
}
if (this.badge) showAlt(this.badge, node.attrs.alt)
}
return true
}
selectNode () { this.dom.setAttribute('mapa-image-selected', '') }
deselectNode () { this.dom.removeAttribute('mapa-image-selected') }
// The badge and the field are the page's own controls, not the text.
stopEvent (event) {
return Boolean(event.target?.closest?.('[mapa-alt-badge], [mapa-alt]'))
}
ignoreMutation () { return true }
destroy () { closeFor(this.dom) }
}
// describeAt opens the description field on the image at pos: the
// bubble's Alt text, and a finished upload.
export function describeAt (view, pos, from) {
const frame = view.nodeDOM(pos)
return frame ? views.get(frame)?.describe(from) ?? null : null
}
export function imageViews (answers, hooks = {}) {
return { image: (node, view, getPos) => new ImageView(node, answers, view, getPos, hooks) }
}
// drawnAs is how an answer draws: an
, or the fixed box.
const drawnAs = answer => answer?.available ? 'image' : 'box'
// The images' decorations: the class alone on a textblock's only image,
// as the server draws it (§2.1), recomputed for each changed block; and
// data-mapa-drawn, the answer it is drawn from, so that when an answer
// arrives the decoration changes and the view draws the image again.
export const imagesKey = new PluginKey('mapa-images')
function decorate (doc, from, to, answers, out) {
doc.nodesBetween(from, to, (node, pos) => {
if (!node.isTextblock) return true
const alone = isAlone(node)
node.forEach((child, offset) => {
if (child.type.name !== 'image') return
const attrs = { 'data-mapa-drawn': drawnAs(answers.answer(child.attrs.id)) }
if (alone) attrs.class = 'alone'
const at = pos + 1 + offset
out.push(Decoration.node(at, at + 1, attrs))
})
return false
})
return out
}
// changedBlocks is each top-level range a transaction touched.
function changedBlocks (tr, each) {
tr.mapping.maps.forEach((map, index) => {
map.forEach((oldStart, oldEnd, newStart, newEnd) => {
const rest = tr.mapping.slice(index + 1)
const from = Math.max(0, rest.map(newStart, -1) - 1)
const to = Math.min(tr.doc.content.size, rest.map(newEnd, 1) + 1)
const $from = tr.doc.resolve(from)
const $to = tr.doc.resolve(to)
each($from.depth ? $from.before(1) : from, $to.depth ? $to.after(1) : to)
})
})
}
export function imagesPlugin (answers) {
const whole = doc => DecorationSet.create(doc, decorate(doc, 0, doc.content.size, answers, []))
return new Plugin({
key: imagesKey,
state: {
init: (config, state) => whole(state.doc),
apply (tr, set) {
if (tr.getMeta(imagesKey)) return whole(tr.doc)
if (!tr.docChanged) return set
let next = set.map(tr.mapping, tr.doc)
changedBlocks(tr, (start, end) => {
next = next.remove(next.find(start, end))
next = next.add(tr.doc, decorate(tr.doc, start, end, answers, []))
})
return next
}
},
view (view) {
const unwatch = answers.watch(() => view.dispatch(view.state.tr.setMeta(imagesKey, true)))
return { destroy: unwatch }
},
props: { decorations: state => imagesKey.getState(state) }
})
}