@rind-ui/testing 0.0.0-stage → 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.
@@ -0,0 +1,854 @@
1
+ import { o as poll, r as describeBy, t as composeInPage } from "./compose-DPLnCCnJ.mjs";
2
+ import { ANNOUNCEMENTS, KEY_DEBOUNCE_MS, PENDING_ANNOUNCEMENTS, isKeptVisible } from "@rind-ui/core";
3
+ import { computeAccessibleDescription, computeAccessibleName } from "dom-accessibility-api";
4
+ //#region src/announcements.ts
5
+ /** An announcer that only records (for machine tests in Node, or as an env override). */
6
+ function recordingAnnouncer() {
7
+ const log = [];
8
+ return {
9
+ log,
10
+ announcer: {
11
+ announce: (a) => {
12
+ log.push(a);
13
+ },
14
+ prepare: () => () => {},
15
+ cancel: () => {}
16
+ }
17
+ };
18
+ }
19
+ /**
20
+ * The page-wide log every rind-ui announce() call appends to (any backend). Installed by
21
+ * @rind-ui/testing/setup and by the adapters; cleared by resetRindGlobals.
22
+ */
23
+ function installAnnouncementLog() {
24
+ let log = Reflect.get(globalThis, ANNOUNCEMENTS);
25
+ if (!log) {
26
+ log = [];
27
+ Reflect.set(globalThis, ANNOUNCEMENTS, log);
28
+ }
29
+ return log;
30
+ }
31
+ //#endregion
32
+ //#region src/collect.ts
33
+ const LIVE_ROLES = [
34
+ "status",
35
+ "alert",
36
+ "log",
37
+ "marquee",
38
+ "timer"
39
+ ];
40
+ const REF_ATTRS = [
41
+ "aria-labelledby",
42
+ "aria-describedby",
43
+ "aria-controls",
44
+ "aria-activedescendant",
45
+ "aria-owns",
46
+ "aria-details",
47
+ "for"
48
+ ];
49
+ const norm = (s) => (s ?? "").replace(/\s+/g, " ").trim();
50
+ /**
51
+ * The one visibility rule both adapters use: attached, and neither it nor an ancestor is
52
+ * `hidden` (including `until-found`), `inert` or `display: none`, and it is not
53
+ * `visibility: hidden`. `display: contents` counts as visible: its children render.
54
+ */
55
+ function isVisible(el) {
56
+ if (!el.isConnected) return false;
57
+ const view = el.ownerDocument.defaultView;
58
+ for (let n = el; n; n = n.parentElement) {
59
+ if (n.hasAttribute("hidden") || n.hasAttribute("inert")) return false;
60
+ const style = view?.getComputedStyle(n);
61
+ if (style?.display === "none") return false;
62
+ if (n === el && style?.visibility === "hidden") return false;
63
+ }
64
+ return true;
65
+ }
66
+ function implicitRole(el) {
67
+ const tag = el.tagName.toLowerCase();
68
+ const type = el.getAttribute("type");
69
+ switch (tag) {
70
+ case "button": return "button";
71
+ case "a": return el.hasAttribute("href") ? "link" : null;
72
+ case "input":
73
+ if (type === "checkbox") return "checkbox";
74
+ if (type === "radio") return "radio";
75
+ if (type === "range") return "slider";
76
+ if (type === "number") return "spinbutton";
77
+ if (type === "button" || type === "submit" || type === "reset" || type === "image") return "button";
78
+ if (type === "hidden") return null;
79
+ return "textbox";
80
+ case "textarea": return "textbox";
81
+ case "select": return el.hasAttribute("multiple") ? "listbox" : "combobox";
82
+ case "img": return el.getAttribute("alt") === "" ? "presentation" : "img";
83
+ case "dialog": return "dialog";
84
+ case "ul":
85
+ case "ol": return "list";
86
+ case "li": return "listitem";
87
+ case "nav": return "navigation";
88
+ case "main": return "main";
89
+ case "h1":
90
+ case "h2":
91
+ case "h3":
92
+ case "h4":
93
+ case "h5":
94
+ case "h6": return "heading";
95
+ default: return null;
96
+ }
97
+ }
98
+ const roleOf = (el) => el.getAttribute("role")?.split(" ")[0] || implicitRole(el);
99
+ function focusable(el) {
100
+ if (!("tabIndex" in el) || el.disabled) return false;
101
+ if (el.hasAttribute("tabindex")) return true;
102
+ return el.matches("a[href], button, input:not([type=hidden]), select, textarea, [contenteditable=''], [contenteditable=true]");
103
+ }
104
+ const describe = (el) => {
105
+ const part = el.getAttribute("data-part");
106
+ return `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}${part ? `[data-part=${part}]` : ""}`;
107
+ };
108
+ const attrsOf = (el) => {
109
+ const out = {};
110
+ for (const a of Array.from(el.attributes)) out[a.name] = a.value;
111
+ return out;
112
+ };
113
+ const ancestorIds = (el) => {
114
+ const out = [];
115
+ for (let n = el.parentElement; n; n = n.parentElement) if (n.id) out.push(n.id);
116
+ return out;
117
+ };
118
+ const identities = /* @__PURE__ */ new WeakMap();
119
+ let lastIdentity = 0;
120
+ const identity = (el) => {
121
+ let id = identities.get(el);
122
+ if (id === void 0) {
123
+ lastIdentity += 1;
124
+ id = lastIdentity;
125
+ identities.set(el, id);
126
+ }
127
+ return id;
128
+ };
129
+ const isLive = (el) => {
130
+ const live = el.getAttribute("aria-live");
131
+ return live !== null ? live !== "off" : LIVE_ROLES.includes(roleOf(el) ?? "");
132
+ };
133
+ const formEvents = /* @__PURE__ */ new WeakMap();
134
+ let countingFormEvents = false;
135
+ function countFormEvents() {
136
+ if (countingFormEvents) return;
137
+ countingFormEvents = true;
138
+ for (const type of [
139
+ "change",
140
+ "input",
141
+ "click"
142
+ ]) document.addEventListener(type, (e) => {
143
+ const t = e.target;
144
+ if (!(t instanceof Element) || t.getAttribute("data-part") !== "hidden-input") return;
145
+ const c = formEvents.get(t) ?? {
146
+ change: 0,
147
+ input: 0,
148
+ click: 0
149
+ };
150
+ c[type] += 1;
151
+ formEvents.set(t, c);
152
+ }, true);
153
+ }
154
+ function collectDom(arg) {
155
+ const doc = document;
156
+ countFormEvents();
157
+ const parents = /* @__PURE__ */ new Map();
158
+ const groupOf = (el) => {
159
+ const parent = el.parentElement;
160
+ if (!parents.has(parent)) parents.set(parent, parents.size);
161
+ return `${parents.get(parent)}|${el.getAttribute("aria-level") ?? ""}`;
162
+ };
163
+ const own = (el) => el.getAttribute("data-instance") === arg.instance && el.getAttribute("data-scope") === arg.scope;
164
+ const info = (el) => ({
165
+ describe: describe(el),
166
+ node: identity(el),
167
+ rect: (() => {
168
+ const r = el.getBoundingClientRect();
169
+ return {
170
+ x: r.x,
171
+ y: r.y,
172
+ width: r.width,
173
+ height: r.height
174
+ };
175
+ })(),
176
+ part: own(el) ? el.getAttribute("data-part") : null,
177
+ role: roleOf(el),
178
+ name: norm(computeAccessibleName(el)),
179
+ description: norm(computeAccessibleDescription(el)),
180
+ text: norm(el.textContent),
181
+ id: el.id || null,
182
+ attrs: attrsOf(el),
183
+ hidden: !isVisible(el),
184
+ inAriaHidden: el.closest("[aria-hidden=true]") !== null,
185
+ inInert: el.closest("[inert]") !== null,
186
+ focusable: focusable(el),
187
+ animations: typeof el.getAnimations === "function" ? el.getAnimations().filter((a) => a.playState === "running" && a.effect?.getComputedTiming().endTime !== Number.POSITIVE_INFINITY).length : 0,
188
+ group: groupOf(el),
189
+ within: ancestorIds(el)
190
+ });
191
+ const selector = `[data-scope="${CSS.escape(arg.scope)}"][data-instance="${CSS.escape(arg.instance)}"]`;
192
+ const partEls = Array.from(doc.querySelectorAll(`${selector}[data-part]`));
193
+ const all = /* @__PURE__ */ new Set();
194
+ for (const p of partEls) {
195
+ all.add(p);
196
+ for (const d of Array.from(p.querySelectorAll("*"))) all.add(d);
197
+ }
198
+ const elements = Array.from(all);
199
+ const refs = [];
200
+ const ids = /* @__PURE__ */ new Set();
201
+ for (const el of elements) {
202
+ if (el.id) ids.add(el.id);
203
+ for (const attr of REF_ATTRS) for (const id of (el.getAttribute(attr) ?? "").split(/\s+/).filter(Boolean)) {
204
+ const target = doc.getElementById(id);
205
+ refs.push({
206
+ from: describe(el),
207
+ attr,
208
+ id,
209
+ exists: target !== null,
210
+ targetInInert: target?.closest("[inert]") != null
211
+ });
212
+ }
213
+ }
214
+ const duplicateIds = Array.from(ids).filter((id) => doc.querySelectorAll(`[id="${CSS.escape(id)}"]`).length > 1);
215
+ const outside = {};
216
+ const record = (sibling) => {
217
+ const picked = {};
218
+ for (const name of [
219
+ "aria-hidden",
220
+ "inert",
221
+ "style"
222
+ ]) {
223
+ const v = sibling.getAttribute(name);
224
+ if (v !== null) picked[name] = v;
225
+ }
226
+ if (isKeptVisible(sibling)) picked["data-rind-kept"] = "";
227
+ if ([
228
+ "SCRIPT",
229
+ "STYLE",
230
+ "TEMPLATE",
231
+ "LINK"
232
+ ].includes(sibling.tagName)) picked["data-rind-kept"] = "";
233
+ outside[`${identity(sibling)}:${describe(sibling)}`] = picked;
234
+ };
235
+ const holdsInstance = (el) => all.has(el) || el.querySelector(selector) !== null;
236
+ for (const p of partEls) for (let n = p; n && n !== doc.body && n.parentElement; n = n.parentElement) for (const sibling of Array.from(n.parentElement.children)) if (sibling !== n && !holdsInstance(sibling)) record(sibling);
237
+ if (partEls.length === 0 && doc.body) for (const el of Array.from(doc.body.querySelectorAll("*"))) record(el);
238
+ const active = doc.activeElement;
239
+ const activePart = active?.closest(selector);
240
+ const fieldRoot = partEls[0]?.closest("[data-scope=\"field\"][data-part=\"root\"]") ?? null;
241
+ const fieldPart = (part) => fieldRoot ? Array.from(doc.querySelectorAll(`[data-scope="field"][data-part="${part}"][data-instance="${fieldRoot.getAttribute("data-instance")}"]`)) : [];
242
+ const fieldLabel = fieldPart("label")[0];
243
+ return {
244
+ field: fieldRoot ? {
245
+ attrs: attrsOf(fieldRoot),
246
+ label: fieldLabel ? {
247
+ id: fieldLabel.id,
248
+ text: norm(fieldLabel.textContent),
249
+ for: fieldLabel.getAttribute("for")
250
+ } : null,
251
+ partIds: [...fieldPart("description"), ...fieldPart("error-message")].map((e) => e.id).filter(Boolean)
252
+ } : null,
253
+ parts: partEls.map(info),
254
+ elements: elements.map(info),
255
+ refs,
256
+ duplicateIds,
257
+ focus: {
258
+ onBody: active === null || active === doc.body,
259
+ part: activePart?.getAttribute("data-part") ?? null,
260
+ inInstance: activePart != null,
261
+ element: active && active !== doc.body ? info(active) : null
262
+ },
263
+ html: attrsOf(doc.documentElement),
264
+ body: attrsOf(doc.body),
265
+ outside,
266
+ viewport: (() => {
267
+ const view = doc.defaultView;
268
+ const vv = view?.visualViewport;
269
+ return {
270
+ x: vv?.offsetLeft ?? 0,
271
+ y: vv?.offsetTop ?? 0,
272
+ width: vv?.width ?? view?.innerWidth ?? 0,
273
+ height: vv?.height ?? view?.innerHeight ?? 0,
274
+ layout: !navigator.userAgent.includes("jsdom") && (view?.innerWidth ?? 0) > 0
275
+ };
276
+ })(),
277
+ liveRegions: elements.filter(isLive).map(describe),
278
+ formInputs: elements.filter((el) => el.getAttribute("data-part") === "hidden-input").map((el) => {
279
+ const input = el;
280
+ const c = formEvents.get(el) ?? {
281
+ change: 0,
282
+ input: 0,
283
+ click: 0
284
+ };
285
+ return {
286
+ describe: describe(el),
287
+ checked: input.checked === true,
288
+ indeterminate: input.indeterminate === true,
289
+ value: input.value ?? "",
290
+ ariaHidden: el.getAttribute("aria-hidden"),
291
+ tabIndex: input.tabIndex,
292
+ focused: doc.activeElement === el,
293
+ changes: c.change,
294
+ inputs: c.input,
295
+ clicks: c.click,
296
+ inParent: el.closest("[data-parent]") !== null
297
+ };
298
+ })
299
+ };
300
+ }
301
+ //#endregion
302
+ //#region src/labelled.ts
303
+ function labelledControl(label) {
304
+ const control = label.control;
305
+ if (control) return control;
306
+ const root = label.getRootNode();
307
+ if (label.id) {
308
+ for (const el of Array.from(root.querySelectorAll("[aria-labelledby]"))) if (el.getAttribute("aria-labelledby")?.split(/\s+/).includes(label.id)) return el;
309
+ }
310
+ const htmlFor = label.getAttribute("for");
311
+ return htmlFor && "getElementById" in root ? root.getElementById(htmlFor) : null;
312
+ }
313
+ //#endregion
314
+ //#region src/navigation.ts
315
+ const NAVIGATIONS = Symbol.for("rind-ui.navigations");
316
+ /** The page-wide log, created on first use. */
317
+ function navigationLog() {
318
+ let log = Reflect.get(globalThis, NAVIGATIONS);
319
+ if (!log) {
320
+ log = [];
321
+ Reflect.set(globalThis, NAVIGATIONS, log);
322
+ }
323
+ return log;
324
+ }
325
+ /**
326
+ * A `Router` that records `navigate` calls (and the page-wide navigation log drivers read),
327
+ * with an optional `href` mapping (a basename). For `RouterProvider` or a raw environment.
328
+ */
329
+ function fakeRouter(options = {}) {
330
+ const calls = [];
331
+ return {
332
+ calls,
333
+ navigate(href, routerOptions) {
334
+ calls.push({
335
+ href,
336
+ routerOptions
337
+ });
338
+ navigationLog().push({
339
+ href: String(href),
340
+ newTab: false,
341
+ via: "router"
342
+ });
343
+ },
344
+ ...options.href ? { href: options.href } : {}
345
+ };
346
+ }
347
+ /** Where the browser would open this activation of `a`, from the event and the anchor. */
348
+ function opensElsewhere(a, e) {
349
+ const target = a.getAttribute("target");
350
+ return e.type === "auxclick" || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || a.hasAttribute("download") || target !== null && target !== "" && target !== "_self";
351
+ }
352
+ const intercepted = /* @__PURE__ */ new WeakSet();
353
+ const handled = /* @__PURE__ */ new WeakSet();
354
+ /**
355
+ * Records every link activation the page leaves to the browser, then cancels it: the test
356
+ * page is never unloaded and no tab opens. Runs after the page's own handlers (window
357
+ * bubble phase; at the target for rind-ui's non-bubbling temporary anchors).
358
+ */
359
+ function interceptNativeNavigation(win) {
360
+ if (intercepted.has(win)) return;
361
+ intercepted.add(win);
362
+ const anchorOf = (e) => e.composedPath().find((n) => n instanceof win.HTMLAnchorElement && n.hasAttribute("href"));
363
+ const finish = (e) => {
364
+ if (e.type === "auxclick" && e.button !== 1) return;
365
+ const a = anchorOf(e);
366
+ if (!a || e.defaultPrevented || handled.has(e)) return;
367
+ handled.add(e);
368
+ navigationLog().push({
369
+ href: a.href,
370
+ newTab: opensElsewhere(a, e),
371
+ via: "browser"
372
+ });
373
+ e.preventDefault();
374
+ };
375
+ win.addEventListener("click", finish);
376
+ win.addEventListener("auxclick", finish);
377
+ win.addEventListener("click", (e) => {
378
+ const a = anchorOf(e);
379
+ if (a?.hasAttribute("data-rind-synthetic-link")) a.addEventListener("click", finish, { once: true });
380
+ }, true);
381
+ }
382
+ /** Whether `log` gained a matching navigation after index `from`. */
383
+ function navigatedSince(log, from, options = {}) {
384
+ return log.slice(from).some((n) => n.newTab === (options.newTab === true));
385
+ }
386
+ //#endregion
387
+ //#region src/adapters/dom.ts
388
+ let tl;
389
+ const loadTL = () => {
390
+ tl ??= import("@testing-library/dom");
391
+ return tl;
392
+ };
393
+ let step = 0;
394
+ const nextCoords = (el) => {
395
+ step += 1;
396
+ const rect = el?.getBoundingClientRect();
397
+ if (!rect || rect.width < 2 || rect.height < 2) {
398
+ const c = step * 7;
399
+ return {
400
+ clientX: c,
401
+ clientY: c,
402
+ pageX: c,
403
+ pageY: c
404
+ };
405
+ }
406
+ const x = rect.left + 1 + step % Math.max(1, Math.floor(rect.width - 2));
407
+ const y = rect.top + 1 + step % Math.max(1, Math.floor(rect.height - 2));
408
+ return {
409
+ clientX: x,
410
+ clientY: y,
411
+ pageX: x + window.scrollX,
412
+ pageY: y + window.scrollY
413
+ };
414
+ };
415
+ /**
416
+ * Resolves once no finite transition or animation is running in the document (or after `max`
417
+ * ms). A sibling panel opening shifts the target's box for a while, and a press aimed at
418
+ * coordinates read before the shift releases outside it (the press is then not a press).
419
+ * Without running animations (every jsdom test, most browser ones) it returns at once; fake
420
+ * timers have no frames to wait on.
421
+ */
422
+ const settled = async (el, fake, max = 1e3) => {
423
+ const doc = el.ownerDocument;
424
+ const view = doc.defaultView;
425
+ if (fake || !view?.requestAnimationFrame || !doc.getAnimations) return;
426
+ const running = () => doc.getAnimations().some((a) => a.playState === "running" && a.effect?.getComputedTiming().iterations !== Number.POSITIVE_INFINITY);
427
+ const end = Date.now() + max;
428
+ while (running() && Date.now() < end) await new Promise((done) => view.requestAnimationFrame(() => done()));
429
+ };
430
+ const KEY_NAMES = {
431
+ Enter: "{Enter}",
432
+ Escape: "{Escape}",
433
+ Space: "[Space]",
434
+ Tab: "{Tab}",
435
+ Home: "{Home}",
436
+ End: "{End}",
437
+ PageUp: "{PageUp}",
438
+ PageDown: "{PageDown}",
439
+ ArrowUp: "{ArrowUp}",
440
+ ArrowDown: "{ArrowDown}",
441
+ ArrowLeft: "{ArrowLeft}",
442
+ ArrowRight: "{ArrowRight}",
443
+ Backspace: "{Backspace}",
444
+ Delete: "{Delete}",
445
+ F10: "{F10}",
446
+ ContextMenu: "{ContextMenu}",
447
+ A: "a"
448
+ };
449
+ function keyText(key, options = {}, apple = false) {
450
+ const mods = [
451
+ options.shift ? "Shift" : null,
452
+ options.alt ? "Alt" : null,
453
+ options.mod ? apple ? "Meta" : "Control" : null
454
+ ].filter((m) => m !== null);
455
+ return `${mods.map((m) => `{${m}>}`).join("")}${KEY_NAMES[key]}${mods.reverse().map((m) => `{/${m}}`).join("")}`;
456
+ }
457
+ const normalize = (s) => (s ?? "").replace(/\s+/g, " ").trim();
458
+ const describeElement = (el) => {
459
+ const html = el.outerHTML;
460
+ return html.length > 160 ? `${html.slice(0, 160)}…` : html;
461
+ };
462
+ const logs = /* @__PURE__ */ new WeakMap();
463
+ /**
464
+ * Records uncaught errors and console.error calls, installed once per window. Called by
465
+ * `@rind-ui/testing/setup` and when a DOM adapter is created, so errors during the first
466
+ * render are caught; `testMachine` clears it before each path.
467
+ */
468
+ function installErrorLog(win = globalThis.window ?? null) {
469
+ if (!win) return [];
470
+ let log = logs.get(win);
471
+ if (!log) {
472
+ const entries = [];
473
+ const { console } = win;
474
+ const original = console.error.bind(console);
475
+ const realBrowser = !(win.navigator?.userAgent ?? "").includes("jsdom");
476
+ console.error = (...args) => {
477
+ const message = args.map(String).join(" ");
478
+ if (!(realBrowser && message.includes("not wrapped in act("))) entries.push(message);
479
+ original(...args);
480
+ };
481
+ win.addEventListener("error", (e) => entries.push(String(e.error ?? e.message)));
482
+ logs.set(win, entries);
483
+ log = entries;
484
+ }
485
+ return log;
486
+ }
487
+ /** The Testing Library adapter. */
488
+ function domEnv(options = {}) {
489
+ const timeout = options.timeout ?? 1e3;
490
+ const doc = options.root?.ownerDocument ?? globalThis.document;
491
+ const errors = installErrorLog(doc?.defaultView ?? null);
492
+ if (doc?.defaultView) interceptNativeNavigation(doc.defaultView);
493
+ let user;
494
+ const getUser = () => {
495
+ user ??= options.user ? Promise.resolve(options.user) : import("@testing-library/user-event").then(({ userEvent }) => userEvent.setup(options.advanceTimers ? { advanceTimers: options.advanceTimers } : {}));
496
+ return user;
497
+ };
498
+ return {
499
+ "~rindEnvFactory": true,
500
+ create: (envOptions) => createDomEnv(envOptions, {
501
+ ...options,
502
+ timeout
503
+ }, getUser, () => errors)
504
+ };
505
+ }
506
+ /** React's flag for "updates must be inside act" (Testing Library's asyncWrapper clears it). */
507
+ const ACT_ENV = "IS_REACT_ACT_ENVIRONMENT";
508
+ /** The `key` value a native event carries for a contract key. */
509
+ const NATIVE_KEY = { Space: " " };
510
+ function createDomEnv({ scope, anchor, modality, platform }, options, getUser, errors) {
511
+ const doc = () => options.root?.ownerDocument ?? document;
512
+ const apple = platform?.apple === true;
513
+ /** The navigation log's length when the current action began. */
514
+ let navigationsFrom = navigationLog().length;
515
+ /** A composing key press: keydown and keyup with isComposing and keyCode 229, no input. */
516
+ const composingPress = (el, key, keyOptions) => act(() => {
517
+ for (const type of ["keydown", "keyup"]) {
518
+ const e = new KeyboardEvent(type, {
519
+ bubbles: true,
520
+ cancelable: true,
521
+ key: NATIVE_KEY[key] ?? key,
522
+ isComposing: true,
523
+ shiftKey: keyOptions.shift === true,
524
+ altKey: keyOptions.alt === true,
525
+ ctrlKey: keyOptions.mod === true && !apple,
526
+ metaKey: keyOptions.mod === true && apple
527
+ });
528
+ Object.defineProperty(e, "keyCode", { value: 229 });
529
+ el.dispatchEvent(e);
530
+ }
531
+ });
532
+ /** Wraps an interaction so the framework flushes (act) around it. */
533
+ const act = async (fn) => {
534
+ const { getConfig } = await loadTL();
535
+ await getConfig().asyncWrapper(async () => {
536
+ const outside = Reflect.get(globalThis, ACT_ENV);
537
+ let result;
538
+ getConfig().eventWrapper(() => {
539
+ result = fn();
540
+ });
541
+ await result;
542
+ if (outside === false) Reflect.set(globalThis, ACT_ENV, false);
543
+ });
544
+ };
545
+ /** The whole loop runs inside asyncWrapper, so deferred updates never warn about act. */
546
+ const until = async (read, accept, timeout = options.timeout) => {
547
+ const { getConfig } = await loadTL();
548
+ const { advanceTimers } = options;
549
+ const wait = advanceTimers ? (ms) => Promise.resolve(getConfig().eventWrapper(() => advanceTimers(ms))) : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
550
+ return getConfig().asyncWrapper(() => poll(read, accept, {
551
+ timeout,
552
+ wait
553
+ }));
554
+ };
555
+ const queryBy = async (by, within) => {
556
+ if ("role" in by) {
557
+ const { queryAllByRole } = await loadTL();
558
+ const name = by.name;
559
+ return queryAllByRole(within, by.role, { ...name === void 0 ? {} : { name: typeof name === "string" ? (n) => normalize(n) === name : name } });
560
+ }
561
+ if ("part" in by) return Array.from(within.querySelectorAll(`[data-scope="${CSS.escape(scope)}"][data-part="${CSS.escape(by.part)}"]`));
562
+ const { text } = by;
563
+ const matches = (el) => {
564
+ const own = normalize(el.textContent);
565
+ return typeof text === "string" ? own === text : text.test(own);
566
+ };
567
+ const found = Array.from(within.querySelectorAll("*")).filter(matches);
568
+ return found.filter((el) => !found.some((other) => other !== el && el.contains(other)));
569
+ };
570
+ const anchorEls = () => queryBy(anchor, options.root ?? doc());
571
+ const instance = async () => {
572
+ const els = await anchorEls();
573
+ const [el, ...more] = els;
574
+ if (!el) throw new Error(`${scope}: no element matches the anchor (${describeBy(anchor)})`);
575
+ if (more.length > 0) throw new Error(`${scope}: ${els.length} elements match the anchor (${describeBy(anchor)}):\n${els.map(describeElement).join("\n")}`);
576
+ const id = el.closest("[data-instance]")?.getAttribute("data-instance");
577
+ if (!id) throw new Error(`${scope}: the anchor has no data-instance`);
578
+ return id;
579
+ };
580
+ /** A lazy handle: `resolve` runs on every use. Reads never wait; actions wait to exist. */
581
+ const handle = (label, resolve) => {
582
+ const single = (els) => {
583
+ if (els.length === 0) throw new Error(`${label}: not found`);
584
+ if (els.length > 1) throw new Error(`${label}: ${els.length} elements match:\n${els.map(describeElement).join("\n")}`);
585
+ return els[0];
586
+ };
587
+ const now = async () => single(await resolve());
588
+ const waitFor = async () => single(await until(resolve, (found) => found.length > 0).catch(async () => resolve()));
589
+ const modifiers = (o = {}) => ({
590
+ shiftKey: o.shift === true,
591
+ ctrlKey: o.mod === true && !apple,
592
+ metaKey: o.mod === true && apple
593
+ });
594
+ const bareClick = (el, o) => act(() => el.dispatchEvent(new MouseEvent("click", {
595
+ bubbles: true,
596
+ cancelable: true,
597
+ composed: true,
598
+ detail: 0,
599
+ ...modifiers(o)
600
+ })));
601
+ /** What a middle click sends (user-event and Vitest's userEvent differ on it). */
602
+ const middleClick = (el, o) => act(() => {
603
+ const init = {
604
+ bubbles: true,
605
+ cancelable: true,
606
+ composed: true,
607
+ button: 1,
608
+ buttons: 4
609
+ };
610
+ const mods = modifiers(o);
611
+ el.dispatchEvent(new PointerEvent("pointerdown", {
612
+ ...init,
613
+ ...mods,
614
+ pointerType: "mouse"
615
+ }));
616
+ el.dispatchEvent(new MouseEvent("mousedown", {
617
+ ...init,
618
+ ...mods
619
+ }));
620
+ el.dispatchEvent(new PointerEvent("pointerup", {
621
+ ...init,
622
+ ...mods,
623
+ buttons: 0,
624
+ pointerType: "mouse"
625
+ }));
626
+ el.dispatchEvent(new MouseEvent("mouseup", {
627
+ ...init,
628
+ ...mods,
629
+ buttons: 0
630
+ }));
631
+ el.dispatchEvent(new MouseEvent("auxclick", {
632
+ ...init,
633
+ ...mods,
634
+ buttons: 0,
635
+ detail: 1
636
+ }));
637
+ });
638
+ /** Holds the modifiers (user-event keyboard state) around a press. */
639
+ const held = async (o, run) => {
640
+ const keys = [o?.shift ? "Shift" : null, o?.mod ? apple ? "Meta" : "Control" : null].filter((k) => k !== null);
641
+ if (keys.length === 0) return run();
642
+ const u = await getUser();
643
+ await act(() => u.keyboard(keys.map((k) => `{${k}>}`).join("")));
644
+ try {
645
+ return await run();
646
+ } finally {
647
+ await act(() => u.keyboard(keys.map((k) => `{/${k}}`).join("")));
648
+ }
649
+ };
650
+ const press = async (el, touch) => {
651
+ const u = await getUser();
652
+ if (!u.pointer) return act(() => u.click(el));
653
+ await settled(el, options.advanceTimers !== void 0);
654
+ const coords = nextCoords(el);
655
+ const steps = touch ? [{
656
+ keys: "[TouchA]",
657
+ target: el,
658
+ coords
659
+ }] : [{
660
+ target: el,
661
+ coords
662
+ }, {
663
+ keys: "[MouseLeft]",
664
+ target: el,
665
+ coords
666
+ }];
667
+ return act(() => u.pointer?.(steps));
668
+ };
669
+ const part = {
670
+ async click(options) {
671
+ const el = await waitFor();
672
+ if (options?.button === "middle") return middleClick(el, options);
673
+ if (modality === "virtual") return bareClick(el, options);
674
+ await held(options, () => press(el, false));
675
+ },
676
+ async tap() {
677
+ const el = await waitFor();
678
+ return modality === "virtual" ? bareClick(el) : press(el, true);
679
+ },
680
+ async hover(hoverOptions) {
681
+ const el = await waitFor();
682
+ const pointerType = hoverOptions?.pointerType ?? "mouse";
683
+ if (pointerType === "touch") return act(() => {
684
+ for (const type of ["pointerover", "pointerenter"]) el.dispatchEvent(new PointerEvent(type, {
685
+ bubbles: type === "pointerover",
686
+ pointerType,
687
+ ...nextCoords(el)
688
+ }));
689
+ });
690
+ const u = await getUser();
691
+ if (u.pointer) await act(() => u.pointer?.({
692
+ target: el,
693
+ coords: nextCoords(el)
694
+ }));
695
+ else await act(() => u.hover(el));
696
+ },
697
+ async focus() {
698
+ const el = await waitFor();
699
+ await act(() => el.focus());
700
+ },
701
+ async press(key, keyOptions) {
702
+ const el = await waitFor();
703
+ if (doc().activeElement !== el) await act(() => el.focus());
704
+ if (keyOptions?.composing) return composingPress(el, key, keyOptions);
705
+ const u = await getUser();
706
+ await act(() => u.keyboard(keyText(key, keyOptions, apple)));
707
+ },
708
+ async type(text) {
709
+ const el = await waitFor();
710
+ const u = await getUser();
711
+ const textEntry = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLElement && el.isContentEditable;
712
+ const skipClick = doc().activeElement === el && !textEntry;
713
+ await act(() => u.type(el, text, skipClick ? { skipClick: true } : void 0));
714
+ },
715
+ async compose(updates, commit) {
716
+ const el = await waitFor();
717
+ if (doc().activeElement !== el) await act(() => el.focus());
718
+ await act(() => composeInPage(el, commit === void 0 ? { updates } : {
719
+ updates,
720
+ commit
721
+ }));
722
+ },
723
+ async pressAtPosition() {
724
+ const el = await waitFor();
725
+ const rect = el.getBoundingClientRect();
726
+ const x = rect.left + rect.width / 2;
727
+ const y = rect.top + rect.height / 2;
728
+ const hit = (rect.width > 0 ? doc().elementFromPoint(x, y) : null) ?? el;
729
+ const u = await getUser();
730
+ if (u.pointer) await act(() => u.pointer?.([{
731
+ keys: "[MouseLeft]",
732
+ target: hit,
733
+ coords: {
734
+ clientX: x,
735
+ clientY: y
736
+ }
737
+ }]));
738
+ else await act(() => u.click(hit));
739
+ },
740
+ waitForDetach: async () => {
741
+ await until(async () => (await resolve()).length, (n) => n === 0);
742
+ },
743
+ isInert: async () => (await now()).closest("[inert]") !== null,
744
+ attr: async (name) => (await now()).getAttribute(name),
745
+ tagName: async () => (await now()).tagName.toLowerCase(),
746
+ scoped: (scope, partName) => handle(`${scope}.${partName} in ${label}`, async () => Array.from((await now()).querySelectorAll(`[data-scope="${scope}"][data-part="${partName}"]`))),
747
+ withAttr: (name, value) => handle(`[${name}] in ${label}`, async () => Array.from((await now()).querySelectorAll(value === void 0 ? `[${name}]` : `[${name}="${CSS.escape(value)}"]`))),
748
+ text: async () => normalize((await now()).textContent),
749
+ value: async () => (await now()).value ?? "",
750
+ checked: async () => (await now()).checked === true,
751
+ indeterminate: async () => (await now()).indeterminate === true,
752
+ exists: async () => (await resolve()).some(isVisible),
753
+ isFocused: async () => {
754
+ const el = await now();
755
+ const active = doc().activeElement;
756
+ return active === el || el.id !== "" && active?.getAttribute("aria-activedescendant") === el.id;
757
+ },
758
+ count: async () => (await resolve()).length,
759
+ accessibleName: async () => {
760
+ const { computeAccessibleName } = await import("dom-accessibility-api");
761
+ return normalize(computeAccessibleName(await now()));
762
+ },
763
+ accessibleDescription: async () => {
764
+ const { computeAccessibleDescription } = await import("dom-accessibility-api");
765
+ return normalize(computeAccessibleDescription(await now()));
766
+ },
767
+ labelled: () => handle(`the control of ${label}`, async () => {
768
+ const control = labelledControl(await now());
769
+ return control ? [control] : [];
770
+ }),
771
+ async doubleClick() {
772
+ const el = await waitFor();
773
+ const u = await getUser();
774
+ if (u.dblClick) await act(() => u.dblClick?.(el));
775
+ else {
776
+ await press(el, false);
777
+ await press(el, false);
778
+ }
779
+ },
780
+ nth: (index) => handle(`${label}[${index}]`, async () => {
781
+ const el = (await resolve())[index];
782
+ return el ? [el] : [];
783
+ }),
784
+ all: async () => (await resolve()).map((_, i) => part.nth(i))
785
+ };
786
+ return part;
787
+ };
788
+ const partEls = async (name, by) => {
789
+ const id = await instance();
790
+ const sel = `[data-scope="${CSS.escape(scope)}"][data-part="${CSS.escape(name)}"][data-instance="${CSS.escape(id)}"]`;
791
+ const parts = Array.from(doc().querySelectorAll(sel));
792
+ if (!by) return parts;
793
+ const matching = new Set(await queryBy(by, doc()));
794
+ return parts.filter((el) => matching.has(el));
795
+ };
796
+ return {
797
+ modality,
798
+ part: (name, by) => handle(`${scope}.${name}${by ? ` (${describeBy(by)})` : ""}`, () => partEls(name, by)),
799
+ find: (by) => handle(describeBy(by), () => queryBy(by, doc())),
800
+ focused: () => handle("the focused element", async () => {
801
+ const active = doc().activeElement;
802
+ return active && active !== doc().body ? [active] : [];
803
+ }),
804
+ async keyboard(key, keyOptions) {
805
+ const target = doc().activeElement ?? doc().body;
806
+ if (keyOptions?.composing) return composingPress(target, key, keyOptions);
807
+ const u = await getUser();
808
+ await act(() => u.keyboard(keyText(key, keyOptions, apple)));
809
+ },
810
+ async pointerOutside() {
811
+ const u = await getUser();
812
+ const body = doc().body;
813
+ if (!u.pointer) return act(() => u.click(body));
814
+ const coords = nextCoords();
815
+ await act(() => u.pointer?.([{
816
+ keys: "[MouseLeft]",
817
+ target: body,
818
+ coords
819
+ }]));
820
+ },
821
+ until,
822
+ advance: async (ms) => {
823
+ if (options.advanceTimers) await act(() => options.advanceTimers?.(ms));
824
+ else await act(() => new Promise((resolve) => setTimeout(resolve, Math.max(ms, 16))));
825
+ },
826
+ instance,
827
+ anchorCount: async () => (await anchorEls()).length,
828
+ collect: async () => collectDom({
829
+ scope,
830
+ instance: await instance()
831
+ }),
832
+ collectDocument: async () => collectDom({
833
+ scope,
834
+ instance: "\0unmounted"
835
+ }),
836
+ announcements: async () => {
837
+ await until(async () => Reflect.get(globalThis, PENDING_ANNOUNCEMENTS) ?? 0, (n) => n === 0, Math.max(options.timeout, KEY_DEBOUNCE_MS * 2)).catch(() => {});
838
+ return [...installAnnouncementLog()];
839
+ },
840
+ takeErrors: async () => errors().splice(0),
841
+ selectedText: async () => doc().getSelection()?.toString() ?? "",
842
+ markNavigations: async () => {
843
+ navigationsFrom = navigationLog().length;
844
+ },
845
+ navigated: async (o) => navigatedSince(navigationLog(), navigationsFrom, o),
846
+ scope: async (fn) => (await loadTL()).getConfig().asyncWrapper(fn),
847
+ setDirection: async (direction) => {
848
+ if (direction === null) doc().documentElement.removeAttribute("dir");
849
+ else doc().documentElement.dir = direction;
850
+ }
851
+ };
852
+ }
853
+ //#endregion
854
+ export { navigationLog as a, interceptNativeNavigation as i, installErrorLog as n, installAnnouncementLog as o, fakeRouter as r, recordingAnnouncer as s, domEnv as t };