oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/toolbar.test.mjs — the editor's chrome must not write to the
2// DOM when the DOM is already right.
3//
4// Named for the toolbar because the toolbar's plugin is the entry
5// point, but it covers both bars: editor-entry.js gives the whole
6// chrome ONE ProseMirror plugin, and the menu bar rides on it through
7// createToolbar's onSync. So this file wires them the same way and
8// holds one property across both.
9//
10// THIS FILE EXISTS BECAUSE ITS ABSENCE SHIPPED A VISIBLE FLASH. Driven
11// in a real browser with one genuinely hidden tab, switching back to a
12// document produced 23 DOM mutations on reveal, 21 of them attribute
13// writes on chrome that was already on screen — and recording each
14// write's old value against its new one, 21 of 21 were redundant. Zero
15// changed anything. Every one restated what was already there:
16// aria-pressed "false" -> "false", disabled "" -> "". setAttribute with
17// an identical value still invalidates style and still records a
18// mutation, and so does setting a reflected boolean property to the
19// value it already holds, so the browser spent a frame repainting
20// chrome nothing had changed.
21//
22// The tab switch was only where it became visible. Both bars sync on
23// EVERY ProseMirror state update, so this was the cost of every
24// keystroke as well; tabbing back merely gathered a page of it into one
25// frame. And it grows: the same measurement gave 12 mutations before
26// the toolbar redesign and 23 after, because each control added brought
27// its own unconditional pair of writes. The menu bar, written after the
28// toolbar by a different session, reproduced the defect from scratch —
29// which is the argument for holding this against the source and not
30// only against the controls that exist today.
31//
32// So the property is not "few mutations on a tab switch", which is a
33// symptom at one moment. It is: AFTER A STATE UPDATE THAT CHANGES
34// NOTHING, THE CHROME PERFORMS ZERO WRITES.
35//
36// No DOM and no browser, the same arrangement menu.test.mjs uses: a
37// stand-in for the handful of DOM surface these modules touch, which
38// records every write WHETHER OR NOT IT CHANGES ANYTHING. Recording the
39// call rather than the change is the entire seam — a check that
40// compared the bars before and after would see nothing wrong, because
41// nothing IS different afterwards.
42import { test } from 'node:test'
43import assert from 'node:assert/strict'
44import { readFileSync } from 'node:fs'
45import { Schema } from 'prosemirror-model'
46import { EditorState, TextSelection } from 'prosemirror-state'
47import { schema as basic } from 'prosemirror-schema-basic'
48import { addListNodes } from 'prosemirror-schema-list'
49import { alignedParagraph } from './align.mjs'
50import { withIndent } from './indent.mjs'
51import { SIZE_MARKS, SIZES, sizeMark, sizeForMarks } from './sizes.mjs'
52import { FONTS } from './fonts.mjs'
53import { createToolbar } from './toolbar.mjs'
54import { mountMenu } from './menu.mjs'
55
56// toolbar.mjs asks the document which element has focus, so that
57// showInCombo can decline to overwrite a filter box somebody is typing
58// into; menu.mjs listens on the document for a click-away close. Those
59// are the two reaches for a global in these modules, and under Node
60// there is nothing to reach for. A stand-in with nothing focused is
61// what a chrome syncing while the caret is in the document sees anyway.
62globalThis.document = { activeElement: null, addEventListener() {} }
63
64// The schema editor-entry.js builds, assembled the same way from the
65// same modules. Written out rather than imported because
66// editor-entry.js is a program, not a module surface — it mounts an
67// EditorView on import — but every piece of the vocabulary here comes
68// from the file that owns it, so the two cannot drift in the parts this
69// test reads (the font marks, the size marks, the block types).
70function spanMark(cls, group) {
71 return {
72 group,
73 excludes: group,
74 parseDOM: [{ tag: 'span.' + cls }],
75 toDOM: () => ['span', { class: cls }, 0],
76 }
77}
78
79const marks = SIZE_MARKS.reduce(
80 (spec, mark) => spec.addToStart(mark, spanMark('docs-' + mark.replace('_', '-'), 'fontSize')),
81 basic.spec.marks,
82)
83 .addToStart('font_mono', spanMark('docs-font-mono', 'fontFamily'))
84 .addToStart('font_sans', spanMark('docs-font-sans', 'fontFamily'))
85 .addToStart('font_serif', spanMark('docs-font-serif', 'fontFamily'))
86
87const nodes = addListNodes(
88 basic.spec.nodes
89 .update('paragraph', withIndent(alignedParagraph(basic.spec.nodes.get('paragraph')), 'p'))
90 .update('heading', withIndent(basic.spec.nodes.get('heading'), 'h1')),
91 'paragraph block*',
92 'block',
93)
94
95const schema = new Schema({ nodes, marks })
96
97// A recording stand-in for the DOM surface the chrome touches.
98//
99// Every attribute write and every property write goes into one log,
100// with its old value beside its new one, whether or not the two differ.
101// Nothing here is a DOM implementation and it must not grow into one —
102// the moment a test needs layout or real focus it belongs in the
103// browser drive (fixtures/browser-drive.mjs).
104//
105// EVERY property write, through a Proxy, and not just the three this
106// file bothered to define accessors for. That distinction was a real
107// hole, found in review with a probe planted on menu.mjs's
108// every-state-update path:
109//
110// if (!name.includes('https://')) el.title = 'seen'
111//
112// which all three tests passed. `title` is attribute-reflected, so an
113// identical-value write invalidates style and records a mutation on
114// every keystroke — the exact defect this file exists to stop — and it
115// was invisible twice over. The structural check below missed it
116// because stripComments does not parse string literals, so the `//`
117// inside 'https://' blanked the rest of the line; and this fake missed
118// it because an assignment to a property with no accessor landed on a
119// plain object without a sound. Two nets, one hole in each, and the
120// holes overlapped.
121//
122// The Proxy closes this one, and closes it for a class rather than for
123// a name: el.title, el.textContent, el.className, el.checked,
124// el.hidden, el.innerHTML, el['disabled'] written through a computed
125// key, and compound forms like `||=` that the structural check's
126// bare-`=` shape does not match either. The three accessors stay for
127// their semantics — a select refusing a value no option carries — and
128// no longer log, because the trap already did.
129//
130// Two roots, not one, because that is how the page is built: the
131// formatting bar is [docs-toolbar] and the menu bar is [estilo-menubar],
132// and both hold elements carrying data-docs-command. A single root
133// would hand the toolbar the menu's items and test something the
134// browser never does.
135function makeDOM({ chips = false } = {}) {
136 const log = []
137 const bar = []
138 const menu = []
139 // The undo/redo pairs (views/partials/editor_bar.html's [docs-history]):
140 // the bar's lead slot's and the strip's, outside [docs-toolbar].
141 const lead = []
142 const strip = []
143
144 // `extra` is applied to the raw node BEFORE the Proxy wraps it: the
145 // fixture's own setup (a select's options, its combobox wrapper) is
146 // not a write by the code under test and must not be logged as one.
147 function element(tag, id, attrs, into, extra = {}) {
148 const own = { ...attrs }
149 let disabled = 'disabled' in own
150 let tabIndex = 'tabindex' in own ? Number(own.tabindex) : -1
151 let value = ''
152 const listeners = {}
153 const node = {
154 tag,
155 id,
156 options: [],
157 selectedIndex: -1,
158 children: [],
159 previousElementSibling: null,
160 getAttribute: (k) => (k in own ? own[k] : null),
161 hasAttribute: (k) => k in own,
162 setAttribute(k, v) {
163 log.push({ id, name: k, from: node.getAttribute(k), to: String(v) })
164 own[k] = String(v)
165 },
166 removeAttribute(k) {
167 log.push({ id, name: k, from: node.getAttribute(k), to: null })
168 delete own[k]
169 },
170 // Two selector forms, which is all these modules use: a bare tag
171 // name, and one or more [attribute] clauses that must all match.
172 matches(sel) {
173 if (sel === tag) return true
174 const parts = sel.match(/\[[^\]]+\]/g)
175 return parts ? parts.every((p) => p.slice(1, -1) in own) : false
176 },
177 querySelector: (sel) => node.children.find((c) => c.matches(sel)) || null,
178 querySelectorAll: (sel) => node.children.filter((c) => c.matches(sel)),
179 closest: () => null,
180 // Listeners are kept, so a test can play a click (emit); none of
181 // the write-counting tests emits anything.
182 addEventListener(type, fn) {
183 ;(listeners[type] = listeners[type] || []).push(fn)
184 },
185 emit(type, event = {}) {
186 for (const fn of listeners[type] || []) fn({ preventDefault() {}, stopPropagation() {}, ...event })
187 },
188 // Focus is recorded as the page's active element, so the roving
189 // tab stop's keyboard handler can be driven here.
190 focus() {
191 globalThis.document.activeElement = this
192 },
193 }
194 // The three properties that are not plain storage. They keep their
195 // accessors for the behaviour, and do no logging of their own — the
196 // Proxy below logs every write, these included, so a value here
197 // would be counted twice.
198 Object.defineProperty(node, 'disabled', {
199 get: () => disabled,
200 set: (v) => {
201 disabled = v
202 },
203 })
204 Object.defineProperty(node, 'tabIndex', {
205 get: () => tabIndex,
206 set: (v) => {
207 tabIndex = v
208 },
209 })
210 Object.defineProperty(node, 'value', {
211 get: () => value,
212 set: (v) => {
213 // A real <select> refuses a value no option carries and reports
214 // "" afterwards. Emulated because it is the one way a write
215 // guarded by a comparison can still fire on every update, and a
216 // fake that quietly accepted any string would hide it.
217 //
218 // selectedIndex is moved on the raw node, not through the
219 // Proxy: it is a consequence of this write, not a second one.
220 if (tag === 'select') {
221 const at = node.options.findIndex((o) => o.value === String(v))
222 node.selectedIndex = at
223 value = at < 0 ? '' : String(v)
224 } else {
225 value = String(v)
226 }
227 },
228 })
229 Object.assign(node, extra)
230
231 const el = new Proxy(node, {
232 set(target, key, v) {
233 log.push({ id, name: String(key), from: target[key], to: v })
234 target[key] = v
235 return true
236 },
237 })
238 into.push(el)
239 return el
240 }
241
242 // views/show.html renders every control disabled, and the toolbar
243 // buttons with aria-pressed="false" except undo and redo, which have
244 // no pressed state to render. Reproduced exactly: what the first sync
245 // has to change depends on it.
246 function button(name, pressed = true) {
247 return element(
248 'button',
249 name,
250 {
251 'data-docs-command': name,
252 tabindex: '-1',
253 disabled: '',
254 ...(pressed ? { 'aria-pressed': 'false' } : {}),
255 },
256 bar,
257 )
258 }
259
260 // An undo/redo button as docs-history renders it, with no tabindex
261 // (an ordinary button, not a roving control) and no pressed state; but
262 // ENABLED, as a pair left stale would be, so the first sync has to
263 // write to it (nothing can be undone in a fresh state) and a pair the
264 // toolbar never reached shows up as no write.
265 function historyButton(name, into, prefix) {
266 return element('button', prefix + name, { 'data-docs-command': name }, into)
267 }
268
269 // A select as ui/select.js leaves it: the native control still there,
270 // with the enhancement's [rst-combo] wrapper inserted immediately
271 // before it, holding the text input a person actually uses.
272 function selectControl(kind, options) {
273 const wrap = element('div', kind + '-wrap', { 'rst-combo': '' }, bar)
274 const input = element('input', kind + '-combo', { tabindex: '-1', disabled: '' }, bar)
275 wrap.children.push(input)
276 return element(
277 'select',
278 'docs-select-' + kind,
279 {
280 'data-docs-select': kind,
281 'aria-label': 'The ' + kind + ' control',
282 tabindex: '-1',
283 disabled: '',
284 },
285 bar,
286 {
287 previousElementSibling: wrap,
288 options: options.map(([value, text]) => ({ value: String(value), text })),
289 },
290 )
291 }
292
293 // A menu row, as menu.go renders it: disabled from the server, and
294 // named by the same data-docs-command vocabulary the toolbar uses.
295 function menuItem(name, extra = {}) {
296 return element(
297 'button',
298 'menu-' + name,
299 { 'estilo-menu-item': '', 'data-docs-command': name, disabled: '', ...extra },
300 menu,
301 )
302 }
303
304 for (const name of ['undo', 'redo']) {
305 historyButton(name, lead, 'lead-')
306 historyButton(name, strip, 'strip-')
307 }
308 selectControl('block', [
309 ['paragraph', 'Paragraph'],
310 ['heading-1', 'Heading 1'],
311 ['heading-2', 'Heading 2'],
312 ['heading-3', 'Heading 3'],
313 ])
314 selectControl(
315 'font',
316 FONTS.map((f) => [f, f[0].toUpperCase() + f.slice(1)]),
317 )
318 selectControl(
319 'size',
320 SIZES.map((pt) => [pt, String(pt)]),
321 )
322 for (const name of ['strong', 'em', 'code']) button(name)
323 // The phone's Format sheet's style chips (views/show.html): buttons
324 // named by the block_ commands, with a pressed state.
325 if (chips) for (const name of ['block_paragraph', 'block_heading-2']) button(name)
326 for (const name of ['align_left', 'align_center', 'align_right']) button(name)
327 for (const name of ['bullet_list', 'ordered_list', 'blockquote']) button(name)
328
329 // The menu bar. One title, because the roving tabindex needs at least
330 // one and this file is not testing the roving; and the three shapes
331 // of row that reach different lines of menu.mjs's sync — an editor
332 // command, a LOCAL_COMMANDS one (Print, available whenever the page
333 // is), and a checkable one, whose aria-pressed sync also writes.
334 element('summary', 'menu-title', { 'estilo-menubar-title': '', tabindex: '-1' }, menu)
335 menuItem('strong')
336 menuItem('undo')
337 menuItem('clear_formatting')
338 menuItem('print')
339 menuItem('block_paragraph', { 'aria-pressed': 'false' })
340 menuItem('block_heading-1', { 'aria-pressed': 'false' })
341
342 const handlers = {}
343 function rootOver(list, record = false) {
344 return {
345 addEventListener(type, fn) {
346 if (record) handlers[type] = fn
347 },
348 contains: (el) => list.includes(el),
349 querySelector: (sel) => list.find((n) => n.matches(sel)) || null,
350 querySelectorAll: (sel) => list.filter((n) => n.matches(sel)),
351 }
352 }
353
354 const everything = () => bar.concat(menu, lead, strip)
355
356 return {
357 toolbarRoot: rootOver(bar, true),
358 toolbarHandlers: handlers,
359 historyRoots: [rootOver(lead), rootOver(strip)],
360 menuRoot: rootOver(menu),
361 log,
362 byId: (id) => everything().find((n) => n.id === id),
363 writesTo: (id, name) => log.filter((w) => w.id === id && w.name === name).map((w) => w.to),
364 }
365}
366
367// Both bars, wired exactly as editor-entry.js wires them: ONE plugin,
368// the toolbar's, with the menu riding on its onSync. `menu` is assigned
369// after createToolbar and read through a closure, which is what lets
370// the very first sync reach it — the same shape editor-entry.js has,
371// and worth copying rather than tidying, because a menu mounted before
372// the toolbar would be driven by a code path the browser never takes.
373//
374// The view is a stand-in. sync reads view.state and hands the view on
375// to commands called with a null dispatch, which is a contract every
376// command in the table honours (buildCommands' own comment has the
377// evening that cost).
378function mount(state, { chips = false, refocus } = {}) {
379 const dom = makeDOM({ chips })
380 // dispatch and focus as ProseMirror's are called: passed on bare,
381 // so they close over the view rather than trust `this`.
382 const view = { state, focused: 0 }
383 view.focus = () => {
384 view.focused++
385 }
386 view.dispatch = (tr) => {
387 view.state = view.state.apply(tr)
388 }
389 let menu = null
390 const toolbar = createToolbar({
391 root: dom.toolbarRoot,
392 history: dom.historyRoots,
393 schema,
394 ...(refocus ? { refocus } : {}),
395 getView: () => view,
396 onSync: (v) => {
397 if (menu) menu.sync(v)
398 },
399 })
400 menu = mountMenu(dom.menuRoot, {
401 getView: () => view,
402 commands: toolbar.commands,
403 isPressed: (name, v) => toolbar.isPressed(v.state, name),
404 })
405 assert.ok(menu, 'the menu bar should have mounted')
406 const pluginView = toolbar.plugin.spec.view(view)
407 return {
408 dom,
409 view,
410 commands: toolbar.commands,
411 to(next) {
412 view.state = next
413 pluginView.update(view)
414 },
415 }
416}
417
418// A document in a monospace 24pt italic heading, with the selection
419// across it — several of the chrome's controls saying something
420// different from what they say over an empty paragraph.
421function headingState() {
422 const text = schema.text('Title', [
423 schema.marks.em.create(),
424 schema.marks.font_mono.create(),
425 schema.marks.size_24.create(),
426 ])
427 const doc = schema.node('doc', null, [schema.node('heading', { level: 1 }, [text])])
428 return EditorState.create({ doc, selection: TextSelection.create(doc, 1, 6) })
429}
430
431test('a state update that changes nothing writes nothing to the chrome', () => {
432 const state = EditorState.create({ schema })
433 const bar = mount(state)
434
435 // The mount itself must write: the chrome arrives disabled and
436 // unpressed and the first sync is what turns it on. Asserted, on both
437 // bars, so this test cannot pass by the recorder seeing nothing at
438 // all, or by one of the two bars never having been driven.
439 assert.ok(bar.dom.log.length > 0, 'the first sync should have written to the chrome')
440 assert.equal(bar.dom.byId('strong').disabled, false)
441 assert.equal(bar.dom.byId('menu-strong').disabled, false)
442 assert.equal(bar.dom.byId('menu-print').disabled, false)
443 // The current paragraph style is checked and enabled.
444 assert.equal(bar.dom.byId('menu-block_paragraph').getAttribute('aria-pressed'), 'true')
445 assert.equal(bar.dom.byId('menu-block_paragraph').disabled, false)
446
447 bar.dom.log.length = 0
448
449 // An empty transaction: a new EditorState with the same document, the
450 // same selection and the same stored marks. ProseMirror delivers one
451 // of these for every meta-only change — and delivers a whole run of
452 // updates whose visible answer is identical while somebody types.
453 bar.to(state.apply(state.tr))
454
455 assert.deepEqual(bar.dom.log, [])
456})
457
458test('a state update that changes something still writes it', () => {
459 // The counterweight to the test above, which "write nothing, ever"
460 // would also pass. Whatever the chrome stops writing, it must go on
461 // writing everything a person can see change.
462 const bar = mount(EditorState.create({ schema }))
463 bar.dom.log.length = 0
464 bar.to(headingState())
465
466 assert.deepEqual(bar.dom.writesTo('em', 'aria-pressed'), ['true'])
467 // And the menu's check column moves with the selection.
468 assert.deepEqual(bar.dom.writesTo('menu-block_heading-1', 'aria-pressed'), ['true'])
469 assert.deepEqual(bar.dom.writesTo('menu-block_paragraph', 'aria-pressed'), ['false'])
470 assert.deepEqual(bar.dom.writesTo('docs-select-block', 'value'), ['heading-1'])
471 assert.deepEqual(bar.dom.writesTo('docs-select-font', 'value'), ['mono'])
472 assert.deepEqual(bar.dom.writesTo('docs-select-size', 'value'), ['24'])
473 // The combobox is the control a person actually reads. select.value
474 // moves no pixel on its own — see showInCombo.
475 assert.deepEqual(bar.dom.writesTo('block-combo', 'value'), ['Heading 1'])
476 assert.deepEqual(bar.dom.writesTo('font-combo', 'value'), ['Mono'])
477 assert.deepEqual(bar.dom.writesTo('size-combo', 'value'), ['24'])
478 // The menu bar too: Clear formatting has nothing to strip over an
479 // empty selection and becomes available once there is one.
480 assert.deepEqual(bar.dom.writesTo('menu-clear_formatting', 'disabled'), [false])
481
482 // And the chrome afterwards says so, which is the thing the redundant
483 // writes were never changing.
484 assert.equal(bar.dom.byId('em').getAttribute('aria-pressed'), 'true')
485 assert.equal(bar.dom.byId('strong').getAttribute('aria-pressed'), 'false')
486 assert.equal(bar.dom.byId('docs-select-block').value, 'heading-1')
487 assert.equal(bar.dom.byId('size-combo').value, '24')
488 assert.equal(bar.dom.byId('menu-clear_formatting').disabled, false)
489})
490
491// The two tests above drive the controls views/show.html renders today.
492// A control added later that this fake does not carry would slip past
493// them — which is the failure mode that took the count from 12 to 23,
494// and then reproduced the whole defect in a second module. So the rule
495// is held against the source as well: neither bar writes to the DOM
496// directly. Every write goes through fixtures/dom-writes.mjs.
497//
498// Two named files rather than a rule over every module that touches the
499// DOM, deliberately. Plenty of modules here write to elements and
500// should — pages.mjs stamps page numbers, wordcount.mjs writes a count,
501// jump-to.mjs builds a palette — and none of them runs on every editor
502// state update. These two do, both from the one plugin, which is what
503// makes a redundant write here cost a frame. Add a third surface to
504// that plugin and add it to this list.
505//
506// THIS CHECK IS THE SECOND NET, NOT THE FIRST. It reads text, and a
507// text rule over JavaScript is approximate in a way the recording fake
508// is not: the stripper below does not parse string literals, so a `//`
509// inside a string blanks the rest of that line and any write after it
510// on the same line becomes invisible here. That is a false PASS, not
511// merely a false positive, and it was found in review by a probe that
512// hid a write behind 'https://' — see makeDOM's own header. The fake's
513// Proxy is what catches that class; this check earns its place on a
514// different one, the control added later that the fake does not carry.
515// Neither is sufficient alone.
516const GUARDED = ['toolbar.mjs', 'menu.mjs']
517
518const WRITE =
519 /\.(?:setAttribute|removeAttribute)\s*\(|\.(?:disabled|value|checked|textContent|innerHTML|className|tabIndex|hidden|title)[ \t]*=(?!=)/g
520
521// Comments go to spaces rather than away, so offsets and line numbers
522// still point at the real file. Both modules' comments discuss the very
523// writes being looked for, at length and by name.
524//
525// It handles // and /* */ and nothing else — in particular it does not
526// know a string literal from code, which is the hole described above.
527// Left as it is deliberately: a stripper that got strings, template
528// literals and regex literals right would be a small parser, and the
529// recording fake already covers what this misses.
530function stripComments(src) {
531 let out = ''
532 let i = 0
533 while (i < src.length) {
534 if (src.startsWith('//', i)) {
535 while (i < src.length && src[i] !== '\n') {
536 out += ' '
537 i++
538 }
539 } else if (src.startsWith('/*', i)) {
540 const end = src.indexOf('*/', i + 2)
541 const stop = end < 0 ? src.length : end + 2
542 for (; i < stop; i++) out += src[i] === '\n' ? '\n' : ' '
543 } else {
544 out += src[i]
545 i++
546 }
547 }
548 return out
549}
550
551function sourceOf(file) {
552 return stripComments(readFileSync(new URL('./' + file, import.meta.url), 'utf8'))
553}
554
555test('no DOM write in either bar bypasses dom-writes.mjs', () => {
556 for (const file of GUARDED) {
557 const code = sourceOf(file)
558 // ok() rather than match(): a failing match() prints the whole
559 // stripped module, which buries the one line that matters.
560 assert.ok(
561 code.includes("from './dom-writes.mjs'"),
562 `${file} should get its writers from dom-writes.mjs`,
563 )
564 const stray = []
565 for (const m of code.matchAll(WRITE)) {
566 stray.push(
567 `${file}:${code.slice(0, m.index).split('\n').length}: ${code
568 .slice(m.index, m.index + 40)
569 .trim()}`,
570 )
571 }
572 assert.deepEqual(stray, [])
573 }
574})
575
576// Undo and redo live in two pairs outside the toolbar (spec I2, P1.2 and
577// C6): the bar's lead slot's and the strip's. Both are bound and kept
578// current, so whichever is on screen says what undo would do; neither is
579// in the toolbar's roving tab stop, which would park the bar's one stop on
580// a button that is not drawn.
581test('both undo/redo pairs are synced and neither is in the roving tab stop', () => {
582 const state = EditorState.create({ schema })
583 const bar = mount(state)
584 for (const id of ['lead-undo', 'lead-redo', 'strip-undo', 'strip-redo']) {
585 // Nothing to undo in a fresh state: the first sync disables it.
586 assert.deepEqual(bar.dom.writesTo(id, 'disabled'), [true], id + ' was not synced')
587 // And it is not a toggle: undo has no pressed state to announce.
588 assert.equal(bar.dom.byId(id).getAttribute('aria-pressed'), null, id + ' was given aria-pressed')
589 assert.deepEqual(bar.dom.writesTo(id, 'tabIndex'), [], id + ' was given a roving tabindex')
590 }
591 // And the roving did run, over the toolbar's own controls.
592 assert.ok(bar.dom.writesTo('strong', 'tabIndex').length > 0 || bar.dom.writesTo('block-combo', 'tabIndex').length > 0, 'the roving tab stop was never set')
593})
594
595// The roving tab stop walks the bar in its reading order (spec I2, P1.2):
596// the three pickers that open it (the inspector's Style section), then
597// the buttons, as the DOM has them. It used to walk buttons first, which
598// only matched the screen while undo and redo opened the bar (review on
599// #106: the change had no test).
600test('the arrow keys walk the bar in reading order: the pickers, then the buttons', () => {
601 const bar = mount(EditorState.create({ schema }))
602 const reading = ['block-combo', 'font-combo', 'size-combo', 'strong', 'em', 'code', 'align_left', 'align_center', 'align_right', 'bullet_list', 'ordered_list', 'blockquote']
603 const want = reading.filter((id) => !bar.dom.byId(id).disabled)
604 assert.deepEqual(want.slice(0, 3), ['block-combo', 'font-combo', 'size-combo'], 'a picker is disabled, so this would not see the order')
605 assert.ok(want.length >= 8, 'too few controls enabled to read an order from')
606 // From Home: the walk wraps, so starting at the first picker would see
607 // any rotation of the right order as the right order.
608 bar.dom.byId(want[want.length - 1]).focus()
609 bar.dom.toolbarHandlers.keydown({ key: 'Home', preventDefault() {} })
610 const walked = []
611 for (let i = 0; i < want.length; i++) {
612 walked.push(globalThis.document.activeElement.id)
613 bar.dom.toolbarHandlers.keydown({ key: 'ArrowRight', preventDefault() {} })
614 }
615 assert.deepEqual(walked, want)
616 assert.equal(globalThis.document.activeElement.id, want[0], 'ArrowRight from the last control did not wrap to the first')
617})
618
619// The phone's Format sheet (design/phone-web, P2; Fable's review 10 on
620// #181). The size steps walk SIZES in order and stop at its ends; called
621// with no dispatch they only say whether they would act.
622function sizedState(pt) {
623 const marks = pt === 12 ? [] : [schema.marks[sizeMark(pt)].create()]
624 const doc = schema.node('doc', null, [schema.node('paragraph', null, [schema.text('Some words', marks)])])
625 return EditorState.create({ doc, selection: TextSelection.create(doc, 1, 11) })
626}
627const sizeAt = (state) => sizeForMarks(state.doc.firstChild.firstChild.marks.map((m) => m.type.name))
628
629test('the size steps walk the ladder one size at a time and stop at its ends', () => {
630 const { commands } = mount(EditorState.create({ schema }))
631 const ladder = [...SIZES].sort((a, b) => a - b)
632 for (const [from, cmd, to] of [[12, 'size_up', 14], [12, 'size_down', 11], [8, 'size_up', 9], [72, 'size_down', 48]]) {
633 let next = null
634 assert.equal(commands[cmd](sizedState(from), (tr) => { next = sizedState(from).apply(tr) }), true, `${cmd} from ${from}`)
635 assert.equal(sizeAt(next), to, `${cmd} from ${from}`)
636 }
637 for (const [at, cmd] of [[ladder[0], 'size_down'], [ladder[ladder.length - 1], 'size_up']]) {
638 let dispatched = false
639 assert.equal(commands[cmd](sizedState(at), () => { dispatched = true }), false, `${cmd} at ${at}, the ladder's end`)
640 assert.equal(dispatched, false)
641 }
642 // A dry run: the answer, and nothing done.
643 const state = sizedState(12)
644 assert.equal(commands.size_up(state), true)
645 assert.equal(commands.size_up(state, null), true)
646 assert.equal(sizeAt(state), 12)
647 assert.equal(commands.size_up(sizedState(72)), false)
648})
649
650test('a control hands the caret back to the document only where refocus says so', () => {
651 for (const [refocus, want] of [[() => true, 1], [() => false, 0]]) {
652 const bar = mount(sizedState(12), { refocus })
653 bar.dom.byId('strong').emit('click')
654 assert.equal(bar.view.focused, want, `refocus() ${refocus()}`)
655 assert.ok(bar.view.state.doc.firstChild.firstChild.marks.some((m) => m.type.name === 'strong'), 'B did not act')
656 }
657})
658
659test('a style chip is pressed for the style the selection is in', () => {
660 const heading = schema.node('doc', null, [schema.node('heading', { level: 2 }, [schema.text('A heading')])])
661 const bar = mount(sizedState(12), { chips: true })
662 assert.equal(bar.dom.byId('block_paragraph').getAttribute('aria-pressed'), 'true')
663 assert.equal(bar.dom.byId('block_heading-2').getAttribute('aria-pressed'), 'false')
664 bar.to(EditorState.create({ doc: heading, selection: TextSelection.create(heading, 1, 3) }))
665 assert.equal(bar.dom.byId('block_paragraph').getAttribute('aria-pressed'), 'false')
666 assert.equal(bar.dom.byId('block_heading-2').getAttribute('aria-pressed'), 'true')
667 // And a chip applies its style.
668 bar.dom.byId('block_paragraph').emit('click')
669 assert.equal(bar.view.state.doc.firstChild.type.name, 'paragraph')
670})
671