| 1 | // altinset.mjs — an image's description, asked for on the image itself |
| 2 | // (images spec §4.3, build note I22). An "ALT" badge sits in the |
| 3 | // image's bottom-left corner: filled when the image has a description, |
| 4 | // outlined and always shown when it has none. The badge, the bubble's |
| 5 | // Alt text and a finished upload open the description field laid over |
| 6 | // the image's bottom edge, inside its box, so nothing below the image |
| 7 | // moves (L5) and the picture stays in view. An image too small to hold |
| 8 | // it gets the field in a small popover under the badge instead, laid |
| 9 | // over the text below, which does not move either. Enter, Tab or |
| 10 | // leaving the field keeps the text; Esc puts back what was there; ⌘S |
| 11 | // keeps it and saves the page. The description is the atom's alt, |
| 12 | // saved in one transaction as before. |
| 13 | |
| 14 | import { NodeSelection, TextSelection } from 'prosemirror-state' |
| 15 | import { cleanAlt } from './schema.mjs' |
| 16 | import { MaxAlt } from './markup.mjs' |
| 17 | |
| 18 | export const altLabel = 'Describe this image for people who can\'t see it' |
| 19 | |
| 20 | // Below these, the image cannot hold the field: it goes under it. |
| 21 | export const insetWidth = 240 |
| 22 | export const insetHeight = 120 |
| 23 | |
| 24 | // firstWords is the start of a description, for the badge's name. |
| 25 | export function firstWords (alt, words = 5, most = 40) { |
| 26 | const all = alt.trim().split(/\s+/u) |
| 27 | let out = all.slice(0, words).join(' ') |
| 28 | if (out.length > most) out = out.slice(0, most).trimEnd() |
| 29 | return out.length < alt.trim().length ? `${out}…` : out |
| 30 | } |
| 31 | |
| 32 | // badgeName is the badge's accessible name. It starts with the badge's |
| 33 | // visible word, so "click Alt text" reaches it by voice (WCAG 2.5.3). |
| 34 | export function badgeName (alt) { |
| 35 | return alt ? `Alt text: ${firstWords(alt)}, edit` : 'Alt text: describe this image' |
| 36 | } |
| 37 | |
| 38 | // fieldAlt is what the field keeps: one line, no [ or ], at most |
| 39 | // MaxAlt bytes, cut at a character, and no space at either end. |
| 40 | export function fieldAlt (value) { |
| 41 | return cleanAlt(value.replace(/\s*[\r\n]+\s*/gu, ' ')).trim() |
| 42 | } |
| 43 | |
| 44 | // fitBytes is value cut, at a character, to MaxAlt bytes of UTF-8: the |
| 45 | // field holds no more than the page will keep. |
| 46 | export function fitBytes (value) { |
| 47 | let bytes = 0 |
| 48 | let out = '' |
| 49 | for (const char of value) { |
| 50 | const code = char.codePointAt(0) |
| 51 | bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4 |
| 52 | if (bytes > MaxAlt) return out |
| 53 | out += char |
| 54 | } |
| 55 | return value |
| 56 | } |
| 57 | |
| 58 | // badge is the ALT button; open is what a click on it does. |
| 59 | export function badge (alt, open) { |
| 60 | const button = document.createElement('button') |
| 61 | button.type = 'button' |
| 62 | button.draggable = false |
| 63 | button.setAttribute('mapa-alt-badge', '') |
| 64 | button.textContent = 'ALT' |
| 65 | showAlt(button, alt) |
| 66 | button.addEventListener('mousedown', event => event.preventDefault()) |
| 67 | button.addEventListener('click', event => { |
| 68 | event.preventDefault() |
| 69 | open() |
| 70 | }) |
| 71 | return button |
| 72 | } |
| 73 | |
| 74 | // showAlt draws the badge for a description, or for none. A missing |
| 75 | // description is a tab stop, so the keyboard finds what is missing; a |
| 76 | // described image's badge is reached from the bubble's Alt text. |
| 77 | export function showAlt (button, alt) { |
| 78 | button.setAttribute('mapa-alt-badge', alt ? 'set' : 'missing') |
| 79 | button.setAttribute('aria-label', badgeName(alt)) |
| 80 | button.tabIndex = alt ? -1 : 0 |
| 81 | } |
| 82 | |
| 83 | let open = null |
| 84 | let fields = 0 |
| 85 | |
| 86 | // closeOpen keeps whatever field is open, as leaving it would: before |
| 87 | // the page is left or saved, so what was typed goes with it. |
| 88 | export function closeOpen () { |
| 89 | open?.finish(true, false) |
| 90 | } |
| 91 | |
| 92 | // closeOn closes the field open on frame, keeping its text, and gives |
| 93 | // focus back; false when none is open there. |
| 94 | export function closeOn (frame) { |
| 95 | if (open?.frame !== frame) return false |
| 96 | open.finish(true, true) |
| 97 | return true |
| 98 | } |
| 99 | |
| 100 | // closeFor keeps the field open on a frame the editor is taking away |
| 101 | // (a rebase wrote its block again), once the editor's update is over: |
| 102 | // the text goes to the image by its id, wherever it is now, and focus |
| 103 | // goes back as if Enter had been pressed, unless it went elsewhere. |
| 104 | export function closeFor (frame) { |
| 105 | const field = open |
| 106 | if (field?.frame !== frame) return |
| 107 | queueMicrotask(() => { |
| 108 | const lost = !document.activeElement || document.activeElement === document.body |
| 109 | field.finish(true, lost) |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | // describe opens the field on frame, the image's NodeView, for the |
| 114 | // image at getPos(). from says where focus goes back to: 'badge' (the |
| 115 | // badge), 'bubble' (the image, selected) or 'upload' (the text after |
| 116 | // the image). hooks: say (the live region), save (the page's ⌘S) and |
| 117 | // closed (called as the field goes, before anything is written). |
| 118 | export function describe (view, frame, getPos, { from = 'bubble', ...hooks } = {}) { |
| 119 | closeOpen() |
| 120 | const node = view.state.doc.nodeAt(getPos()) |
| 121 | if (node?.type.name !== 'image') return null |
| 122 | const field = new Field(view, frame, getPos, from, hooks) |
| 123 | field.show(node.attrs.alt ?? '') |
| 124 | return field |
| 125 | } |
| 126 | |
| 127 | class Field { |
| 128 | constructor (view, frame, getPos, from, hooks) { |
| 129 | Object.assign(this, { view, frame, getPos, from, hooks, closed: false }) |
| 130 | this.id = node => node?.type.name === 'image' ? node.attrs.id : null |
| 131 | this.image = this.id(view.state.doc.nodeAt(getPos())) |
| 132 | } |
| 133 | |
| 134 | show (alt) { |
| 135 | const box = this.frame.getBoundingClientRect() |
| 136 | this.inset = box.width >= insetWidth && box.height >= insetHeight |
| 137 | const wrap = document.createElement('div') |
| 138 | wrap.setAttribute('mapa-alt', this.inset ? 'inset' : 'popover') |
| 139 | wrap.draggable = false |
| 140 | const id = `mapa-alt-${++fields}` |
| 141 | const label = document.createElement('label') |
| 142 | label.htmlFor = id |
| 143 | label.textContent = altLabel |
| 144 | const text = document.createElement('textarea') |
| 145 | Object.assign(text, { id, rows: 1, value: alt }) |
| 146 | text.setAttribute('autocomplete', 'off') |
| 147 | text.setAttribute('enterkeyhint', 'done') |
| 148 | wrap.append(label, text) |
| 149 | Object.assign(this, { wrap, text, before: alt }) |
| 150 | this.listen() |
| 151 | this.frame.append(wrap) |
| 152 | this.parent = this.frame.parentNode |
| 153 | this.frame.setAttribute('mapa-alt-open', '') |
| 154 | this.draggable = this.frame.draggable |
| 155 | this.frame.draggable = false |
| 156 | open = this |
| 157 | if (!this.inset) keepInView(wrap) |
| 158 | this.grow() |
| 159 | text.focus({ preventScroll: true }) |
| 160 | text.setSelectionRange(text.value.length, text.value.length) |
| 161 | wrap.scrollIntoView?.({ block: 'nearest' }) |
| 162 | } |
| 163 | |
| 164 | listen () { |
| 165 | const { text, wrap } = this |
| 166 | text.addEventListener('keydown', event => this.key(event)) |
| 167 | // A press on the label or the band is not leaving: the field keeps |
| 168 | // its focus (Fable M1). |
| 169 | wrap.addEventListener('mousedown', event => { |
| 170 | if (event.target === text) return |
| 171 | event.preventDefault() |
| 172 | text.focus({ preventScroll: true }) |
| 173 | }) |
| 174 | // Alt is one line: a pasted line break is a space. And the field |
| 175 | // holds no more than the page keeps (Fable L10). |
| 176 | text.addEventListener('input', () => { |
| 177 | const fitted = fitBytes(text.value.replace(/[ \t]*\r?\n[ \t]*/gu, ' ')) |
| 178 | if (fitted !== text.value) { |
| 179 | const at = Math.min(text.selectionStart, fitted.length) |
| 180 | text.value = fitted |
| 181 | text.setSelectionRange(at, at) |
| 182 | } |
| 183 | this.grow() |
| 184 | }) |
| 185 | // Leaving keeps the text. Another window taking focus is not |
| 186 | // leaving: the field is still there on the way back, unless focus |
| 187 | // came back somewhere else (Fable L3). |
| 188 | text.addEventListener('blur', () => { |
| 189 | if (!document.hasFocus()) return |
| 190 | setTimeout(() => { |
| 191 | // The editor moved the image into a block drawn again (Fable |
| 192 | // L6): the field went with it, and keeps its focus. |
| 193 | if (this.frame.isConnected && this.frame.parentNode !== this.parent && |
| 194 | document.activeElement === document.body) { |
| 195 | this.parent = this.frame.parentNode |
| 196 | text.focus({ preventScroll: true }) |
| 197 | return |
| 198 | } |
| 199 | this.finish(true, false) |
| 200 | }, 0) |
| 201 | }) |
| 202 | this.returned = () => setTimeout(() => { |
| 203 | if (document.activeElement !== text) this.finish(true, false) |
| 204 | }, 0) |
| 205 | window.addEventListener('focus', this.returned) |
| 206 | } |
| 207 | |
| 208 | key (event) { |
| 209 | if (event.isComposing || event.keyCode === 229) return |
| 210 | if (event.key === 'Enter' || event.key === 'Tab') { |
| 211 | event.preventDefault() |
| 212 | this.finish(true, true) |
| 213 | } else if (event.key === 'Escape') { |
| 214 | event.preventDefault() |
| 215 | event.stopPropagation() |
| 216 | this.finish(false, true) |
| 217 | } else if (event.key.toLowerCase() === 's' && (event.metaKey || event.ctrlKey) && |
| 218 | !event.altKey && !event.shiftKey) { |
| 219 | // ⌘S keeps the text and saves the page, as it does in the text. |
| 220 | event.preventDefault() |
| 221 | this.finish(true, true) |
| 222 | this.hooks.save?.() |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // grow fits the field to its text, up to four lines, and, over the |
| 227 | // image, to the room the image has (Fable L1). |
| 228 | grow () { |
| 229 | const { text } = this |
| 230 | text.style.removeProperty('height') |
| 231 | let height = text.scrollHeight + 2 |
| 232 | if (this.inset) { |
| 233 | const band = this.wrap.offsetHeight - text.offsetHeight |
| 234 | height = Math.min(height, Math.max(36, this.frame.clientHeight - band)) |
| 235 | } |
| 236 | text.style.setProperty('height', `${height}px`) |
| 237 | } |
| 238 | |
| 239 | // finish closes the field, keeping its text or not, and, if refocus, |
| 240 | // gives focus back where it came from. |
| 241 | finish (keep, refocus) { |
| 242 | if (this.closed) return |
| 243 | this.closed = true |
| 244 | if (open === this) open = null |
| 245 | window.removeEventListener('focus', this.returned) |
| 246 | this.wrap.remove() |
| 247 | this.frame.removeAttribute('mapa-alt-open') |
| 248 | this.frame.draggable = this.draggable |
| 249 | this.hooks.closed?.() |
| 250 | const pos = this.place() |
| 251 | const alt = fieldAlt(this.text.value) |
| 252 | const saved = keep && pos !== null && alt !== this.before |
| 253 | if (saved) this.view.dispatch(this.view.state.tr.setNodeAttribute(pos, 'alt', alt)) |
| 254 | // The save may have drawn the block again (the settle plugin's |
| 255 | // reparse), so the image is found afresh. |
| 256 | if (refocus) this.refocus(saved ? this.place(pos) : pos) |
| 257 | if (saved && !(refocus && this.from === 'badge')) { |
| 258 | this.hooks.say?.(alt ? `Image: ${alt}` : 'Image with no description') |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // place is where the image is now, or null when it has gone: at the |
| 263 | // place it was (hint), at its view's, or wherever its id is. |
| 264 | place (hint = null) { |
| 265 | const { doc } = this.view.state |
| 266 | const here = at => typeof at === 'number' && at >= 0 && at < doc.content.size && |
| 267 | this.id(doc.nodeAt(at)) === this.image |
| 268 | if (here(hint)) return hint |
| 269 | let pos = null |
| 270 | try { pos = this.getPos() } catch { pos = null } |
| 271 | if (here(pos)) return pos |
| 272 | pos = null |
| 273 | doc.descendants((node, at) => { |
| 274 | if (pos === null && this.id(node) === this.image) pos = at |
| 275 | return pos === null |
| 276 | }) |
| 277 | return pos |
| 278 | } |
| 279 | |
| 280 | refocus (pos) { |
| 281 | const { view } = this |
| 282 | const frame = pos === null ? null : view.nodeDOM(pos) |
| 283 | const button = frame?.querySelector?.('[mapa-alt-badge]') |
| 284 | if (this.from === 'badge' && button?.isConnected) { |
| 285 | button.focus() |
| 286 | return |
| 287 | } |
| 288 | if (pos !== null) { |
| 289 | const selection = this.from === 'upload' |
| 290 | ? TextSelection.near(view.state.doc.resolve(pos + 1)) |
| 291 | : NodeSelection.create(view.state.doc, pos) |
| 292 | view.dispatch(view.state.tr.setSelection(selection)) |
| 293 | } |
| 294 | view.focus() |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // keepInView moves a popover sideways onto the screen. |
| 299 | function keepInView (wrap) { |
| 300 | const box = wrap.getBoundingClientRect() |
| 301 | const room = document.documentElement.clientWidth - 8 |
| 302 | const shift = box.right > room ? room - box.right : (box.left < 8 ? 8 - box.left : 0) |
| 303 | if (shift) wrap.style.setProperty('inset-inline-start', `${shift}px`) |
| 304 | } |
| 305 | |