| 1 | // fixtures/toolbar.mjs — the formatting bar. |
| 2 | // |
| 3 | // Chrome, so it lives outside [docs-editor]: ProseMirror's {mount: el} |
| 4 | // takes over everything inside that element, and a toolbar rendered |
| 5 | // inside it would be replaced by the document on the first mount. |
| 6 | // views/show.html renders the markup, server-side, with every label |
| 7 | // resolved from the catalog — this module carries no copy of its own, |
| 8 | // the same rule the save-status indicator already follows. |
| 9 | // |
| 10 | // It never holds an EditorView. attemptResync (editor-entry.js) |
| 11 | // destroys and rebuilds the view wholesale, so anything holding one |
| 12 | // dispatches into a dead view after a resync; every command here reads |
| 13 | // getView() at the moment it runs instead. |
| 14 | // |
| 15 | // The button state is kept in step by a ProseMirror plugin rather than |
| 16 | // by listening for clicks and keystrokes: the selection also moves |
| 17 | // under the arrow keys, under a click on the page, and under a remote |
| 18 | // edit arriving through the CRDT, and a bar that only updates on its |
| 19 | // own buttons is wrong most of the time. |
| 20 | |
| 21 | import { Plugin } from 'prosemirror-state' |
| 22 | import { toggleMark, setBlockType, wrapIn, lift, selectAll, chainCommands } from 'prosemirror-commands' |
| 23 | import { wrapInList, liftListItem, sinkListItem } from 'prosemirror-schema-list' |
| 24 | import { undoCommand, redoCommand, yUndoPluginKey } from 'y-prosemirror' |
| 25 | import { setAttr, setProp } from './dom-writes.mjs' |
| 26 | import { setupRoving } from './toolbar-roving.mjs' |
| 27 | import { ALIGNMENTS, alignClass, setAlign, currentAlign } from './align.mjs' |
| 28 | import { FONT_MARKS, fontForMarks } from './fonts.mjs' |
| 29 | import { fontMark as fontMarkOf } from './fonts.mjs' |
| 30 | import { changeIndent } from './indent.mjs' |
| 31 | import { SIZES, SIZE_MARKS, sizeMark, sizeForMarks } from './sizes.mjs' |
| 32 | |
| 33 | // The two exclusive mark groups. A run is in one font and at one size, |
| 34 | // so choosing one has to clear the others — the schema's own |
| 35 | // `excludes` handles that for a toggle, but the select controls set a |
| 36 | // value rather than toggling, which is what setExclusive below is for. |
| 37 | // |
| 38 | // The font group is fonts.mjs's, not a second list here. It has to be |
| 39 | // every font mark including the default's, or clearing would leave the |
| 40 | // mark it missed in place and the run would be in two faces at once — |
| 41 | // and the default's mark is precisely the one a toolbar might think it |
| 42 | // could skip, since this toolbar never writes it. The size group has no |
| 43 | // such subtlety — "normal" has never had a mark — so it stays a literal |
| 44 | // beside its own use. |
| 45 | |
| 46 | |
| 47 | // The three alignment commands: each button's data-docs-command name, |
| 48 | // and the attribute value that button sets. |
| 49 | // |
| 50 | // A module-level table, not three entries inside buildCommands, because |
| 51 | // the guard below has to be able to check it with no schema and no |
| 52 | // browser — see alignmentsAreCovered. |
| 53 | // |
| 54 | // The names are literal keys, and that matters: internal/docs's |
| 55 | // TestToolbarOptionValuesMatchTheBundle checks that every |
| 56 | // data-docs-command in views/show.html is a name this file implements, |
| 57 | // and it does that by looking for the name in this file's source. A |
| 58 | // loop building "align_" + value would leave it nothing to find, so it |
| 59 | // would pass by seeing nothing rather than by agreeing with anything. |
| 60 | // |
| 61 | // Left is `null`, not the string "left": ProseMirror's default for the |
| 62 | // attribute is null and y-prosemirror removes a null attribute from the |
| 63 | // CRDT rather than storing it, so choosing left returns a paragraph to |
| 64 | // exactly the bytes it had before anyone aligned it. |
| 65 | export const ALIGN_COMMANDS = { |
| 66 | align_left: null, |
| 67 | align_center: 'center', |
| 68 | align_right: 'right', |
| 69 | } |
| 70 | |
| 71 | // Every alignment align.mjs offers has a command in that table, every |
| 72 | // command in it is one align.mjs offers, and each command's NAME |
| 73 | // matches the VALUE it sets. |
| 74 | // |
| 75 | // That last clause is the half nothing else can check. This guard's |
| 76 | // first version compared names only, and so does |
| 77 | // TestToolbarOptionValuesMatchTheBundle — so `align_center: 'centre'` |
| 78 | // had the right name, sat under the right button, satisfied both, and |
| 79 | // wrote an alignment that core/src/fragment.rs and both exporters drop |
| 80 | // on the floor. A person would click Centre and watch nothing happen, |
| 81 | // with no error anywhere. |
| 82 | // |
| 83 | // It runs on the line below, at module load, rather than inside |
| 84 | // createToolbar where it used to sit. That was the finding: nothing in |
| 85 | // the gate imports this module, and inside createToolbar it ran only |
| 86 | // when a browser actually mounted the editor — dead code in CI, so a |
| 87 | // mismatch the other tests missed would have passed the entire gate and |
| 88 | // then thrown at startup for every user. fixtures/align.test.mjs now |
| 89 | // imports this module, which is what makes the call below execute on |
| 90 | // every gate run. |
| 91 | // |
| 92 | // A module-load throw does abort the whole bundle, earlier than |
| 93 | // editor-entry.js's own try/catch, so [docs-editor] would not get its |
| 94 | // data-editor-failed marker — the page would keep the server-rendered |
| 95 | // read view without saying why. That is the right trade now that this |
| 96 | // cannot reach production without failing CI first, and it is stated |
| 97 | // here rather than left for someone to discover. |
| 98 | function alignmentsAreCovered() { |
| 99 | const names = Object.keys(ALIGN_COMMANDS) |
| 100 | for (const name of names) { |
| 101 | const value = ALIGN_COMMANDS[name] |
| 102 | const expected = 'align_' + (value === null ? 'left' : value) |
| 103 | if (name !== expected) { |
| 104 | throw new Error( |
| 105 | `toolbar: ${name} sets the alignment ${JSON.stringify(value)}, which belongs to ${expected}`, |
| 106 | ) |
| 107 | } |
| 108 | // alignClass, not a bare lookup: it is the allowlist, so a value |
| 109 | // align.mjs does not know is rejected here rather than stored. |
| 110 | if (value !== null && !alignClass(value)) { |
| 111 | throw new Error(`toolbar: ${name} sets ${JSON.stringify(value)}, which align.mjs does not know`) |
| 112 | } |
| 113 | } |
| 114 | const covered = names.map((name) => name.slice('align_'.length)).sort() |
| 115 | const offered = [...ALIGNMENTS].sort() |
| 116 | if (covered.join() !== offered.join()) { |
| 117 | throw new Error(`toolbar: alignment commands [${covered}] do not match align.mjs's [${offered}]`) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | alignmentsAreCovered() |
| 122 | |
| 123 | // comboInputFor returns the text input ui/select.js built for a |
| 124 | // <select>, or null if the enhancement has not run (or was opted out |
| 125 | // of, or the script never loaded). |
| 126 | // |
| 127 | // select.js inserts its [rst-combo] wrapper immediately BEFORE the |
| 128 | // native select and leaves the select in place, visually hidden — see |
| 129 | // its own `native.parentNode.insertBefore(wrap, native)`. So the |
| 130 | // wrapper is the select's previous sibling, and that relationship is |
| 131 | // the only handle we get; there is no id linking the two. |
| 132 | // |
| 133 | // Null-safe everywhere it is used, because "the enhancement did not |
| 134 | // run" is a state this bar must keep working in: the whole point of |
| 135 | // select.js is that it enhances a real <select> which goes on working |
| 136 | // without it. |
| 137 | function comboInputFor(select) { |
| 138 | const wrap = select.previousElementSibling |
| 139 | if (!wrap || !wrap.hasAttribute('rst-combo')) return null |
| 140 | return wrap.querySelector('input') |
| 141 | } |
| 142 | |
| 143 | // nameCombo gives the combobox the name the select had. |
| 144 | // |
| 145 | // select.js transfers a <label for> onto its input, and nothing else. |
| 146 | // These three selects are named by aria-label — they sit in a toolbar |
| 147 | // with no visible labels — so without this the control a person |
| 148 | // actually reaches has no accessible name at all beyond its |
| 149 | // placeholder, and all three announce as "Type to filter". SC 4.1.2, |
| 150 | // and AGENTS.md allows no exemptions. |
| 151 | function nameCombo(select, input) { |
| 152 | if (!input) return |
| 153 | const name = select.getAttribute('aria-label') |
| 154 | if (name) setAttr(input, 'aria-label', name) |
| 155 | } |
| 156 | |
| 157 | // showInCombo keeps the combobox's visible text in step with the |
| 158 | // select's value. |
| 159 | // |
| 160 | // select.js writes input.value at enhancement, on a user's pick, and on |
| 161 | // blur — and never again. Everything in this file sets select.value |
| 162 | // programmatically, which fires no event and moves nothing a person can |
| 163 | // see: put the caret in a 24pt heading and the native select becomes |
| 164 | // "24" while the combobox still reads whatever was last chosen by hand. |
| 165 | // |
| 166 | // That is not cosmetic. The spec's argument for keeping Font and Size |
| 167 | // out of the Format menu was precisely that a person needs to SEE what |
| 168 | // they are in without opening anything, so a control that displays a |
| 169 | // stale value is the one failure this design cannot absorb. |
| 170 | // |
| 171 | // Skipped while the input has focus: overwriting what somebody is |
| 172 | // halfway through typing into the filter is worse than a stale display. |
| 173 | // |
| 174 | // When the value really did change, ui/select.js is told through its own |
| 175 | // path: a change event on the select, which it answers by redrawing the |
| 176 | // box (its text, and the option's data-rst-class: the font box wears the |
| 177 | // face of the font the caret is in, review finding 6). The event is |
| 178 | // marked as this file's own, so the toolbar's change handlers, which |
| 179 | // apply formatting, ignore it. |
| 180 | let syncing = false |
| 181 | function showInCombo(select, input, changed) { |
| 182 | if (!input || document.activeElement === input) return |
| 183 | if (changed && typeof select.dispatchEvent === 'function') { |
| 184 | syncing = true |
| 185 | try { |
| 186 | select.dispatchEvent(new Event('change')) |
| 187 | } finally { |
| 188 | syncing = false |
| 189 | } |
| 190 | return |
| 191 | } |
| 192 | const option = select.options[select.selectedIndex] |
| 193 | const d = (option && option.dataset) || {} |
| 194 | const text = option ? d.rstShort || d.rstName || option.text : '' |
| 195 | setProp(input, 'value', text) |
| 196 | } |
| 197 | |
| 198 | // onSync, when given, is called after every sync with the live view. It |
| 199 | // is how the menu bar (fixtures/menu.mjs) keeps its items in step |
| 200 | // without a second ProseMirror plugin: one plugin means the two |
| 201 | // surfaces cannot disagree about the same selection, which they would |
| 202 | // eventually do if each watched the editor for itself. |
| 203 | // fonts is the tab's font session (font-session.mjs): a font is loaded |
| 204 | // before it is applied, and the font control stays shut until the |
| 205 | // picker's preview faces have settled. wrapCommand lets the editor make |
| 206 | // bold, italic, code and the block styles wait for their faces too. |
| 207 | // onFontUnavailable is told when a chosen font cannot be loaded. |
| 208 | // history is the undo/redo pairs (views/partials/editor_bar.html's |
| 209 | // [docs-history]: the bar's lead slot's and the strip's). They are bound |
| 210 | // and kept current like every other button, but they are outside the |
| 211 | // role="toolbar" and outside its roving tab stop: two ordinary buttons |
| 212 | // each (spec I2, P1.2 and C6). |
| 213 | // refocus says whether a control should hand the caret back to the |
| 214 | // document once it has acted. It does by default; the phone's Format |
| 215 | // sheet (design/phone-web, P2) says not while it is open, because the |
| 216 | // keyboard went away when it opened and every control applies at once |
| 217 | // with the sheet still up. |
| 218 | export function createToolbar({ root, history = [], schema, getView, onSync, fonts = null, wrapCommand = (c) => c, onFontUnavailable = null, refocus = () => true }) { |
| 219 | // The command table is built even with no toolbar in the DOM, and |
| 220 | // returned either way — the menu bar reads it, and a template that |
| 221 | // renders a menu without a formatting bar (or a future one that drops |
| 222 | // the bar entirely) must still get working menu commands. |
| 223 | // focusStop is in the early return too, and its absence was a real |
| 224 | // bug for one commit: editor-entry.js binds Escape to it and its |
| 225 | // comment promises that with no toolbar there is "nowhere to go" and |
| 226 | // false comes back — but this branch returned no focusStop at all, so |
| 227 | // Escape would have thrown a TypeError inside ProseMirror's keymap. |
| 228 | // Unreachable today because show.html always renders the bar, which |
| 229 | // is exactly why a comment asserting the guarantee needed the code to |
| 230 | // hold it. toolbar-roving.mjs's own early return already did. |
| 231 | if (!root) return { plugin: null, commands: buildCommands(schema, wrapCommand), focusStop: () => false } |
| 232 | |
| 233 | const tools = Array.from(root.querySelectorAll('[data-docs-command]')) |
| 234 | const pairs = history.flatMap((h) => Array.from(h.querySelectorAll('[data-docs-command]'))) |
| 235 | const buttons = [...tools, ...pairs] |
| 236 | const selects = Array.from(root.querySelectorAll('[data-docs-select]')) |
| 237 | |
| 238 | // ui/select.js opens a picker's list upward when there is more room |
| 239 | // above its box than below, and the room above the toolbar is under |
| 240 | // estilo's sticky title bar, which is drawn over the list: an upward |
| 241 | // Style list hid "Body text" there (review on #95). Marked a ceiling, |
| 242 | // the bar is not room, so the list opens down instead. Marked here |
| 243 | // because the bar is estilo's markup, not this page's. |
| 244 | const doc = root.ownerDocument |
| 245 | const header = doc && doc.querySelector && doc.querySelector('[estilo-bar]') |
| 246 | if (header) setAttr(header, 'data-rst-select-ceiling', '') |
| 247 | |
| 248 | const commands = buildCommands(schema, wrapCommand) |
| 249 | |
| 250 | // The chevron at the end of each picker (views/show.html draws it as |
| 251 | // the [rst-combo] wrapper's ::after, with a pointer cursor) is a |
| 252 | // button to the eye, so it opens the list like one: a press on the |
| 253 | // wrapper itself, which is only ever the chevron since the input |
| 254 | // fills the rest, focuses the input, and ui/select.js opens its list |
| 255 | // on focus. A second press, with the list open, closes it. Delegated |
| 256 | // from the bar because select.js builds the wrappers after this runs. |
| 257 | root.addEventListener('pointerdown', (e) => { |
| 258 | const wrap = e.target |
| 259 | if (!wrap || !wrap.hasAttribute || !wrap.hasAttribute('rst-combo')) return |
| 260 | const input = wrap.querySelector('input') |
| 261 | if (!input || input.disabled) return |
| 262 | e.preventDefault() |
| 263 | if (doc.activeElement === input) input.blur() |
| 264 | else input.focus() |
| 265 | }) |
| 266 | |
| 267 | for (const button of buttons) { |
| 268 | // Without this the browser blurs the editor on mousedown, which |
| 269 | // collapses the very selection the command is about to act on. |
| 270 | button.addEventListener('mousedown', (e) => e.preventDefault()) |
| 271 | button.addEventListener('click', () => { |
| 272 | const run = commands[button.getAttribute('data-docs-command')] |
| 273 | const view = getView() |
| 274 | if (!view || !run) return |
| 275 | run(view.state, view.dispatch, view) |
| 276 | if (refocus()) view.focus() |
| 277 | }) |
| 278 | } |
| 279 | |
| 280 | for (const select of selects) { |
| 281 | select.addEventListener('mousedown', (e) => e.stopPropagation()) |
| 282 | // The caret goes back to the document after a choice, always. |
| 283 | // |
| 284 | // Every other control in this bar is a <button>, which cannot hold |
| 285 | // a caret, so nothing needed this before. Once ui/select.js has |
| 286 | // enhanced these, choosing a size leaves focus in a text input — |
| 287 | // and the next thing a person types goes into the font filter |
| 288 | // rather than into their document. The change handler below already |
| 289 | // dispatches; this is the other half of what a toolbar control owes |
| 290 | // the editor. |
| 291 | // |
| 292 | // On the native select too, not only the combobox: without the |
| 293 | // enhancement (a browser that never ran the script, or a future |
| 294 | // opt-out) the behaviour should be the same. |
| 295 | select.addEventListener('change', () => { |
| 296 | if (syncing) return |
| 297 | const view = getView() |
| 298 | if (view && refocus()) view.focus() |
| 299 | else blurPicker() |
| 300 | }) |
| 301 | select.addEventListener('change', () => { |
| 302 | if (syncing) return |
| 303 | const view = getView() |
| 304 | if (!view) return |
| 305 | const kind = select.getAttribute('data-docs-select') |
| 306 | const value = select.value |
| 307 | // A pick, a style or a size is an ordinary transaction: if it needs |
| 308 | // a font that has not loaded, the editor's gate cancels it, waits |
| 309 | // for the font with the editor inert, and performs it then. |
| 310 | // fontMark and sizeMark return undefined for a value this build |
| 311 | // does not know, which must change nothing; null is a real |
| 312 | // instruction to clear. |
| 313 | if (kind === 'block') setBlock(schema, value)(view.state, view.dispatch, view) |
| 314 | if (kind === 'font') { |
| 315 | const mark = fontMarkOf(value) |
| 316 | if (mark !== undefined) setExclusive(schema, FONT_MARKS, mark)(view.state, view.dispatch) |
| 317 | } |
| 318 | if (kind === 'size') { |
| 319 | const mark = sizeMark(value) |
| 320 | if (mark !== undefined) setExclusive(schema, SIZE_MARKS, mark)(view.state, view.dispatch) |
| 321 | } |
| 322 | if (refocus()) view.focus() |
| 323 | }) |
| 324 | } |
| 325 | |
| 326 | // Where the caret stays out of the document (the phone's Format |
| 327 | // sheet), a pick leaves no text box focused: a focused filter would |
| 328 | // keep the on-screen keyboard up over the sheet. |
| 329 | function blurPicker() { |
| 330 | const active = doc && doc.activeElement |
| 331 | if (active && active.tagName === 'INPUT' && root.contains(active)) active.blur() |
| 332 | } |
| 333 | |
| 334 | function sync(view) { |
| 335 | // Every write below goes through setAttr/setProp, which write only |
| 336 | // when the value would change. sync runs on EVERY state update, so |
| 337 | // rewriting a value that is already there costs a style invalidation |
| 338 | // and a mutation record per control per keystroke — and shows up as a |
| 339 | // visible flash on the frame a hidden tab comes back. See |
| 340 | // fixtures/dom-writes.mjs for the measurement. |
| 341 | const state = view.state |
| 342 | for (const button of buttons) { |
| 343 | const name = button.getAttribute('data-docs-command') |
| 344 | const run = commands[name] |
| 345 | if (!run) continue |
| 346 | // A command called with no dispatch reports whether it would do |
| 347 | // anything, which is exactly "should this button be available". |
| 348 | // |
| 349 | // Every command in the table above must honour that contract — |
| 350 | // see buildCommands for the one that did not, and what it cost. |
| 351 | // A command that acts anyway turns this line, which runs on |
| 352 | // every single state update, into an edit nobody asked for. |
| 353 | const enabled = run(state, null, view) |
| 354 | setProp(button, 'disabled', !enabled) |
| 355 | // Only a control rendered with a pressed state has one: undo and |
| 356 | // redo are plain buttons, and an aria-pressed written onto them |
| 357 | // made each announce as a toggle. |
| 358 | if (button.hasAttribute('aria-pressed')) { |
| 359 | // isPressed, not isActive: the phone's style chips are pressed |
| 360 | // for the paragraph style the selection is in, as the menu's |
| 361 | // check column is. |
| 362 | const on = isPressed(state, name) |
| 363 | setAttr(button, 'aria-pressed', on ? 'true' : 'false') |
| 364 | } |
| 365 | } |
| 366 | for (const select of selects) { |
| 367 | // Enabled here, having been rendered disabled. views/show.html |
| 368 | // renders every control disabled so that a page with no working |
| 369 | // JavaScript offers nothing that silently does nothing when |
| 370 | // operated — the buttons were already doing this and the selects |
| 371 | // were not, so with scripting off a person could change "Font" |
| 372 | // to Monospace and watch the document ignore them. |
| 373 | // The font control opens only once the picker's preview faces |
| 374 | // have settled, so no row is ever drawn in a face still arriving. |
| 375 | const shut = select.getAttribute('data-docs-select') === 'font' && fonts && fonts.previews === 'pending' |
| 376 | setProp(select, 'disabled', shut) |
| 377 | // And the combobox, if ui/select.js enhanced this select. |
| 378 | // |
| 379 | // The enhancement does not mirror `disabled` — the string does |
| 380 | // not appear in select.js at all. It mirrors value, options, |
| 381 | // optgroups, required and reset, and stops there. So without |
| 382 | // this line the page ships a control that looks usable before the |
| 383 | // editor has mounted, takes focus and typing, and drives a |
| 384 | // disabled select behind it. |
| 385 | // |
| 386 | // Looked up here rather than captured at mount: select.js runs |
| 387 | // from the shell's own deferred script and this bundle runs from |
| 388 | // a later one, so today the wrapper already exists by the time |
| 389 | // createToolbar runs — but that is an ordering between two files |
| 390 | // neither of which states it, and a lookup costs nothing. |
| 391 | const combo = comboInputFor(select) |
| 392 | if (combo) setProp(combo, 'disabled', shut) |
| 393 | nameCombo(select, combo) |
| 394 | const kind = select.getAttribute('data-docs-select') |
| 395 | const before = select.value |
| 396 | if (kind === 'block') setProp(select, 'value', currentBlock(state)) |
| 397 | // Not currentGroup: the font group's fallback is not a literal |
| 398 | // this file gets to choose. An unmarked run is in whatever face |
| 399 | // fonts.mjs says the default is, and that is the same answer |
| 400 | // views/show.html and internal/export/pdf.go have to give. |
| 401 | if (kind === 'font') setProp(select, 'value', currentFont(state, schema)) |
| 402 | // Not currentGroup, for the same reason the font control stopped |
| 403 | // using it: the fallback is not a literal this file gets to |
| 404 | // choose, and the answer for a legacy mark is not its own name. |
| 405 | // sizes.mjs maps size_lg to 14 so the control names a size that |
| 406 | // is on the ladder and in the list, rather than a value no option |
| 407 | // carries — which a <select> renders by showing nothing at all. |
| 408 | if (kind === 'size') { |
| 409 | setProp(select, 'value', String(sizeForMarks(activeMarkNames(state, schema, SIZE_MARKS)))) |
| 410 | } |
| 411 | // Every branch above sets select.value programmatically, which |
| 412 | // fires no event, so the combobox has to be told. See |
| 413 | // showInCombo — without this the enhanced control displays |
| 414 | // whatever was last chosen by hand while the document says |
| 415 | // otherwise. |
| 416 | showInCombo(select, comboInputFor(select), select.value !== before) |
| 417 | } |
| 418 | if (onSync) onSync(view) |
| 419 | } |
| 420 | |
| 421 | // The roving tabindex walks what a person can actually reach. |
| 422 | // |
| 423 | // For an enhanced select that is the combobox input, not the select: |
| 424 | // select.js gives the native one tabindex="-1" and aria-hidden="true" |
| 425 | // and hides it, so leaving it in this list would put an arrow-key |
| 426 | // stop on an element no one can see. Where the enhancement has not |
| 427 | // run, the select itself is still the control and still belongs here. |
| 428 | // |
| 429 | // Each select's stand-in takes that select's own place in the list, |
| 430 | // so this substitution changes nothing about the order. The order is |
| 431 | // the reading order, selects then buttons, as the DOM has them: the |
| 432 | // selects open the bar (the Style section, in the inspector), now that |
| 433 | // undo and redo have left it. It used to be buttons-then-selects, which |
| 434 | // walked the strip out of visual order while undo/redo came first; the |
| 435 | // inspector lays the groups out in a column, and Left/Right walk it in |
| 436 | // the order it is read (spec I2, P1.2). |
| 437 | // The undo/redo pairs are not in it (tools, not buttons). |
| 438 | const roving = setupRoving(root, [ |
| 439 | ...selects.map((select) => comboInputFor(select) || select), |
| 440 | ...tools, |
| 441 | ]) |
| 442 | |
| 443 | // One Plugin instance, reused by every EditorState this page creates |
| 444 | // — a plugin is configuration, not state, so a resync's fresh state |
| 445 | // can take the same one. |
| 446 | const plugin = new Plugin({ |
| 447 | view: (view) => { |
| 448 | sync(view) |
| 449 | roving.ensureReachable() |
| 450 | // Undo and redo were stale after either was used: an undo applies |
| 451 | // its change, and the transaction that tells this view about it runs |
| 452 | // before Y.UndoManager has moved the item onto the redo stack, so |
| 453 | // sync read the stacks a moment early and greyed out Redo (and, |
| 454 | // after a redo, Undo), with no later transaction to correct it. |
| 455 | // The manager's own stack events are that later moment. Both pairs, |
| 456 | // the lead's and the strip's, are in buttons, so both stay current. |
| 457 | const undoManager = yUndoPluginKey.getState(view.state)?.undoManager |
| 458 | const refresh = () => { |
| 459 | sync(view) |
| 460 | roving.ensureReachable() |
| 461 | } |
| 462 | if (undoManager) { |
| 463 | undoManager.on('stack-item-added', refresh) |
| 464 | undoManager.on('stack-item-popped', refresh) |
| 465 | } |
| 466 | return { |
| 467 | update: (v) => { |
| 468 | sync(v) |
| 469 | roving.ensureReachable() |
| 470 | }, |
| 471 | destroy: () => { |
| 472 | if (undoManager) { |
| 473 | undoManager.off('stack-item-added', refresh) |
| 474 | undoManager.off('stack-item-popped', refresh) |
| 475 | } |
| 476 | }, |
| 477 | } |
| 478 | }, |
| 479 | }) |
| 480 | |
| 481 | // isPressed answers the menu bar's check column (menu.mjs): which |
| 482 | // paragraph style and which alignment the selection is in. Paragraph |
| 483 | // styles are named as the block select names them. |
| 484 | const isPressed = (state, name) => { |
| 485 | if (name.startsWith('block_')) return currentBlock(state) === name.slice('block_'.length) |
| 486 | return isActive(state, schema, name) |
| 487 | } |
| 488 | return { plugin, commands, focusStop: roving.focusStop, isPressed } |
| 489 | } |
| 490 | |
| 491 | function buildCommands(schema, wrapCommand = (c) => c) { |
| 492 | const marks = schema.marks |
| 493 | const nodes = schema.nodes |
| 494 | return { |
| 495 | // undoCommand/redoCommand, NOT y-prosemirror's undo/redo. |
| 496 | // |
| 497 | // This distinction cost an evening, so it is written down. A |
| 498 | // ProseMirror command's contract is that calling it with a null |
| 499 | // dispatch performs nothing and only reports whether it could — |
| 500 | // which is how `sync` below decides whether to grey a button out. |
| 501 | // y-prosemirror's exported `undo` does not honour that contract: |
| 502 | // |
| 503 | // export const undo = state => |
| 504 | // yUndoPluginKey.getState(state)?.undoManager?.undo() != null |
| 505 | // |
| 506 | // It ignores dispatch entirely and undoes immediately. So a |
| 507 | // toolbar that asked "could I undo?" on every state update — which |
| 508 | // is exactly what keeping a button's disabled state honest means — |
| 509 | // performed a real undo on every state update, and every edit |
| 510 | // anyone made was silently reverted a moment later. Typing did |
| 511 | // nothing. Bold did nothing. There was no error, because nothing |
| 512 | // went wrong: the button asked a question and the library answered |
| 513 | // it by doing the thing. |
| 514 | // |
| 515 | // undoCommand/redoCommand are the library's own dispatch-aware |
| 516 | // pair (canUndo()/canRedo() when dispatch is null), and they are |
| 517 | // what a command table read by `sync` must use. The keymap in |
| 518 | // editor-entry.js keeps the bare undo/redo, correctly: a keymap |
| 519 | // never calls a command with a null dispatch. |
| 520 | undo: undoCommand, |
| 521 | redo: redoCommand, |
| 522 | // Each waits for the face it will paint in (editor-entry.js's |
| 523 | // afterFaces): Cmd+B in a family whose bold has not arrived would |
| 524 | // otherwise draw a fallback bold first. |
| 525 | strong: wrapCommand(toggleMark(marks.strong)), |
| 526 | em: wrapCommand(toggleMark(marks.em)), |
| 527 | code: wrapCommand(toggleMark(marks.code), true), |
| 528 | bullet_list: toggleList(nodes.bullet_list, nodes.list_item), |
| 529 | ordered_list: toggleList(nodes.ordered_list, nodes.list_item), |
| 530 | blockquote: toggleWrap(nodes.blockquote), |
| 531 | // The two menu-only commands. They live here rather than in |
| 532 | // fixtures/menu.mjs because this is the command table both surfaces |
| 533 | // read, and a command implemented beside one of them is a command |
| 534 | // the other cannot offer — which is the duplication the menu was |
| 535 | // supposed to avoid. Neither has a toolbar button today; both would |
| 536 | // be reasonable ones later, and that costs a line of markup rather |
| 537 | // than a move. |
| 538 | select_all: selectAll, |
| 539 | clear_formatting: clearFormatting, |
| 540 | // The paragraph styles, as commands. |
| 541 | // |
| 542 | // The Style select already sets these, through setBlock and its own |
| 543 | // change handler — but a select is not reachable as a command, and |
| 544 | // the Format menu needs them by name. Rather than a second |
| 545 | // implementation, each of these IS setBlock, bound to one of the |
| 546 | // select's own option values, so the two controls cannot come to |
| 547 | // mean different things. |
| 548 | // |
| 549 | // Names are written out rather than built in a loop, for the reason |
| 550 | // ALIGN_COMMANDS' comment gives at length: internal/docs's tests |
| 551 | // look for the literal name in this file's source, and a loop would |
| 552 | // leave them nothing to find, so they would pass by seeing nothing. |
| 553 | block_paragraph: setBlock(schema, 'paragraph'), |
| 554 | 'block_heading-1': setBlock(schema, 'heading-1'), |
| 555 | 'block_heading-2': setBlock(schema, 'heading-2'), |
| 556 | 'block_heading-3': setBlock(schema, 'heading-3'), |
| 557 | // The phone's size stepper (design/phone-web, P2): one step down or |
| 558 | // up the ladder sizes.mjs keeps, from the size the selection is in. |
| 559 | // A step past either end does nothing, and says so to a dry run. |
| 560 | size_down: stepSize(schema, -1), |
| 561 | size_up: stepSize(schema, 1), |
| 562 | // Indent and outdent. The same two commands the Tab key runs |
| 563 | // (editor-entry.js's keymap), chained the same way so the menu and |
| 564 | // the key cannot disagree about what Tab does in a list: nest the |
| 565 | // item if there is one, step the block's indent otherwise. |
| 566 | indent: chainCommands(sinkListItem(nodes.list_item), changeIndent(1)), |
| 567 | outdent: chainCommands(liftListItem(nodes.list_item), changeIndent(-1)), |
| 568 | // The three alignments, from the module-level table above — the |
| 569 | // one place their names and their values are written down. |
| 570 | ...Object.fromEntries( |
| 571 | Object.entries(ALIGN_COMMANDS).map(([name, value]) => [name, setAlign(value)]), |
| 572 | ), |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | // clearFormatting strips every mark from the selection and returns its |
| 577 | // blocks to plain paragraphs — the thing a person reaches for after a |
| 578 | // bad paste, and the one command in this table that is defined by what |
| 579 | // it removes rather than by what it applies. |
| 580 | // |
| 581 | // It honours the null-dispatch contract the whole table is held to (see |
| 582 | // buildCommands' own comment): with a collapsed selection there is |
| 583 | // nothing to strip and nothing to report, so it says no rather than |
| 584 | // quietly clearing the stored marks a person just set up for their next |
| 585 | // word. |
| 586 | // |
| 587 | // removeMark(from, to, null) removes ALL marks in the range, which is |
| 588 | // deliberately not a loop over the schema's mark types: the CRDT can |
| 589 | // carry a mark this build's schema has never heard of — a document |
| 590 | // written by a later version, or bytes posted straight to |
| 591 | // /d/{sqid}/updates — and a loop over known types would leave exactly |
| 592 | // those in place while telling a person the formatting was cleared. |
| 593 | // |
| 594 | // The block reset is separate and comes second, because setBlockType |
| 595 | // maps over the range and would otherwise be undone by the mark |
| 596 | // removal's own mapping. |
| 597 | function clearFormatting(state, dispatch) { |
| 598 | const { from, to, empty } = state.selection |
| 599 | if (empty) return false |
| 600 | if (dispatch) { |
| 601 | const tr = state.tr.removeMark(from, to, null) |
| 602 | tr.setBlockType(from, to, state.schema.nodes.paragraph) |
| 603 | dispatch(tr.scrollIntoView()) |
| 604 | } |
| 605 | return true |
| 606 | } |
| 607 | |
| 608 | // setBlock turns the block containing the selection into a paragraph |
| 609 | // or a heading. The select's values are "paragraph" and "heading-N". |
| 610 | function setBlock(schema, value) { |
| 611 | if (value === 'paragraph') return setBlockType(schema.nodes.paragraph) |
| 612 | const level = Number(value.split('-')[1]) |
| 613 | if (!Number.isInteger(level)) return () => false |
| 614 | return setBlockType(schema.nodes.heading, { level }) |
| 615 | } |
| 616 | |
| 617 | // setExclusive clears every mark in a group and then applies one of |
| 618 | // them (or none). One transaction, not two: internal/core caps the |
| 619 | // retained update log at 4096 with no compaction yet, and every |
| 620 | // transaction the editor dispatches becomes an update in it, so a |
| 621 | // control that spent two per click would spend that budget twice as |
| 622 | // fast for no benefit a person can see. |
| 623 | // stepSize moves the selection's size one step along the ladder, in |
| 624 | // order (SIZES is not: its first entry is the default). |
| 625 | function stepSize(schema, dir) { |
| 626 | const ladder = [...SIZES].sort((a, b) => a - b) |
| 627 | return (state, dispatch) => { |
| 628 | const at = ladder.indexOf(sizeForMarks(activeMarkNames(state, schema, SIZE_MARKS))) |
| 629 | const next = ladder[at + dir] |
| 630 | if (at < 0 || next === undefined) return false |
| 631 | const mark = sizeMark(next) |
| 632 | if (mark === undefined) return false |
| 633 | return setExclusive(schema, SIZE_MARKS, mark)(state, dispatch) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | function setExclusive(schema, group, wanted) { |
| 638 | return (state, dispatch) => { |
| 639 | const types = group.map((n) => schema.marks[n]).filter(Boolean) |
| 640 | const target = wanted ? schema.marks[wanted] : null |
| 641 | if (wanted && !target) return false |
| 642 | if (!dispatch) return true |
| 643 | |
| 644 | const { from, to, empty } = state.selection |
| 645 | if (empty) { |
| 646 | // No selection: the choice applies to whatever is typed next, |
| 647 | // which ProseMirror models as stored marks rather than as a |
| 648 | // change to the document. |
| 649 | let stored = (state.storedMarks || state.selection.$from.marks()).filter( |
| 650 | (m) => !types.includes(m.type), |
| 651 | ) |
| 652 | if (target) stored = target.create().addToSet(stored) |
| 653 | dispatch(state.tr.setStoredMarks(stored)) |
| 654 | return true |
| 655 | } |
| 656 | |
| 657 | const tr = state.tr |
| 658 | for (const type of types) tr.removeMark(from, to, type) |
| 659 | if (target) tr.addMark(from, to, target.create()) |
| 660 | dispatch(tr) |
| 661 | return true |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | // toggleList wraps the selection in a list, or lifts it out if it is |
| 666 | // already in one — a list button that only ever wraps is a button you |
| 667 | // cannot undo without reaching for the keyboard. |
| 668 | function toggleList(listType, itemType) { |
| 669 | const wrap = wrapInList(listType) |
| 670 | const unwrap = liftListItem(itemType) |
| 671 | return (state, dispatch, view) => { |
| 672 | if (inside(state, listType)) return unwrap(state, dispatch, view) |
| 673 | return wrap(state, dispatch, view) |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | function toggleWrap(nodeType) { |
| 678 | const wrap = wrapIn(nodeType) |
| 679 | return (state, dispatch, view) => { |
| 680 | if (inside(state, nodeType)) return lift(state, dispatch, view) |
| 681 | return wrap(state, dispatch, view) |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | // inside reports whether the selection sits anywhere within a node of |
| 686 | // this type. |
| 687 | function inside(state, nodeType) { |
| 688 | const $from = state.selection.$from |
| 689 | for (let d = $from.depth; d > 0; d--) { |
| 690 | if ($from.node(d).type === nodeType) return true |
| 691 | } |
| 692 | return false |
| 693 | } |
| 694 | |
| 695 | function isActive(state, schema, name) { |
| 696 | // Exactly one of the three is pressed at any moment, and it is the |
| 697 | // alignment the block will actually RENDER at — currentAlign reports |
| 698 | // left for a value this build does not know, because a button |
| 699 | // pressed for something the reader will never see would be a lie |
| 700 | // about the document. |
| 701 | if (name.startsWith('align_')) return currentAlign(state) === name.slice('align_'.length) |
| 702 | if (name === 'bullet_list') return inside(state, schema.nodes.bullet_list) |
| 703 | if (name === 'ordered_list') return inside(state, schema.nodes.ordered_list) |
| 704 | if (name === 'blockquote') return inside(state, schema.nodes.blockquote) |
| 705 | const type = schema.marks[name] |
| 706 | if (!type) return false |
| 707 | return markActive(state, type) |
| 708 | } |
| 709 | |
| 710 | // markActive is ProseMirror's own idiom: for an empty selection the |
| 711 | // answer is about the marks that would apply to the next keystroke |
| 712 | // (stored marks, or the marks at the cursor), not about the document. |
| 713 | function markActive(state, type) { |
| 714 | const { from, $from, to, empty } = state.selection |
| 715 | if (empty) return !!type.isInSet(state.storedMarks || $from.marks()) |
| 716 | return state.doc.rangeHasMark(from, to, type) |
| 717 | } |
| 718 | |
| 719 | // currentBlock is what the block select should read. A selection |
| 720 | // spanning two different block types reports the one it starts in |
| 721 | // rather than blanking the control: a select with no value looks |
| 722 | // broken, and the first block is the one a person's cursor is in. |
| 723 | function currentBlock(state) { |
| 724 | const parent = state.selection.$from.parent |
| 725 | if (parent.type.name === 'heading') return 'heading-' + parent.attrs.level |
| 726 | return 'paragraph' |
| 727 | } |
| 728 | |
| 729 | // currentFont is what the font select should read: the face the |
| 730 | // selection is actually in, which for a run carrying no font mark is |
| 731 | // the default rather than "nothing". |
| 732 | // |
| 733 | // The reading is split from the answering on purpose. This function |
| 734 | // knows about ProseMirror state and nothing about which face is the |
| 735 | // default; fonts.mjs's fontForMarks knows which face is the default and |
| 736 | // nothing about ProseMirror. That is what lets the default be pinned by |
| 737 | // a test that needs no editor (fonts.test.mjs) and, through it, held |
| 738 | // equal to the stylesheet's and the exporter's (internal/docs's |
| 739 | // TestTheToolbarDefaultFontIsTheDefaultFace). |
| 740 | function currentFont(state, schema) { |
| 741 | const active = FONT_MARKS.filter((name) => { |
| 742 | const type = schema.marks[name] |
| 743 | return type && markActive(state, type) |
| 744 | }) |
| 745 | return fontForMarks(active) |
| 746 | } |
| 747 | |
| 748 | // currentGroup reads which of an exclusive mark group applies, as the |
| 749 | // select's own value. A selection carrying two different sizes reports |
| 750 | // the fallback rather than picking one of them arbitrarily. |
| 751 | // |
| 752 | // Only the size control uses it now: "normal" is a fallback this file |
| 753 | // can name, because unlike the default FACE nothing outside the editor |
| 754 | // has an opinion about it — no stylesheet rule and no exporter constant |
| 755 | // says what "normal" is, the body size says it. |
| 756 | function currentGroup(state, schema, group, prefix, fallback) { |
| 757 | for (const name of group) { |
| 758 | const type = schema.marks[name] |
| 759 | if (type && markActive(state, type)) return name.slice(prefix.length) |
| 760 | } |
| 761 | return fallback |
| 762 | } |
| 763 | |
| 764 | // activeMarkNames is currentGroup's raw half: which of a group's marks |
| 765 | // are on the selection, in the group's own order, without deciding what |
| 766 | // they mean. |
| 767 | // |
| 768 | // It exists because the size group stopped being answerable by string |
| 769 | // surgery. currentGroup returns the mark's name with its prefix cut |
| 770 | // off, which was the whole answer while the sizes were called sm, lg |
| 771 | // and xl — the control's option values were those same three strings. |
| 772 | // They are numbers now, and three legacy marks map onto the ladder |
| 773 | // rather than naming themselves, so the mapping is sizes.mjs's job. |
| 774 | // This hands it the names and lets sizeForMarks answer. |
| 775 | function activeMarkNames(state, schema, group) { |
| 776 | const out = [] |
| 777 | for (const name of group) { |
| 778 | const type = schema.marks[name] |
| 779 | if (type && markActive(state, type)) out.push(name) |
| 780 | } |
| 781 | return out |
| 782 | } |
| 783 | |