rails-jsdom 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,7 @@ const { createRequire } = require("node:module")
8
8
 
9
9
  const STUB_NAMESPACE = "rails-jsdom-stub"
10
10
  const STUB_SOURCE = "module.exports = Object.create(new Proxy({}, { get: (target, key) => typeof key === 'symbol' || key === 'then' || key === '__esModule' ? undefined : () => {} }))"
11
+ const STIMULUS_LOADING = "@hotwired/stimulus-loading"
11
12
  const INLINE_ELEMENTS = new Set(["a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "dfn", "em", "i", "kbd", "label", "mark", "output", "q", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var"])
12
13
  const CLICKABLE = "button, input[type=submit], input[type=button], input[type=reset], input[type=image], input[type=checkbox], input[type=radio], a[href], summary, label, [role=button]"
13
14
  const BUTTON_INPUTS = "input[type=submit], input[type=button], input[type=reset], input[type=image]"
@@ -20,11 +21,13 @@ const QUERY_KINDS = { css: "*", field: FIELDS, button: KINDS.button, link: KINDS
20
21
  const FOCUSABLE = "a[href], button, input:not([type=hidden]), select, textarea, [tabindex], [contenteditable]"
21
22
  const PRESSABLE = "button, input[type=checkbox], input[type=radio], input[type=submit], input[type=button], input[type=reset]"
22
23
  const STEPPABLE = "input[type=range], input[type=number]"
23
- const KEYS = { enter: "Enter", tab: "Tab", backspace: "Backspace", delete: "Delete", escape: "Escape", space: " ", left: "ArrowLeft", right: "ArrowRight", up: "ArrowUp", down: "ArrowDown", home: "Home", end: "End", page_up: "PageUp", page_down: "PageDown" }
24
+ const KEYS = { enter: "Enter", return: "Enter", tab: "Tab", backspace: "Backspace", delete: "Delete", escape: "Escape", space: " ", left: "ArrowLeft", right: "ArrowRight", up: "ArrowUp", down: "ArrowDown", home: "Home", end: "End", page_up: "PageUp", page_down: "PageDown", arrow_left: "ArrowLeft", arrow_right: "ArrowRight", arrow_up: "ArrowUp", arrow_down: "ArrowDown" }
24
25
  const MODIFIERS = { shift: "shiftKey", control: "ctrlKey", ctrl: "ctrlKey", alt: "altKey", meta: "metaKey", command: "metaKey" }
25
26
  const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])
26
27
  const SETTLE_LIMIT = 10000
27
- const STREAM_SOURCES = "turbo-cable-stream-source[signed-stream-name][channel='Turbo::StreamsChannel'], turbo-cable-stream-source[signed-stream-name]:not([channel])"
28
+ const MEASUREMENT_LIMIT = 10000
29
+ const LAYOUT_LOOP = `RailsJsdom: the page measured element positions ${MEASUREMENT_LIMIT} times without its event loop moving on. jsdom has no layout, so every element and range measures 0x0 at 0,0, and code that waits for a real measurement, such as positioning a menu or popover at the caret, never gets one and repeats forever. If the test does not depend on where things are, give the elements involved a box with stub_layout in that test; otherwise test this behaviour in a system test.`
30
+ const LOADABLE = "link[rel~=stylesheet], img[src]:not([src=\"\"])"
28
31
 
29
32
  const replies = new Map()
30
33
  const fetchStubs = new Map()
@@ -33,18 +36,29 @@ const errors = []
33
36
  const owners = new WeakMap()
34
37
  let nextFetchId = 1
35
38
  let nextPageId = 1
39
+ let nextObjectUrl = 1
40
+ let nextSocketId = 1
41
+ let measurements = 0
42
+ const time = { now: 0, epoch: 0, target: null, deadline: null }
43
+ let inbox = []
36
44
  let config = null
37
45
  let jsdom = null
46
+ let wrappers = null
38
47
  let bundle = null
39
48
  let page = null
40
49
  const sessions = new Map()
41
50
  let session = sessionNamed("default")
42
51
  let modal = null
43
52
  let modalMessages = []
53
+ let chooser = null
54
+ const requests = new WeakMap()
44
55
 
45
56
  let output = null
46
- const send = message => output.write(`${JSON.stringify(message)}\n`)
57
+ const send = message => output.write(`${JSON.stringify({ ...message, clock: time.now })}\n`)
47
58
  const tick = () => new Promise(resolve => setTimeout(resolve, 0))
59
+ let typing = 0
60
+ const turn = () => new Promise(resolve => setImmediate(resolve))
61
+ const pause = busy => (busy ? turn() : tick())
48
62
  const normalize = text => String(text ?? "").replace(/\s+/g, " ").trim()
49
63
 
50
64
  let queue = Promise.resolve()
@@ -59,6 +73,7 @@ function start(io) {
59
73
  input.on("line", line => {
60
74
  const message = JSON.parse(line)
61
75
  if (message.type === "fetch_response") {
76
+ if (message.sync) applySync(message.sync)
62
77
  const resolve = replies.get(message.id)
63
78
  replies.delete(message.id)
64
79
  resolve(message.response)
@@ -88,10 +103,12 @@ const READS = {
88
103
  read: message => describe(elementFor(message.handle)),
89
104
  session: message => switchSession(message.name),
90
105
  stub_fetch: message => stubFetch(message.url, message.response),
106
+ stub_layout: message => stubLayout(message.selector, message.box),
91
107
  reset: () => reset(),
92
- streams: () => streams(),
93
108
  expect_modal: message => expectModal(message),
94
- modal_messages: () => takeModalMessages()
109
+ modal_messages: () => takeModalMessages(),
110
+ expect_file_chooser: message => expectFileChooser(message.files),
111
+ file_chooser_opened: () => takeFileChooser()
95
112
  }
96
113
 
97
114
  const ACTIONS = {
@@ -108,25 +125,45 @@ const ACTIONS = {
108
125
  send_keys: message => sendKeys(null, message.keys),
109
126
  element: message => elementAction(message),
110
127
  traverse: message => traverse(message.delta),
111
- evaluate: message => evaluate(message.script),
112
- deliver: message => deliver(message.messages)
128
+ evaluate: message => evaluate(message),
129
+ settle: () => null,
130
+ catch_up: null
113
131
  }
114
132
 
115
133
  async function perform(message) {
134
+ if (message.sync) applySync(message.sync)
116
135
  if (READS[message.command]) return READS[message.command](message)
117
- if (!ACTIONS[message.command]) throw new Error(`RailsJsdom: unknown command ${message.command}`)
136
+ if (!Object.hasOwn(ACTIONS, message.command)) throw new Error(`RailsJsdom: unknown command ${message.command}`)
118
137
  errors.length = 0
119
- const value = await ACTIONS[message.command](message)
120
- await settle()
138
+ await catchUp()
139
+ const value = ACTIONS[message.command] ? await act(ACTIONS[message.command], message) : null
121
140
  if (errors.length > 0) throw new Error(errors.splice(0).map(describeError).join("\n\n"))
122
141
  return value === undefined ? null : JSON.parse(JSON.stringify(value) ?? "null")
123
142
  }
124
143
 
144
+ async function act(action, message) {
145
+ let state = "running"
146
+ const outcome = Promise.resolve().then(() => action(message)).then(value => { state = "done"; return value }, error => { state = "failed"; throw error })
147
+ outcome.catch(() => {})
148
+ await settle(() => state, config.horizon)
149
+ return await outcome
150
+ }
151
+
152
+ async function catchUp() {
153
+ if (page && (inbox.length > 0 || time.target !== null || page.clock.due(time.now))) await settle(() => "done", 0)
154
+ }
155
+
125
156
  function stubFetch(url, response) {
126
157
  fetchStubs.set(url, response)
127
158
  return null
128
159
  }
129
160
 
161
+ function stubLayout(selector, box) {
162
+ if (!page) throw new Error("RailsJsdom: visit a page or mount a partial first")
163
+ page.layoutStubs.push({ selector, box })
164
+ return null
165
+ }
166
+
130
167
  function loadFresh(html, url, history) {
131
168
  fetchStubs.clear()
132
169
  return load(html, url, history)
@@ -136,6 +173,7 @@ async function setup(message) {
136
173
  config = message
137
174
  const appRequire = createRequire(path.join(config.root, "package.json"))
138
175
  jsdom = appRequire("jsdom")
176
+ wrappers = appRequire("jsdom/lib/generated/idl/utils.js")
139
177
  const esbuild = appRequire("esbuild")
140
178
  const result = await esbuild.build({
141
179
  stdin: { contents: entrySource(), resolveDir: config.root, sourcefile: "rails-jsdom-entry.js", loader: "js" },
@@ -167,7 +205,8 @@ function entrySource() {
167
205
  "import \"@hotwired/turbo-rails\"",
168
206
  "export { Application } from \"@hotwired/stimulus\"",
169
207
  ...files.map(([, file], index) => `import controller${index} from ${JSON.stringify(file)}`),
170
- `export const controllers = { ${files.map(([relative], index) => `${JSON.stringify(identifierFor(relative))}: controller${index}`).join(", ")} }`
208
+ `export const controllers = { ${files.map(([relative], index) => `${JSON.stringify(identifierFor(relative))}: controller${index}`).join(", ")} }`,
209
+ ...(config.modules.application ? ["import \"application\""] : [])
171
210
  ].join("\n")
172
211
  }
173
212
 
@@ -175,32 +214,41 @@ function importmapPlugin() {
175
214
  return {
176
215
  name: "rails-jsdom-importmap",
177
216
  setup(build) {
178
- build.onResolve({ filter: /^[^./]/ }, args => resolveImport(args.path))
217
+ build.onResolve({ filter: /^[^./]/ }, args => resolveImport(args.path) ?? unresolvedImport(args))
179
218
  build.onLoad({ filter: /.*/, namespace: STUB_NAMESPACE }, () => ({ contents: STUB_SOURCE, loader: "js" }))
180
219
  }
181
220
  }
182
221
  }
183
222
 
223
+ function unresolvedImport(args) {
224
+ return args.kind === "dynamic-import" ? { path: args.path, external: true } : undefined
225
+ }
226
+
184
227
  function resolveImport(specifier) {
185
228
  const directory = Object.keys(config.directories).find(prefix => specifier.startsWith(`${prefix}/`))
186
- if (config.stubs.includes(specifier)) return { path: specifier, namespace: STUB_NAMESPACE }
229
+ if (specifier === STIMULUS_LOADING || config.stubs.includes(specifier)) return { path: specifier, namespace: STUB_NAMESPACE }
187
230
  if (config.modules[specifier]) return { path: config.modules[specifier] }
231
+ if (config.directories[specifier]) return { path: path.join(config.directories[specifier], "index.js") }
188
232
  if (directory) return { path: `${path.join(config.directories[directory], specifier.slice(directory.length + 1))}.js` }
189
233
  return undefined
190
234
  }
191
235
 
192
236
  class Clock {
193
237
  constructor() {
194
- this.now = 0
195
238
  this.sequence = 0
196
239
  this.timers = new Map()
197
240
  }
198
241
 
242
+ get now() {
243
+ return time.now
244
+ }
245
+
199
246
  install(window) {
200
247
  window.setTimeout = (callback, delay, ...args) => this.schedule(callback, delay, args, false)
201
248
  window.setInterval = (callback, delay, ...args) => this.schedule(callback, delay, args, true)
202
249
  window.requestAnimationFrame = callback => this.schedule(() => callback(this.now), 0, [], false)
203
250
  window.clearTimeout = window.clearInterval = window.cancelAnimationFrame = id => { this.timers.delete(id) }
251
+ addVirtualTime(window)
204
252
  }
205
253
 
206
254
  schedule(callback, delay, args, repeat) {
@@ -220,7 +268,8 @@ class Clock {
220
268
  }
221
269
 
222
270
  run([id, timer]) {
223
- this.now = timer.at
271
+ measurements = 0
272
+ time.now = Math.max(time.now, timer.at)
224
273
  if (timer.every) {
225
274
  this.sequence += 1
226
275
  timer.at += timer.every
@@ -236,27 +285,148 @@ class Clock {
236
285
  }
237
286
  }
238
287
 
239
- async function settle() {
288
+ async function settle(status, ahead) {
240
289
  let idle = 0
241
- let current = null
242
- let limit = 0
290
+ let horizon = null
291
+ let progress = 0
243
292
  for (let round = 0; idle < 3; round += 1) {
244
- if (round > SETTLE_LIMIT) throw new Error("RailsJsdom: the page did not settle")
245
- await tick()
246
- if (current !== page) {
247
- current = page
248
- limit = page.clock.now + config.horizon
293
+ if (progress > SETTLE_LIMIT) throw notSettled()
294
+ await pause(idle === 0 && round > 0)
295
+ if (status() === "failed" || !page) return
296
+ horizon = horizonFor(horizon, ahead)
297
+ const busy = await advance(reachable(horizon))
298
+ progress += Number(busy)
299
+ idle = busy || status() !== "done" ? 0 : idle + 1
300
+ }
301
+ reachTarget()
302
+ }
303
+
304
+ function reachable(horizon) {
305
+ return typing > 0 ? -Infinity : horizon.limit
306
+ }
307
+
308
+ function notSettled() {
309
+ return new Error("RailsJsdom: the page did not settle")
310
+ }
311
+
312
+ function horizonFor(previous, ahead) {
313
+ const limit = previous && previous.page === page ? previous.limit : time.now + ahead
314
+ return { page, limit: Math.max(limit, time.target ?? limit) }
315
+ }
316
+
317
+ async function advance(limit) {
318
+ measurements = 0
319
+ if (pending.size > 0) {
320
+ await Promise.race(pending)
321
+ return true
322
+ }
323
+ if (deliverInbox()) return true
324
+ const timer = page.clock.due(limit)
325
+ if (time.deadline !== null && time.deadline <= (timer ? timer[1].at : time.target ?? time.now)) {
326
+ await tickRails()
327
+ return true
328
+ }
329
+ if (timer) page.clock.run(timer)
330
+ return Boolean(timer)
331
+ }
332
+
333
+ function applySync(sync) {
334
+ time.epoch = sync.epoch
335
+ time.deadline = sync.deadline
336
+ if (sync.now > time.now) time.target = Math.max(time.target ?? sync.now, sync.now)
337
+ inbox.push(...sync.frames)
338
+ }
339
+
340
+ function reachTarget() {
341
+ if (time.target === null) return
342
+ time.now = Math.max(time.now, time.target)
343
+ time.target = null
344
+ }
345
+
346
+ function deliverInbox() {
347
+ if (inbox.length === 0) return false
348
+ for (const frame of inbox.splice(0)) deliverFrame(page.sockets.get(frame.socket), frame)
349
+ return true
350
+ }
351
+
352
+ async function tickRails() {
353
+ time.now = Math.max(time.now, time.deadline)
354
+ time.deadline = null
355
+ await requestRails({ kind: "cable", action: "tick" })
356
+ }
357
+
358
+ function deliverFrame(socket, frame) {
359
+ if (socket && frame.closed) socket.closed(frame.code)
360
+ else if (socket) socket.received(frame.data)
361
+ }
362
+
363
+ const socketContexts = new WeakMap()
364
+
365
+ function cableSocketClass(window, owner) {
366
+ class WebSocket extends window.EventTarget {
367
+ constructor(url, protocols = []) {
368
+ super()
369
+ socketContexts.set(this, { window, owner })
370
+ openSocket(this, socketUrl(window, url), [].concat(protocols))
249
371
  }
250
- const timer = page.clock.due(limit)
251
- if (pending.size > 0) {
252
- idle = 0
253
- await Promise.race(pending)
254
- } else if (timer) {
255
- idle = 0
256
- page.clock.run(timer)
372
+ }
373
+ Object.assign(WebSocket.prototype, SOCKET_METHODS)
374
+ return Object.assign(WebSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 })
375
+ }
376
+
377
+ function socketUrl(window, url) {
378
+ const resolved = new window.URL(url, window.location.href)
379
+ resolved.protocol = resolved.protocol.replace(/^http/, "ws")
380
+ return resolved.href
381
+ }
382
+
383
+ function openSocket(socket, url, protocols) {
384
+ Object.assign(socket, { url, readyState: 0, protocol: "", extensions: "", binaryType: "blob", bufferedAmount: 0, onopen: null, onmessage: null, onclose: null, onerror: null, id: `${process.pid}:${nextSocketId}` })
385
+ nextSocketId += 1
386
+ socketContexts.get(socket).owner.sockets.set(socket.id, socket)
387
+ requestRails({ kind: "cable", action: "open", socket: socket.id, url, protocols }).then(reply => socket.opened(reply))
388
+ }
389
+
390
+ const SOCKET_METHODS = {
391
+ opened(reply) {
392
+ const { window } = socketContexts.get(this)
393
+ if (this.readyState !== 0) return
394
+ if (reply.error) {
395
+ this.fire(new window.Event("error"))
396
+ this.closed(1006)
257
397
  } else {
258
- idle += 1
398
+ Object.assign(this, { readyState: 1, protocol: reply.protocol })
399
+ this.fire(new window.Event("open"))
259
400
  }
401
+ },
402
+
403
+ send(data) {
404
+ if (this.readyState !== 1) throw new (socketContexts.get(this).window.DOMException)("The WebSocket is not open", "InvalidStateError")
405
+ requestRails({ kind: "cable", action: "send", socket: this.id, data: String(data) })
406
+ },
407
+
408
+ close(code = 1000) {
409
+ if (this.readyState > 1) return
410
+ this.readyState = 2
411
+ requestRails({ kind: "cable", action: "close", socket: this.id }).then(() => this.closed(code))
412
+ },
413
+
414
+ received(data) {
415
+ if (this.readyState === 1) this.fire(new (socketContexts.get(this).window.MessageEvent)("message", { data }))
416
+ },
417
+
418
+ closed(code) {
419
+ const { window, owner } = socketContexts.get(this)
420
+ if (this.readyState === 3) return
421
+ this.readyState = 3
422
+ owner.sockets.delete(this.id)
423
+ this.fire(new window.CloseEvent("close", { code, wasClean: code === 1000 }))
424
+ },
425
+
426
+ fire(event) {
427
+ this.dispatchEvent(event)
428
+ const handler = this[`on${event.type}`]
429
+ if (typeof handler === "function") handler.call(this, event)
260
430
  }
261
431
  }
262
432
 
@@ -277,7 +447,7 @@ function requestRails(request) {
277
447
  }
278
448
 
279
449
  function sessionNamed(name) {
280
- if (!sessions.has(name)) sessions.set(name, { page: null, back: [], forward: [] })
450
+ if (!sessions.has(name)) sessions.set(name, { page: null, back: [], forward: [], storage: { localStorage: new Map(), sessionStorage: new Map() } })
281
451
  return sessions.get(name)
282
452
  }
283
453
 
@@ -289,8 +459,9 @@ function switchSession(name) {
289
459
 
290
460
  function load(html, url, history = "push") {
291
461
  const previous = page
462
+ if (previous) keepStorage(previous.window, session.storage)
292
463
  if (history === "push" && previous) pushHistory(previous.window.location.href)
293
- const current = { id: nextPageId, clock: new Clock(), closed: false, position: 0, length: 1, handles: new Map(), ids: new WeakMap(), nextHandle: 0, edited: new Map() }
464
+ const current = { id: nextPageId, clock: new Clock(), closed: false, position: 0, length: 1, handles: new Map(), ids: new WeakMap(), nextHandle: 0, edited: new Map(), sockets: new Map(), layoutStubs: [] }
294
465
  nextPageId += 1
295
466
  const report = error => { if (page === current) errors.push(error) }
296
467
  session.page = current
@@ -317,44 +488,87 @@ function pushHistory(url) {
317
488
  function pageConsole(report) {
318
489
  const virtualConsole = new jsdom.VirtualConsole()
319
490
  virtualConsole.forwardTo(console, { jsdomErrors: "none" })
320
- virtualConsole.on("jsdomError", report)
491
+ virtualConsole.on("jsdomError", error => { if (error.type !== "css-parsing") report(error) })
321
492
  return virtualConsole
322
493
  }
323
494
 
324
- async function evaluate(script) {
325
- return await page.window.eval(script)
495
+ async function evaluate(message) {
496
+ if (message.kind === undefined) return await page.window.eval(message.script)
497
+ const body = message.kind === "expression" ? `return (${message.script}\n)` : message.script
498
+ const receiver = message.receiver === null ? page.window : elementFor(message.receiver)
499
+ return await new page.window.Function(body).apply(receiver, message.args.map(scriptArgument))
500
+ }
501
+
502
+ function scriptArgument(value) {
503
+ return value !== null && typeof value === "object" && "rails_jsdom_element" in value ? elementFor(value.rails_jsdom_element) : value
326
504
  }
327
505
 
328
506
  function reset() {
329
- for (const each of sessions.values()) if (each.page) close(each.page)
507
+ for (const each of sessions.values()) if (each.page) close(each.page, false)
330
508
  sessions.clear()
331
509
  session = sessionNamed("default")
332
510
  page = null
333
511
  modal = null
334
512
  modalMessages = []
513
+ chooser = null
335
514
  errors.length = 0
336
515
  fetchStubs.clear()
337
516
  replies.clear()
338
517
  pending.clear()
518
+ inbox = []
519
+ Object.assign(time, { now: 0, epoch: 0, target: null, deadline: null })
339
520
  return null
340
521
  }
341
522
 
342
- function close(target) {
523
+ function keepStorage(window, storage) {
524
+ for (const [area, entries] of Object.entries(storage)) {
525
+ entries.clear()
526
+ for (let index = 0; index < window[area].length; index += 1) entries.set(window[area].key(index), window[area].getItem(window[area].key(index)))
527
+ }
528
+ }
529
+
530
+ function restoreStorage(window, storage) {
531
+ for (const [area, entries] of Object.entries(storage)) for (const [key, value] of entries) window[area].setItem(key, value)
532
+ }
533
+
534
+ function close(target, notify = true) {
343
535
  target.closed = true
536
+ for (const socket of target.sockets.values()) notify ? socket.close() : socket.closed(1001)
344
537
  target.clock.timers.clear()
345
538
  if (target.window) target.window.close()
346
539
  }
347
540
 
348
541
  function prepare(window, current) {
349
542
  owners.set(window, current)
543
+ restoreStorage(window, session.storage)
350
544
  current.clock.install(window)
351
545
  trackHistory(window, current)
352
- window.fetch = (resource, init) => pageFetch(window, resource, init ?? {})
546
+ window.fetch = (resource, init) => owners.get(window).closed ? new Promise(() => {}) : track(pageFetch(window, resource, init ?? {}))
547
+ addXMLHttpRequest(window)
548
+ openFileChoosers(window)
549
+ window.WebSocket = cableSocketClass(window, current)
353
550
  window.alert = message => dialog("alert", message)
354
551
  window.confirm = message => dialog("confirm", message)
355
552
  window.prompt = (message, defaultValue) => dialog("prompt", message, defaultValue)
356
553
  window.HTMLFormElement.prototype.submit = function () { submitNatively(this, null) }
357
554
  stubMissingBrowserApis(window)
555
+ addMessageChannel(window, current.clock)
556
+ addClipboardData(window, current.clock)
557
+ fireResourceLoads(window, current.clock)
558
+ }
559
+
560
+ function addVirtualTime(window) {
561
+ const RealDate = window.Date
562
+ const current = () => time.epoch + time.now
563
+ function VirtualDate(...args) {
564
+ if (!new.target) return new RealDate(current()).toString()
565
+ return Reflect.construct(RealDate, args.length === 0 ? [current()] : args, new.target)
566
+ }
567
+ Object.setPrototypeOf(VirtualDate, RealDate)
568
+ VirtualDate.prototype = RealDate.prototype
569
+ VirtualDate.now = () => Math.floor(current())
570
+ window.Date = VirtualDate
571
+ Object.defineProperty(window.performance, "now", { configurable: true, value: () => time.now })
358
572
  }
359
573
 
360
574
  function trackHistory(window, current) {
@@ -366,13 +580,135 @@ function trackHistory(window, current) {
366
580
  }
367
581
  }
368
582
 
583
+ function addFormParticipation(window) {
584
+ const hosts = new WeakMap()
585
+ const states = new WeakMap()
586
+ const attach = window.HTMLElement.prototype.attachInternals
587
+ window.HTMLElement.prototype.attachInternals = function () {
588
+ const internals = attach.call(this)
589
+ hosts.set(internals, this)
590
+ states.set(this, { value: null, validity: { valid: true }, message: "" })
591
+ return internals
592
+ }
593
+ defineInternals(window.ElementInternals.prototype, internals => states.get(hosts.get(internals)), internals => hosts.get(internals))
594
+ window.FormData = formDataWithCustomElements(window.FormData, states)
595
+ }
596
+
597
+ function defineInternals(prototype, state, host) {
598
+ Object.defineProperties(prototype, {
599
+ form: { configurable: true, get() { return owningForm(host(this)) } },
600
+ validity: { configurable: true, get() { return state(this).validity } },
601
+ validationMessage: { configurable: true, get() { return state(this).message } },
602
+ willValidate: { configurable: true, get: () => true }
603
+ })
604
+ prototype.setFormValue = function (value) { state(this).value = value }
605
+ prototype.setValidity = function (flags = {}, message = "") {
606
+ const invalid = Object.values(flags).some(Boolean)
607
+ Object.assign(state(this), { validity: { ...flags, valid: !invalid }, message: invalid ? String(message) : "" })
608
+ }
609
+ prototype.checkValidity = prototype.reportValidity = function () { return state(this).validity.valid }
610
+ }
611
+
612
+ function owningForm(element) {
613
+ const id = element.getAttribute("form")
614
+ return id ? element.ownerDocument.getElementById(id) : element.closest("form")
615
+ }
616
+
617
+ function formDataWithCustomElements(NativeFormData, states) {
618
+ return class FormData extends NativeFormData {
619
+ constructor(form, submitter) {
620
+ super(form, submitter)
621
+ if (form) for (const element of form.ownerDocument.querySelectorAll("[name]")) appendCustomValue(this, element, form, states.get(element))
622
+ }
623
+ }
624
+ }
625
+
626
+ function appendCustomValue(data, element, form, state) {
627
+ if (state && state.value !== null && !element.hasAttribute("disabled") && owningForm(element) === form) data.append(element.getAttribute("name"), state.value)
628
+ }
629
+
630
+ function countMeasurements(prototype, name) {
631
+ const measure = prototype[name]
632
+ prototype[name] = function (...args) {
633
+ measurements += 1
634
+ if (measurements > MEASUREMENT_LIMIT) throw new Error(LAYOUT_LOOP)
635
+ const box = stubbedBox(this)
636
+ return box ? stubbedMeasurement(this, name, box) : measure.apply(this, args)
637
+ }
638
+ }
639
+
640
+ function stubbedBox(target) {
641
+ const node = target.startContainer || target
642
+ const element = node.nodeType === 1 ? node : node.parentElement
643
+ const owner = element && owners.get(element.ownerDocument.defaultView)
644
+ const stub = owner && owner.layoutStubs.find(entry => element.closest(entry.selector))
645
+ return stub ? stub.box : null
646
+ }
647
+
648
+ function stubbedMeasurement(target, name, box) {
649
+ const window = (target.startContainer || target).ownerDocument.defaultView
650
+ const rect = new window.DOMRect(box.left, box.top, box.width, box.height)
651
+ return name === "getClientRects" ? [rect] : rect
652
+ }
653
+
654
+ function addLayoutStubs(window) {
655
+ window.scrollTo = window.scroll = window.scrollBy = () => {}
656
+ window.Element.prototype.scrollIntoView = window.Element.prototype.scrollTo = window.Element.prototype.scroll = window.Element.prototype.scrollBy = () => {}
657
+ window.Element.prototype.checkVisibility = function () { return isVisible(this) }
658
+ window.Range.prototype.getBoundingClientRect = () => new window.DOMRect()
659
+ window.Range.prototype.getClientRects = () => []
660
+ for (const prototype of [window.Element.prototype, window.Range.prototype]) {
661
+ for (const name of ["getBoundingClientRect", "getClientRects"]) countMeasurements(prototype, name)
662
+ }
663
+ }
664
+
665
+ function addFullscreen(window) {
666
+ let fullscreen = null
667
+ const change = target => target.dispatchEvent(new window.Event("fullscreenchange", { bubbles: true }))
668
+ Object.defineProperty(window.Document.prototype, "fullscreenElement", { configurable: true, get: () => fullscreen })
669
+ Object.defineProperty(window.Document.prototype, "fullscreenEnabled", { configurable: true, get: () => true })
670
+ window.Element.prototype.requestFullscreen = function () {
671
+ fullscreen = this
672
+ change(this)
673
+ return Promise.resolve()
674
+ }
675
+ window.Document.prototype.exitFullscreen = function () {
676
+ const previous = fullscreen
677
+ fullscreen = null
678
+ if (previous) change(previous)
679
+ return Promise.resolve()
680
+ }
681
+ }
682
+
683
+ function addContentEditable(window) {
684
+ Object.defineProperty(window.HTMLElement.prototype, "isContentEditable", { configurable: true, get() { return Boolean(editingHost(this)) } })
685
+ }
686
+
687
+ function removeTouchSupport(window) {
688
+ for (const target of [window, window.Document.prototype, window.HTMLElement.prototype, window.SVGElement.prototype]) {
689
+ for (const name of ["ontouchstart", "ontouchend", "ontouchmove", "ontouchcancel"]) deleteFromChain(target, name)
690
+ }
691
+ Object.defineProperty(window.navigator, "maxTouchPoints", { configurable: true, value: 0 })
692
+ }
693
+
694
+ function deleteFromChain(object, name) {
695
+ for (let owner = object; owner; owner = Object.getPrototypeOf(owner)) {
696
+ if (Object.hasOwn(owner, name)) delete owner[name]
697
+ }
698
+ }
699
+
369
700
  function stubMissingBrowserApis(window) {
701
+ addFormParticipation(window)
702
+ addContentEditable(window)
703
+ addFullscreen(window)
704
+ removeTouchSupport(window)
370
705
  window.Headers = Headers
371
706
  window.Request = Request
372
707
  window.Response = Response
373
708
  window.matchMedia = media => ({ matches: false, media, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => false })
374
- window.scrollTo = window.scroll = window.scrollBy = () => {}
375
- window.Element.prototype.scrollIntoView = () => {}
709
+ window.URL.createObjectURL = () => objectUrl(window)
710
+ window.URL.revokeObjectURL = () => {}
711
+ addLayoutStubs(window)
376
712
  window.IntersectionObserver = window.ResizeObserver = class {
377
713
  observe() {}
378
714
  unobserve() {}
@@ -380,6 +716,96 @@ function stubMissingBrowserApis(window) {
380
716
  takeRecords() { return [] }
381
717
  }
382
718
  Object.defineProperty(window.navigator, "clipboard", { configurable: true, value: { writeText: async () => {}, readText: async () => "" } })
719
+ addDialogMethods(window)
720
+ }
721
+
722
+ function fireResourceLoads(window, clock) {
723
+ const images = new WeakMap()
724
+ const load = element => {
725
+ if (element.localName === "img" && images.get(element) === element.src) return
726
+ if (element.localName === "img") images.set(element, element.src)
727
+ clock.schedule(() => element.dispatchEvent(new window.Event("load")), 0, [], false)
728
+ }
729
+ new window.MutationObserver(records => records.flatMap(loadedBy).forEach(load)).observe(window.document, { childList: true, subtree: true, attributes: true, attributeFilter: ["src"] })
730
+ const src = Object.getOwnPropertyDescriptor(window.HTMLImageElement.prototype, "src")
731
+ Object.defineProperty(window.HTMLImageElement.prototype, "src", { ...src, set(value) { src.set.call(this, value); if (!this.isConnected && this.matches(LOADABLE)) load(this) } })
732
+ }
733
+
734
+ function loadedBy(record) {
735
+ if (record.type === "attributes") return record.target.matches(LOADABLE) ? [record.target] : []
736
+ return [...record.addedNodes].flatMap(loadablesIn)
737
+ }
738
+
739
+ function loadablesIn(node) {
740
+ if (node.nodeType !== 1) return []
741
+ return [...(node.matches(LOADABLE) ? [node] : []), ...node.querySelectorAll(LOADABLE)]
742
+ }
743
+
744
+ function objectUrl(window) {
745
+ const url = `blob:${window.location.origin}/${nextObjectUrl}`
746
+ nextObjectUrl += 1
747
+ return url
748
+ }
749
+
750
+ function addClipboardData(window, clock) {
751
+ const values = new WeakMap()
752
+ const item = (kind, type, value) => {
753
+ const entry = { kind, type, getAsFile: () => kind === "file" ? value : null, getAsString: callback => { if (kind === "string" && typeof callback === "function") clock.schedule(() => callback(value), 0, [], false) } }
754
+ values.set(entry, value)
755
+ return entry
756
+ }
757
+ window.DataTransfer = class DataTransfer {
758
+ constructor() {
759
+ Object.assign(this, { dropEffect: "none", effectAllowed: "all", items: transferItems(window, item) })
760
+ }
761
+
762
+ get types() { return [...new Set(this.items.map(entry => entry.kind === "file" ? "Files" : entry.type))] }
763
+
764
+ get files() { return this.items.filter(entry => entry.kind === "file").map(entry => entry.getAsFile()) }
765
+
766
+ setData(format, data) {
767
+ this.clearData(format)
768
+ this.items.add(String(data), dataType(format))
769
+ }
770
+
771
+ getData(format) { return values.get(this.items.find(entry => entry.kind === "string" && entry.type === dataType(format))) ?? "" }
772
+
773
+ clearData(format) { this.items.keep(entry => entry.kind === "file" || (format !== undefined && entry.type !== dataType(format))) }
774
+
775
+ setDragImage() {}
776
+ }
777
+ addClipboardEvent(window)
778
+ }
779
+
780
+ function addClipboardEvent(window) {
781
+ window.ClipboardEvent = class ClipboardEvent extends window.Event {
782
+ constructor(type, init = {}) {
783
+ super(type, init)
784
+ this.clipboardData = init.clipboardData ?? null
785
+ }
786
+ }
787
+ }
788
+
789
+ function transferItems(window, item) {
790
+ const list = []
791
+ return Object.assign(list, {
792
+ add: (data, type) => {
793
+ const entry = data instanceof window.File ? item("file", data.type, data) : item("string", String(type).toLowerCase(), String(data))
794
+ list.push(entry)
795
+ return entry
796
+ },
797
+ remove: index => { list.splice(index, 1) },
798
+ clear: () => { list.length = 0 },
799
+ keep: test => { list.splice(0, list.length, ...list.filter(test)) }
800
+ })
801
+ }
802
+
803
+ function dataType(format) {
804
+ const type = String(format).toLowerCase()
805
+ return { text: "text/plain", url: "text/uri-list" }[type] ?? type
806
+ }
807
+
808
+ function addDialogMethods(window) {
383
809
  window.HTMLDialogElement.prototype.show = window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", "") }
384
810
  window.HTMLDialogElement.prototype.close = function (returnValue) {
385
811
  if (returnValue !== undefined) this.returnValue = returnValue
@@ -390,28 +816,75 @@ function stubMissingBrowserApis(window) {
390
816
  }
391
817
  }
392
818
 
819
+ function addMessageChannel(window, clock) {
820
+ const peers = new WeakMap()
821
+ const closed = new WeakSet()
822
+ class MessagePort extends window.EventTarget {
823
+ constructor() {
824
+ super()
825
+ this.onmessage = null
826
+ }
827
+
828
+ postMessage(message) {
829
+ const data = structuredClone(message)
830
+ if (!closed.has(this)) clock.schedule(() => receiveMessage(window, peers.get(this), data, closed), 0, [], false)
831
+ }
832
+
833
+ start() {}
834
+
835
+ close() { closed.add(this) }
836
+ }
837
+ window.MessageChannel = class MessageChannel {
838
+ constructor() {
839
+ this.port1 = new MessagePort()
840
+ this.port2 = new MessagePort()
841
+ peers.set(this.port1, this.port2).set(this.port2, this.port1)
842
+ }
843
+ }
844
+ }
845
+
846
+ function receiveMessage(window, port, data, closed) {
847
+ if (closed.has(port)) return
848
+ const event = new window.MessageEvent("message", { data })
849
+ port.dispatchEvent(event)
850
+ if (typeof port.onmessage === "function") port.onmessage(event)
851
+ }
852
+
393
853
  function boot(window, report) {
394
854
  const { Application, controllers } = window.RailsJsdomBundle
395
- const application = Application.start()
396
- const registered = new Set()
855
+ const application = window.Stimulus instanceof Application ? window.Stimulus : Application.start()
397
856
  application.handleError = (error, message) => report(new Error(`${message}: ${describeError(error)}`))
398
857
  window.Stimulus = application
399
- const discover = () => {
400
- for (const identifier of controllerIdentifiers(window.document)) {
401
- if (controllers[identifier] && !registered.has(identifier)) {
402
- registered.add(identifier)
403
- application.register(identifier, controllers[identifier])
404
- }
405
- }
858
+ const registered = new Set()
859
+ const register = identifier => {
860
+ registered.add(identifier)
861
+ application.register(identifier, controllers[identifier])
406
862
  }
407
- discover()
408
- new window.MutationObserver(discover).observe(window.document, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-controller"] })
863
+ const discover = (records = [{ target: window.document, type: "attributes" }]) => changedElements(records).flatMap(controllerIdentifiers).filter(identifier => controllers[identifier] && !registered.has(identifier)).forEach(register)
864
+ const present = new Set(controllerIdentifiers(window.document))
865
+ registerInTurn(window, Object.keys(controllers).filter(identifier => present.has(identifier)), register, () => {
866
+ discover()
867
+ new window.MutationObserver(discover).observe(window.document, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-controller"] })
868
+ })
409
869
  fallBackLast(window, "click", event => followLink(window, event))
410
870
  fallBackLast(window, "submit", event => submitUnhandled(event))
411
871
  }
412
872
 
413
- function controllerIdentifiers(document) {
414
- return [...document.querySelectorAll("[data-controller]")].flatMap(element => element.getAttribute("data-controller").split(/\s+/))
873
+ function registerInTurn(window, identifiers, register, done) {
874
+ window.setTimeout(() => {
875
+ if (identifiers.length === 0) return done()
876
+ register(identifiers[0])
877
+ registerInTurn(window, identifiers.slice(1), register, done)
878
+ }, 0)
879
+ }
880
+
881
+ function changedElements(records) {
882
+ return records.flatMap(record => record.type === "attributes" ? [record.target] : [...record.addedNodes].filter(node => node.nodeType === 1))
883
+ }
884
+
885
+ function controllerIdentifiers(root) {
886
+ const own = root.nodeType === 1 && root.matches("[data-controller]") ? [root] : []
887
+ return [...own, ...root.querySelectorAll("[data-controller]")].flatMap(element => element.getAttribute("data-controller").split(/\s+/))
415
888
  }
416
889
 
417
890
  function fallBackLast(window, type, listener) {
@@ -499,7 +972,6 @@ function traverse(delta) {
499
972
  }
500
973
 
501
974
  async function pageFetch(window, resource, init) {
502
- if (owners.get(window).closed) return new Promise(() => {})
503
975
  const url = resourceUrl(window, resource)
504
976
  const headers = Object.fromEntries(new Headers(init.headers ?? {}))
505
977
  const body = await encodeBody(window, init.body, headers)
@@ -526,6 +998,7 @@ function pageResponse(reply) {
526
998
 
527
999
  async function encodeBody(window, body, headers) {
528
1000
  if (body === undefined || body === null) return null
1001
+ if (body instanceof window.Blob) return encodeBlob(body, headers)
529
1002
  if (Array.isArray(body) || body instanceof window.FormData || body instanceof window.URLSearchParams) {
530
1003
  const entries = [...body]
531
1004
  if (entries.some(([, value]) => typeof value !== "string")) return multipart(entries, headers)
@@ -535,6 +1008,105 @@ async function encodeBody(window, body, headers) {
535
1008
  return Buffer.from(String(body)).toString("base64")
536
1009
  }
537
1010
 
1011
+ async function encodeBlob(blob, headers) {
1012
+ if (blob.type && !headers["content-type"]) headers["content-type"] = blob.type
1013
+ return Buffer.from(await blob.arrayBuffer()).toString("base64")
1014
+ }
1015
+
1016
+ function addXMLHttpRequest(window) {
1017
+ window.XMLHttpRequest = class XMLHttpRequest extends window.EventTarget {
1018
+ constructor() {
1019
+ super()
1020
+ Object.assign(this, { readyState: 0, status: 0, statusText: "", response: "", responseText: "", responseURL: "", responseType: "", timeout: 0, withCredentials: false, upload: new window.EventTarget() })
1021
+ requests.set(this, { headers: {}, responseHeaders: {} })
1022
+ }
1023
+
1024
+ open(method, url, async = true) { openRequest(window, this, { method, url, async }) }
1025
+
1026
+ setRequestHeader(name, value) { requests.get(this).headers[String(name).toLowerCase()] = String(value) }
1027
+
1028
+ send(body = null) { track(sendRequest(window, this, body).catch(error => { errors.push(error) })) }
1029
+
1030
+ abort() { requests.get(this).aborted = true }
1031
+
1032
+ getResponseHeader(name) { return requests.get(this).responseHeaders[String(name).toLowerCase()] ?? null }
1033
+
1034
+ getAllResponseHeaders() { return Object.entries(requests.get(this).responseHeaders).map(([name, value]) => `${name}: ${value}\r\n`).join("") }
1035
+
1036
+ overrideMimeType() {}
1037
+ }
1038
+ }
1039
+
1040
+ function openRequest(window, xhr, { method, url, async }) {
1041
+ if (!async) throw new Error("RailsJsdom: synchronous XMLHttpRequest is not supported")
1042
+ if (owners.get(window).closed) return
1043
+ Object.assign(requests.get(xhr), { method: String(method).toUpperCase(), url: resourceUrl(window, url), aborted: false })
1044
+ xhr.readyState = 1
1045
+ fire(window, xhr, "readystatechange")
1046
+ }
1047
+
1048
+ async function sendRequest(window, xhr, body) {
1049
+ const request = requests.get(xhr)
1050
+ if (owners.get(window).closed) return
1051
+ const headers = { ...request.headers }
1052
+ const encoded = await encodeBody(window, body, headers)
1053
+ const stub = stubFor(request.url)
1054
+ const reply = stub ? { ...stub, url: request.url.href } : await requestRails({ method: request.method, url: request.url.href, headers, body: encoded })
1055
+ if (request.aborted) return
1056
+ if (body !== null) for (const type of ["progress", "load", "loadend"]) fire(window, xhr.upload, type, Buffer.byteLength(encoded, "base64"))
1057
+ if (reply.error) finishRequest(window, xhr, { status: 0, url: "", headers: {}, body: "" }, "error")
1058
+ else finishRequest(window, xhr, reply, "load")
1059
+ }
1060
+
1061
+ function finishRequest(window, xhr, reply, outcome) {
1062
+ const text = String(reply.body ?? "")
1063
+ requests.get(xhr).responseHeaders = Object.fromEntries(Object.entries(reply.headers).map(([name, value]) => [name.toLowerCase(), value]))
1064
+ Object.assign(xhr, { readyState: 4, status: reply.status, responseURL: reply.url, responseText: text, response: responseFor(window, xhr.responseType, text) })
1065
+ for (const type of ["readystatechange", outcome, "loadend"]) fire(window, xhr, type, text.length)
1066
+ }
1067
+
1068
+ function responseFor(window, type, text) {
1069
+ if (type === "json") return text === "" ? null : window.JSON.parse(text)
1070
+ if (type === "" || type === "text") return text
1071
+ throw new Error(`RailsJsdom: XMLHttpRequest responseType "${type}" is not supported`)
1072
+ }
1073
+
1074
+ function fire(window, target, type, size = 0) {
1075
+ const event = type === "readystatechange" ? new window.Event(type) : new window.ProgressEvent(type, { lengthComputable: true, loaded: size, total: size })
1076
+ target.dispatchEvent(event)
1077
+ if (typeof target[`on${type}`] === "function") target[`on${type}`](event)
1078
+ }
1079
+
1080
+ function openFileChoosers(window) {
1081
+ const click = window.HTMLElement.prototype.click
1082
+ window.HTMLInputElement.prototype.click = function () {
1083
+ let activation = null
1084
+ const listen = event => { activation = event }
1085
+ this.addEventListener("click", listen, true)
1086
+ click.call(this)
1087
+ this.removeEventListener("click", listen, true)
1088
+ if (activation && !activation.defaultPrevented && this.type === "file") openFileChooser(this)
1089
+ }
1090
+ }
1091
+
1092
+ function openFileChooser(input) {
1093
+ if (!chooser || chooser.opened) return
1094
+ const files = chooser.files
1095
+ chooser.opened = true
1096
+ page.clock.schedule(() => attachFiles(input, files), 0, [], false)
1097
+ }
1098
+
1099
+ function expectFileChooser(files) {
1100
+ chooser = { files, opened: false }
1101
+ return null
1102
+ }
1103
+
1104
+ function takeFileChooser() {
1105
+ const opened = Boolean(chooser && chooser.opened)
1106
+ chooser = null
1107
+ return opened
1108
+ }
1109
+
538
1110
  async function multipart(entries, headers) {
539
1111
  const boundary = `----RailsJsdomBoundary${nextFetchId}${Date.now()}`
540
1112
  const quote = text => String(text).replace(/"/g, "%22").replace(/\r?\n/g, " ")
@@ -575,9 +1147,14 @@ function dialog(type, message, defaultValue) {
575
1147
 
576
1148
  function find({ locator, scope, match }, strategy, kind) {
577
1149
  const root = scopeRoot(scope)
578
- const candidates = [byAction, strategy, byCss].map(search => search(root, locator).filter(element => !kind || element.matches(kind))).find(list => list.length > 0) || []
579
- if (candidates.length === 0) throw new Error(`RailsJsdom: unable to find ${JSON.stringify(locator)}`)
580
- return pick(candidates, JSON.stringify(locator), match)
1150
+ const description = locator === null ? "any element of that kind" : JSON.stringify(locator)
1151
+ const candidates = locator === null ? [...root.querySelectorAll(kind || CLICKABLE)] : located(root, locator, strategy, kind)
1152
+ if (candidates.length === 0) throw new Error(`RailsJsdom: unable to find ${description}`)
1153
+ return pick(candidates, description, match)
1154
+ }
1155
+
1156
+ function located(root, locator, strategy, kind) {
1157
+ return [byAction, strategy, byCss].map(search => search(root, locator).filter(element => !kind || element.matches(kind))).find(list => list.length > 0) || []
581
1158
  }
582
1159
 
583
1160
  function scopeRoot(scope = []) {
@@ -614,7 +1191,7 @@ function byCss(root, locator) {
614
1191
  }
615
1192
 
616
1193
  function names(element) {
617
- return [element.textContent, element.getAttribute("aria-label"), element.getAttribute("title"), element.id, element.matches(BUTTON_INPUTS) ? element.value : ""].map(normalize).filter(Boolean)
1194
+ return [element.textContent, element.getAttribute("aria-label"), element.getAttribute("title"), element.id, element.matches(BUTTON_INPUTS) ? element.value : "", element.matches(`button, ${BUTTON_INPUTS}`) ? element.getAttribute("name") : ""].map(normalize).filter(Boolean)
618
1195
  }
619
1196
 
620
1197
  function byText(elements, text) {
@@ -693,9 +1270,9 @@ function attachFiles(input, files) {
693
1270
  }
694
1271
 
695
1272
  function internal(object) {
696
- const symbol = Object.getOwnPropertySymbols(object).find(candidate => candidate.description === "impl")
697
- if (!symbol) throw new Error("RailsJsdom: attach_file does not work with this jsdom version")
698
- return object[symbol]
1273
+ const implementation = wrappers.implForWrapper(object)
1274
+ if (!implementation) throw new Error("RailsJsdom: attach_file does not work with this jsdom version")
1275
+ return implementation
699
1276
  }
700
1277
 
701
1278
  function handleFor(element) {
@@ -759,12 +1336,54 @@ function elementAction(message) {
759
1336
  return ELEMENT_ACTIONS[message.action](element, message)
760
1337
  }
761
1338
 
762
- function sendKeys(element, keys) {
763
- if (element) element.focus()
1339
+ async function sendKeys(element, keys) {
1340
+ if (element) focusForTyping(element)
1341
+ typing += 1
1342
+ try {
1343
+ await pressKeys(keys)
1344
+ } finally {
1345
+ typing -= 1
1346
+ }
1347
+ }
1348
+
1349
+ async function pressKeys(keys) {
764
1350
  for (const entry of keys) {
765
1351
  const modifiers = modifierFlags(entry.modifiers || [])
766
- for (const key of pressedKeys(entry)) press(key, modifiers)
1352
+ for (const key of pressedKeys(entry)) {
1353
+ await runQueuedTasks()
1354
+ press(key, modifiers)
1355
+ }
1356
+ }
1357
+ }
1358
+
1359
+ async function runQueuedTasks() {
1360
+ let ran = 0
1361
+ do {
1362
+ if (ran > SETTLE_LIMIT) throw notSettled()
1363
+ ran += 1
1364
+ await turn()
1365
+ } while (await stepNow())
1366
+ }
1367
+
1368
+ async function stepNow() {
1369
+ if (pending.size > 0) {
1370
+ await Promise.race(pending)
1371
+ return true
767
1372
  }
1373
+ return runTaskDueNow()
1374
+ }
1375
+
1376
+ function runTaskDueNow() {
1377
+ const timer = page.clock.due(time.now)
1378
+ if (timer) page.clock.run(timer)
1379
+ return Boolean(timer)
1380
+ }
1381
+
1382
+ function focusForTyping(element) {
1383
+ const focused = element.ownerDocument.activeElement === element
1384
+ element.focus()
1385
+ const host = editingHost(element)
1386
+ if (host && !focused) placeCaretAtEnd(host.ownerDocument.defaultView, host)
768
1387
  }
769
1388
 
770
1389
  function modifierFlags(names) {
@@ -797,6 +1416,11 @@ function press(key, modifiers) {
797
1416
 
798
1417
  function keyAction(target, key, modifiers) {
799
1418
  if (key === "Tab") return moveFocus(target, modifiers.shiftKey)
1419
+ const host = editingHost(target)
1420
+ return host ? editContent(host, key, modifiers) : fieldKeyAction(target, key, modifiers)
1421
+ }
1422
+
1423
+ function fieldKeyAction(target, key, modifiers) {
800
1424
  if (key === "Enter") return pressEnter(target)
801
1425
  if (key === " " && target.matches(PRESSABLE)) return click(target)
802
1426
  if (target.matches(STEPPABLE) && ["ArrowUp", "ArrowRight", "ArrowDown", "ArrowLeft", "Home", "End"].includes(key)) return step(target, key)
@@ -804,6 +1428,80 @@ function keyAction(target, key, modifiers) {
804
1428
  return null
805
1429
  }
806
1430
 
1431
+ function editingHost(element) {
1432
+ const nearest = element && element.closest("[contenteditable]")
1433
+ if (!nearest || nearest.getAttribute("contenteditable") === "false") return null
1434
+ return editingHost(nearest.parentElement) || nearest
1435
+ }
1436
+
1437
+ function editContent(host, key, modifiers) {
1438
+ const window = host.ownerDocument.defaultView
1439
+ const inputType = contentInputType(key, modifiers)
1440
+ const init = { bubbles: true, cancelable: true, composed: true, inputType, data: inputType === "insertText" ? key : null }
1441
+ if (inputType && host.dispatchEvent(new window.InputEvent("beforeinput", init))) {
1442
+ editAtCaret(window, caretIn(window, host), inputType, init.data)
1443
+ host.dispatchEvent(new window.InputEvent("input", { ...init, cancelable: false }))
1444
+ }
1445
+ return null
1446
+ }
1447
+
1448
+ function contentInputType(key, modifiers) {
1449
+ if (key === "Backspace") return "deleteContentBackward"
1450
+ if (key === "Enter") return modifiers.shiftKey ? "insertLineBreak" : "insertParagraph"
1451
+ return typesCharacter(key, modifiers) ? "insertText" : null
1452
+ }
1453
+
1454
+ function caretIn(window, host) {
1455
+ const selection = window.getSelection()
1456
+ if (selection.rangeCount === 0 || !host.contains(selection.anchorNode)) placeCaretAtEnd(window, host)
1457
+ return selection
1458
+ }
1459
+
1460
+ function placeCaretAtEnd(window, host) {
1461
+ const texts = window.document.createTreeWalker(host, window.NodeFilter.SHOW_TEXT)
1462
+ let last = null
1463
+ while (texts.nextNode()) last = texts.currentNode
1464
+ if (last) window.getSelection().collapse(last, last.length)
1465
+ else window.getSelection().collapse(host, host.childNodes.length)
1466
+ }
1467
+
1468
+ function editAtCaret(window, selection, inputType, data) {
1469
+ if (inputType === "deleteContentBackward") return deleteBeforeCaret(selection)
1470
+ const node = selection.anchorNode
1471
+ const offset = selection.anchorOffset
1472
+ if (inputType === "insertText" && node.nodeType === 3) {
1473
+ node.insertData(offset, data)
1474
+ selection.collapse(node, offset + data.length)
1475
+ } else if (inputType === "insertText") {
1476
+ const text = window.document.createTextNode(data)
1477
+ selection.getRangeAt(0).insertNode(text)
1478
+ selection.collapse(text, data.length)
1479
+ } else {
1480
+ insertNodeAtCaret(selection, window.document.createElement("br"))
1481
+ }
1482
+ }
1483
+
1484
+ function deleteBeforeCaret(selection) {
1485
+ const node = selection.anchorNode
1486
+ const offset = selection.anchorOffset
1487
+ const before = node.nodeType === 3 ? null : node.childNodes[offset - 1]
1488
+ if (node.nodeType === 3 && offset > 0) {
1489
+ node.deleteData(offset - 1, 1)
1490
+ selection.collapse(node, offset - 1)
1491
+ } else if (before?.nodeType === 3 && before.length > 0) {
1492
+ before.deleteData(before.length - 1, 1)
1493
+ selection.collapse(before, before.length)
1494
+ } else if (before) {
1495
+ before.remove()
1496
+ selection.collapse(node, offset - 1)
1497
+ }
1498
+ }
1499
+
1500
+ function insertNodeAtCaret(selection, inserted) {
1501
+ selection.getRangeAt(0).insertNode(inserted)
1502
+ selection.collapse(inserted.parentNode, [...inserted.parentNode.childNodes].indexOf(inserted) + 1)
1503
+ }
1504
+
807
1505
  function editText(target, key, modifiers) {
808
1506
  if (target.disabled || target.readOnly) return null
809
1507
  const before = target.value
@@ -906,16 +1604,6 @@ function visibleText(node) {
906
1604
  return INLINE_ELEMENTS.has(node.localName) ? text : ` ${text} `
907
1605
  }
908
1606
 
909
- function streams() {
910
- if (!page) return []
911
- return [...page.window.document.querySelectorAll(STREAM_SOURCES)].map(source => source.getAttribute("signed-stream-name"))
912
- }
913
-
914
- function deliver(messages) {
915
- for (const message of messages) page.window.Turbo.renderStreamMessage(message)
916
- return null
917
- }
918
-
919
1607
  function snapshot(scope) {
920
1608
  if (!page) throw new Error("RailsJsdom: visit a page or mount a partial first")
921
1609
  const root = scopeRoot(scope)