oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/dom-stub.mjs — the smallest DOM the tests need, and only
2// the tests: nothing in the bundle imports it (build-bundles.mjs walks
3// from editor-entry.js, which does not).
4//
5// It exists because two of the rules this project cares about are DOM
6// rules and neither can be checked without one: that the Outline's list
7// keeps the SAME button elements across a fill (so focus survives a
8// colleague's keystroke), and that a mount's listeners are actually
9// gone after destroy() (so a resync does not leave a second copy of
10// every handler on the page's own elements). Both are about node
11// identity and listener count, which is exactly what a stub can answer
12// and what a headless browser answers slowly. Events bubble through
13// dispatchEvent, and focus() is heard as a focusin, so the stage's tab
14// stops (stage-focus.mjs) can be driven too.
15//
16// It is not a DOM. Selectors are a list of compounds of attributes,
17// present or equal to a value, with an optional tag —
18// `[data-select-block]`, `[slides-block][data-id="b1"], [x]` — because
19// that is all the code under test asks for; no combinators.
20
21class StubElement {
22 constructor (tag = 'div') {
23 this.tagName = tag.toUpperCase()
24 this.attrs = new Map()
25 this.children = []
26 this.parentNode = null
27 this.dataset = {}
28 this.listeners = []
29 this.text = ''
30 this.hidden = false
31 this.type = ''
32 }
33
34 get textContent () {
35 if (this.children.length) return this.children.map(c => c.textContent).join('')
36 return this.text
37 }
38
39 set textContent (v) {
40 // The real thing replaces every child with one text node — which
41 // is why the code under test avoids writing it when it need not.
42 this.children = []
43 this.text = String(v)
44 }
45
46 setAttribute (name, value) { this.attrs.set(name, String(value)) }
47 getAttribute (name) { return this.attrs.has(name) ? this.attrs.get(name) : null }
48 hasAttribute (name) { return this.attrs.has(name) }
49 removeAttribute (name) { this.attrs.delete(name) }
50
51 get firstElementChild () { return this.children[0] || null }
52 get nextElementSibling () {
53 if (!this.parentNode) return null
54 const at = this.parentNode.children.indexOf(this)
55 return this.parentNode.children[at + 1] || null
56 }
57
58 append (...nodes) {
59 for (const n of nodes) {
60 n.remove()
61 n.parentNode = this
62 this.children.push(n)
63 }
64 }
65
66 insertBefore (node, ref) {
67 node.remove()
68 node.parentNode = this
69 const at = ref ? this.children.indexOf(ref) : -1
70 if (at < 0) this.children.push(node)
71 else this.children.splice(at, 0, node)
72 return node
73 }
74
75 remove () {
76 if (!this.parentNode) return
77 // A browser blurs the focused element when it (or an ancestor)
78 // leaves the tree — which is what moving a node does, and what
79 // strip.mjs's sync has to put right afterwards.
80 const doc = globalThis.document
81 if (doc && doc.activeElement && this.contains(doc.activeElement)) doc.activeElement = null
82 const at = this.parentNode.children.indexOf(this)
83 if (at >= 0) this.parentNode.children.splice(at, 1)
84 this.parentNode = null
85 }
86
87 // Focus is heard as the browser says it: a focusin that bubbles.
88 focus () {
89 if (globalThis.document) globalThis.document.activeElement = this
90 this.dispatchEvent({ type: 'focusin', target: this })
91 }
92
93 // An attribute's value, a data-* one read from dataset first (el()
94 // writes both; code under test often writes dataset alone).
95 attrValue (name) {
96 if (name.startsWith('data-')) {
97 const key = name.slice(5).replace(/-([a-z])/g, (m, c) => c.toUpperCase())
98 if (this.dataset[key] !== undefined) return String(this.dataset[key])
99 }
100 return this.attrs.has(name) ? this.attrs.get(name) : null
101 }
102
103 matches (selector) {
104 // A list of compounds, each an optional tag and attributes, present
105 // or equal to a quoted value: `button[data-a]`, `[x="y"], [z]`.
106 const parts = selector.split(',').map(s => s.trim().match(/^([a-z0-9]*)((?:\[[^\]=]+(?:="[^"]*")?\])+)$/i))
107 if (parts.every(Boolean)) {
108 return parts.some(([, tag, attrs]) => {
109 if (tag && this.tagName !== tag.toUpperCase()) return false
110 return [...attrs.matchAll(/\[([^\]=]+)(?:="([^"]*)")?\]/g)].every(([, name, value]) => {
111 const v = this.attrValue(name)
112 return value === undefined ? v !== null : v === value
113 })
114 })
115 }
116 const name = selector.replace(/^\[|\]$/g, '')
117 if (name.startsWith('data-')) {
118 const key = name.slice(5).replace(/-([a-z])/g, (m, c) => c.toUpperCase())
119 return this.dataset[key] !== undefined
120 }
121 return this.attrs.has(name)
122 }
123
124 // Bubbles from here to the root, as a DOM event does; the event is a
125 // plain object the test makes ({type, key, shiftKey, …}), given a
126 // target and a preventDefault() if it has none.
127 dispatchEvent (ev) {
128 if (!ev.target) ev.target = this
129 if (!ev.preventDefault) ev.preventDefault = () => { ev.defaultPrevented = true }
130 if (!ev.stopPropagation) ev.stopPropagation = () => { ev.stopped = true }
131 for (let n = this; n && !ev.stopped; n = n.parentNode) {
132 for (const l of [...n.listeners]) if (l.type === ev.type) l.fn(ev)
133 }
134 return !ev.defaultPrevented
135 }
136
137 descendants () {
138 return this.children.flatMap(c => [c, ...c.descendants()])
139 }
140
141 querySelectorAll (selector) {
142 return this.descendants().filter(el => el.matches(selector))
143 }
144
145 querySelector (selector) {
146 return this.querySelectorAll(selector)[0] || null
147 }
148
149 contains (el) {
150 return el === this || this.descendants().includes(el)
151 }
152
153 closest (selector) {
154 for (let el = this; el; el = el.parentNode) if (el.matches(selector)) return el
155 return null
156 }
157
158 // The whole point of the listener half: {signal} has to work, or a
159 // destroy() built on AbortController would test as passing while
160 // leaving every handler in place.
161 addEventListener (type, fn, opts = {}) {
162 const entry = { type, fn }
163 this.listeners.push(entry)
164 if (opts && opts.signal) {
165 opts.signal.addEventListener('abort', () => {
166 const at = this.listeners.indexOf(entry)
167 if (at >= 0) this.listeners.splice(at, 1)
168 })
169 }
170 }
171
172 removeEventListener (type, fn) {
173 const at = this.listeners.findIndex(l => l.type === type && l.fn === fn)
174 if (at >= 0) this.listeners.splice(at, 1)
175 }
176
177 countListeners (type) {
178 return this.listeners.filter(l => l.type === type).length
179 }
180}
181
182/** A stub element, optionally with attributes and children. */
183export function el (tag = 'div', attrs = {}, children = []) {
184 const node = new StubElement(tag)
185 for (const [k, v] of Object.entries(attrs)) {
186 if (k.startsWith('data-')) node.dataset[k.slice(5).replace(/-([a-z])/g, (m, c) => c.toUpperCase())] = String(v)
187 node.setAttribute(k, v)
188 }
189 node.append(...children)
190 return node
191}
192
193/**
194 * Installs a stub `document` on globalThis for the duration of a test
195 * and returns it plus the undo. Only what the modules under test reach
196 * for: createElement, and activeElement (nothing focused).
197 */
198export function withDocument () {
199 const before = globalThis.document
200 const doc = el('html')
201 doc.createElement = tag => new StubElement(tag)
202 doc.activeElement = null
203 globalThis.document = doc
204 return { document: doc, restore () { globalThis.document = before } }
205}
206