// altinset.mjs — an image's description, asked for on the image itself // (images spec §4.3, build note I22). An "ALT" badge sits in the // image's bottom-left corner: filled when the image has a description, // outlined and always shown when it has none. The badge, the bubble's // Alt text and a finished upload open the description field laid over // the image's bottom edge, inside its box, so nothing below the image // moves (L5) and the picture stays in view. An image too small to hold // it gets the field in a small popover under the badge instead, laid // over the text below, which does not move either. Enter, Tab or // leaving the field keeps the text; Esc puts back what was there; ⌘S // keeps it and saves the page. The description is the atom's alt, // saved in one transaction as before. import { NodeSelection, TextSelection } from 'prosemirror-state' import { cleanAlt } from './schema.mjs' import { MaxAlt } from './markup.mjs' export const altLabel = 'Describe this image for people who can\'t see it' // Below these, the image cannot hold the field: it goes under it. export const insetWidth = 240 export const insetHeight = 120 // firstWords is the start of a description, for the badge's name. export function firstWords (alt, words = 5, most = 40) { const all = alt.trim().split(/\s+/u) let out = all.slice(0, words).join(' ') if (out.length > most) out = out.slice(0, most).trimEnd() return out.length < alt.trim().length ? `${out}…` : out } // badgeName is the badge's accessible name. It starts with the badge's // visible word, so "click Alt text" reaches it by voice (WCAG 2.5.3). export function badgeName (alt) { return alt ? `Alt text: ${firstWords(alt)}, edit` : 'Alt text: describe this image' } // fieldAlt is what the field keeps: one line, no [ or ], at most // MaxAlt bytes, cut at a character, and no space at either end. export function fieldAlt (value) { return cleanAlt(value.replace(/\s*[\r\n]+\s*/gu, ' ')).trim() } // fitBytes is value cut, at a character, to MaxAlt bytes of UTF-8: the // field holds no more than the page will keep. export function fitBytes (value) { let bytes = 0 let out = '' for (const char of value) { const code = char.codePointAt(0) bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4 if (bytes > MaxAlt) return out out += char } return value } // badge is the ALT button; open is what a click on it does. export function badge (alt, open) { const button = document.createElement('button') button.type = 'button' button.draggable = false button.setAttribute('mapa-alt-badge', '') button.textContent = 'ALT' showAlt(button, alt) button.addEventListener('mousedown', event => event.preventDefault()) button.addEventListener('click', event => { event.preventDefault() open() }) return button } // showAlt draws the badge for a description, or for none. A missing // description is a tab stop, so the keyboard finds what is missing; a // described image's badge is reached from the bubble's Alt text. export function showAlt (button, alt) { button.setAttribute('mapa-alt-badge', alt ? 'set' : 'missing') button.setAttribute('aria-label', badgeName(alt)) button.tabIndex = alt ? -1 : 0 } let open = null let fields = 0 // closeOpen keeps whatever field is open, as leaving it would: before // the page is left or saved, so what was typed goes with it. export function closeOpen () { open?.finish(true, false) } // closeOn closes the field open on frame, keeping its text, and gives // focus back; false when none is open there. export function closeOn (frame) { if (open?.frame !== frame) return false open.finish(true, true) return true } // closeFor keeps the field open on a frame the editor is taking away // (a rebase wrote its block again), once the editor's update is over: // the text goes to the image by its id, wherever it is now, and focus // goes back as if Enter had been pressed, unless it went elsewhere. export function closeFor (frame) { const field = open if (field?.frame !== frame) return queueMicrotask(() => { const lost = !document.activeElement || document.activeElement === document.body field.finish(true, lost) }) } // describe opens the field on frame, the image's NodeView, for the // image at getPos(). from says where focus goes back to: 'badge' (the // badge), 'bubble' (the image, selected) or 'upload' (the text after // the image). hooks: say (the live region), save (the page's ⌘S) and // closed (called as the field goes, before anything is written). export function describe (view, frame, getPos, { from = 'bubble', ...hooks } = {}) { closeOpen() const node = view.state.doc.nodeAt(getPos()) if (node?.type.name !== 'image') return null const field = new Field(view, frame, getPos, from, hooks) field.show(node.attrs.alt ?? '') return field } class Field { constructor (view, frame, getPos, from, hooks) { Object.assign(this, { view, frame, getPos, from, hooks, closed: false }) this.id = node => node?.type.name === 'image' ? node.attrs.id : null this.image = this.id(view.state.doc.nodeAt(getPos())) } show (alt) { const box = this.frame.getBoundingClientRect() this.inset = box.width >= insetWidth && box.height >= insetHeight const wrap = document.createElement('div') wrap.setAttribute('mapa-alt', this.inset ? 'inset' : 'popover') wrap.draggable = false const id = `mapa-alt-${++fields}` const label = document.createElement('label') label.htmlFor = id label.textContent = altLabel const text = document.createElement('textarea') Object.assign(text, { id, rows: 1, value: alt }) text.setAttribute('autocomplete', 'off') text.setAttribute('enterkeyhint', 'done') wrap.append(label, text) Object.assign(this, { wrap, text, before: alt }) this.listen() this.frame.append(wrap) this.parent = this.frame.parentNode this.frame.setAttribute('mapa-alt-open', '') this.draggable = this.frame.draggable this.frame.draggable = false open = this if (!this.inset) keepInView(wrap) this.grow() text.focus({ preventScroll: true }) text.setSelectionRange(text.value.length, text.value.length) wrap.scrollIntoView?.({ block: 'nearest' }) } listen () { const { text, wrap } = this text.addEventListener('keydown', event => this.key(event)) // A press on the label or the band is not leaving: the field keeps // its focus (Fable M1). wrap.addEventListener('mousedown', event => { if (event.target === text) return event.preventDefault() text.focus({ preventScroll: true }) }) // Alt is one line: a pasted line break is a space. And the field // holds no more than the page keeps (Fable L10). text.addEventListener('input', () => { const fitted = fitBytes(text.value.replace(/[ \t]*\r?\n[ \t]*/gu, ' ')) if (fitted !== text.value) { const at = Math.min(text.selectionStart, fitted.length) text.value = fitted text.setSelectionRange(at, at) } this.grow() }) // Leaving keeps the text. Another window taking focus is not // leaving: the field is still there on the way back, unless focus // came back somewhere else (Fable L3). text.addEventListener('blur', () => { if (!document.hasFocus()) return setTimeout(() => { // The editor moved the image into a block drawn again (Fable // L6): the field went with it, and keeps its focus. if (this.frame.isConnected && this.frame.parentNode !== this.parent && document.activeElement === document.body) { this.parent = this.frame.parentNode text.focus({ preventScroll: true }) return } this.finish(true, false) }, 0) }) this.returned = () => setTimeout(() => { if (document.activeElement !== text) this.finish(true, false) }, 0) window.addEventListener('focus', this.returned) } key (event) { if (event.isComposing || event.keyCode === 229) return if (event.key === 'Enter' || event.key === 'Tab') { event.preventDefault() this.finish(true, true) } else if (event.key === 'Escape') { event.preventDefault() event.stopPropagation() this.finish(false, true) } else if (event.key.toLowerCase() === 's' && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey) { // ⌘S keeps the text and saves the page, as it does in the text. event.preventDefault() this.finish(true, true) this.hooks.save?.() } } // grow fits the field to its text, up to four lines, and, over the // image, to the room the image has (Fable L1). grow () { const { text } = this text.style.removeProperty('height') let height = text.scrollHeight + 2 if (this.inset) { const band = this.wrap.offsetHeight - text.offsetHeight height = Math.min(height, Math.max(36, this.frame.clientHeight - band)) } text.style.setProperty('height', `${height}px`) } // finish closes the field, keeping its text or not, and, if refocus, // gives focus back where it came from. finish (keep, refocus) { if (this.closed) return this.closed = true if (open === this) open = null window.removeEventListener('focus', this.returned) this.wrap.remove() this.frame.removeAttribute('mapa-alt-open') this.frame.draggable = this.draggable this.hooks.closed?.() const pos = this.place() const alt = fieldAlt(this.text.value) const saved = keep && pos !== null && alt !== this.before if (saved) this.view.dispatch(this.view.state.tr.setNodeAttribute(pos, 'alt', alt)) // The save may have drawn the block again (the settle plugin's // reparse), so the image is found afresh. if (refocus) this.refocus(saved ? this.place(pos) : pos) if (saved && !(refocus && this.from === 'badge')) { this.hooks.say?.(alt ? `Image: ${alt}` : 'Image with no description') } } // place is where the image is now, or null when it has gone: at the // place it was (hint), at its view's, or wherever its id is. place (hint = null) { const { doc } = this.view.state const here = at => typeof at === 'number' && at >= 0 && at < doc.content.size && this.id(doc.nodeAt(at)) === this.image if (here(hint)) return hint let pos = null try { pos = this.getPos() } catch { pos = null } if (here(pos)) return pos pos = null doc.descendants((node, at) => { if (pos === null && this.id(node) === this.image) pos = at return pos === null }) return pos } refocus (pos) { const { view } = this const frame = pos === null ? null : view.nodeDOM(pos) const button = frame?.querySelector?.('[mapa-alt-badge]') if (this.from === 'badge' && button?.isConnected) { button.focus() return } if (pos !== null) { const selection = this.from === 'upload' ? TextSelection.near(view.state.doc.resolve(pos + 1)) : NodeSelection.create(view.state.doc, pos) view.dispatch(view.state.tr.setSelection(selection)) } view.focus() } } // keepInView moves a popover sideways onto the screen. function keepInView (wrap) { const box = wrap.getBoundingClientRect() const room = document.documentElement.clientWidth - 8 const shift = box.right > room ? room - box.right : (box.left < 8 ? 8 - box.left : 0) if (shift) wrap.style.setProperty('inset-inline-start', `${shift}px`) }