diff --git a/node_modules/@tanstack/virtual-core/LICENSE b/node_modules/@tanstack/virtual-core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1869e21fc3c80b3010c3e60c5ab6dda077ce1f22 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present Tanner Linsley + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js b/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js new file mode 100644 index 0000000000000000000000000000000000000000..e72658059f7762de45de0e1a23f4fb27aaa32273 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js @@ -0,0 +1,34 @@ +function createLazyMeasurementsView(count, flat, getItemKey) { + const cache = new Array(count); + return new Proxy(cache, { + get(target, prop, receiver) { + if (typeof prop === "string") { + const c = prop.charCodeAt(0); + if (c >= 48 && c <= 57) { + const i = +prop; + if (Number.isInteger(i) && i >= 0 && i < count) { + let v = target[i]; + if (!v) { + const s = flat[i * 2]; + v = target[i] = { + index: i, + key: getItemKey(i), + start: s, + size: flat[i * 2 + 1], + end: s + flat[i * 2 + 1], + lane: 0 + }; + } + return v; + } + } + if (prop === "length") return count; + } + return Reflect.get(target, prop, receiver); + } + }); +} +export { + createLazyMeasurementsView +}; +//# sourceMappingURL=lazy-measurements.js.map diff --git a/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js.map b/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js.map new file mode 100644 index 0000000000000000000000000000000000000000..276f937b6ecb0714e7491b39691e91ee0d4e7549 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/dist/esm/lazy-measurements.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lazy-measurements.js","sources":["../../src/lazy-measurements.ts"],"sourcesContent":["// Lazy materialization for the lanes===1 fast path. Backed by a\n// Float64Array (stride 2: start, size, …); VirtualItems are constructed on\n// first indexed read and cached. Saves the per-item object allocation at\n// large list counts where most items are never visible.\n\nimport type { VirtualItem } from './index'\n\ntype Key = number | string | bigint\n\nexport function createLazyMeasurementsView(\n count: number,\n flat: Float64Array,\n getItemKey: (i: number) => Key,\n): Array {\n const cache: Array = new Array(count)\n return new Proxy(cache as any, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n // Cheap digit-prefix sniff before number coerce.\n const c = prop.charCodeAt(0)\n if (c >= 48 && c <= 57) {\n const i = +prop\n if (Number.isInteger(i) && i >= 0 && i < count) {\n let v = target[i]\n if (!v) {\n const s = flat[i * 2]!\n v = target[i] = {\n index: i,\n key: getItemKey(i),\n start: s,\n size: flat[i * 2 + 1]!,\n end: s + flat[i * 2 + 1]!,\n lane: 0,\n }\n }\n return v\n }\n }\n if (prop === 'length') return count\n }\n return Reflect.get(target, prop, receiver)\n },\n }) as Array\n}\n"],"names":[],"mappings":"AASO,SAAS,2BACd,OACA,MACA,YACoB;AACpB,QAAM,QAAwC,IAAI,MAAM,KAAK;AAC7D,SAAO,IAAI,MAAM,OAAc;AAAA,IAC7B,IAAI,QAAQ,MAAM,UAAU;AAC1B,UAAI,OAAO,SAAS,UAAU;AAE5B,cAAM,IAAI,KAAK,WAAW,CAAC;AAC3B,YAAI,KAAK,MAAM,KAAK,IAAI;AACtB,gBAAM,IAAI,CAAC;AACX,cAAI,OAAO,UAAU,CAAC,KAAK,KAAK,KAAK,IAAI,OAAO;AAC9C,gBAAI,IAAI,OAAO,CAAC;AAChB,gBAAI,CAAC,GAAG;AACN,oBAAM,IAAI,KAAK,IAAI,CAAC;AACpB,kBAAI,OAAO,CAAC,IAAI;AAAA,gBACd,OAAO;AAAA,gBACP,KAAK,WAAW,CAAC;AAAA,gBACjB,OAAO;AAAA,gBACP,MAAM,KAAK,IAAI,IAAI,CAAC;AAAA,gBACpB,KAAK,IAAI,KAAK,IAAI,IAAI,CAAC;AAAA,gBACvB,MAAM;AAAA,cAAA;AAAA,YAEV;AACA,mBAAO;AAAA,UACT;AAAA,QACF;AACA,YAAI,SAAS,SAAU,QAAO;AAAA,MAChC;AACA,aAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAAA,IAC3C;AAAA,EAAA,CACD;AACH;"} \ No newline at end of file diff --git a/node_modules/@tanstack/virtual-core/dist/esm/utils.d.ts b/node_modules/@tanstack/virtual-core/dist/esm/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8af53b8d393dad4705e07f35dba3f0749beae6a5 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/dist/esm/utils.d.ts @@ -0,0 +1,15 @@ +export type NoInfer = [A][A extends any ? 0 : never]; +export type PartialKeys = Omit & Partial>; +export declare function memo, TResult>(getDeps: () => [...TDeps], fn: (...args: NoInfer<[...TDeps]>) => TResult, opts: { + key: false | string; + debug?: () => boolean; + onChange?: (result: TResult) => void; + initialDeps?: TDeps; + skipInitialOnChange?: boolean; +}): { + (): TResult; + updateDeps(newDeps: [...TDeps]): void; +}; +export declare function notUndefined(value: T | undefined, msg?: string): T; +export declare const approxEqual: (a: number, b: number) => boolean; +export declare const debounce: (targetWindow: Window & typeof globalThis, fn: Function, ms: number) => (this: any, ...args: Array) => void; diff --git a/node_modules/@tanstack/virtual-core/dist/esm/utils.js b/node_modules/@tanstack/virtual-core/dist/esm/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..5369a85f196d547cc760ff4b1c8d2a0b4857bf62 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/dist/esm/utils.js @@ -0,0 +1,74 @@ +function memo(getDeps, fn, opts) { + let deps = opts.initialDeps ?? []; + let result; + let isInitial = true; + function memoizedFunction() { + var _a; + const debugEnabled = process.env.NODE_ENV !== "production" && !!opts.key && !!((_a = opts.debug) == null ? void 0 : _a.call(opts)); + let depTime = 0; + if (debugEnabled) depTime = Date.now(); + const newDeps = getDeps(); + const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep); + if (!depsChanged) { + return result; + } + deps = newDeps; + let resultTime = 0; + if (debugEnabled) resultTime = Date.now(); + result = fn(...newDeps); + if (debugEnabled) { + const depEndTime = Math.round((Date.now() - depTime) * 100) / 100; + const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100; + const resultFpsPercentage = resultEndTime / 16; + const pad = (str, num) => { + str = String(str); + while (str.length < num) { + str = " " + str; + } + return str; + }; + console.info( + `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, + ` + font-size: .6rem; + font-weight: bold; + color: hsl(${Math.max( + 0, + Math.min(120 - 120 * resultFpsPercentage, 120) + )}deg 100% 31%);`, + opts == null ? void 0 : opts.key + ); + } + if ((opts == null ? void 0 : opts.onChange) && !(isInitial && opts.skipInitialOnChange)) { + opts.onChange(result); + } + isInitial = false; + return result; + } + memoizedFunction.updateDeps = (newDeps) => { + deps = newDeps; + }; + return memoizedFunction; +} +function notUndefined(value, msg) { + if (value === void 0) { + throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ""}`); + } else { + return value; + } +} +const approxEqual = (a, b) => Math.abs(a - b) < 1.01; +const debounce = (targetWindow, fn, ms) => { + let timeoutId; + return function(...args) { + targetWindow.clearTimeout(timeoutId); + timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms); + }; +}; +export { + approxEqual, + debounce, + memo, + notUndefined +}; +//# sourceMappingURL=utils.js.map diff --git a/node_modules/@tanstack/virtual-core/dist/esm/utils.js.map b/node_modules/@tanstack/virtual-core/dist/esm/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..193b63c4243f3f093d782fcc8d92b35f5e2be5b1 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/dist/esm/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["export type NoInfer = [A][A extends any ? 0 : never]\n\nexport type PartialKeys = Omit & Partial>\n\nexport function memo, TResult>(\n getDeps: () => [...TDeps],\n fn: (...args: NoInfer<[...TDeps]>) => TResult,\n opts: {\n key: false | string\n debug?: () => boolean\n onChange?: (result: TResult) => void\n initialDeps?: TDeps\n skipInitialOnChange?: boolean\n },\n) {\n let deps = opts.initialDeps ?? []\n let result: TResult | undefined\n let isInitial = true\n\n function memoizedFunction(): TResult {\n // Debug-only timing. In production builds, `process.env.NODE_ENV !==\n // 'production'` is constant-folded to `false` by downstream minifiers\n // (Terser/esbuild/swc with `define`), which DCEs the entire block.\n const debugEnabled =\n process.env.NODE_ENV !== 'production' && !!opts.key && !!opts.debug?.()\n let depTime = 0\n if (debugEnabled) depTime = Date.now()\n\n const newDeps = getDeps()\n\n const depsChanged =\n newDeps.length !== deps.length ||\n newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n let resultTime = 0\n if (debugEnabled) resultTime = Date.now()\n\n result = fn(...newDeps)\n\n if (debugEnabled) {\n const depEndTime = Math.round((Date.now() - depTime) * 100) / 100\n const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100\n const resultFpsPercentage = resultEndTime / 16\n\n const pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n }\n\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120),\n )}deg 100% 31%);`,\n opts?.key,\n )\n }\n\n if (opts?.onChange && !(isInitial && opts.skipInitialOnChange)) {\n opts.onChange(result)\n }\n\n isInitial = false\n\n return result\n }\n\n // Attach updateDeps to the function itself\n memoizedFunction.updateDeps = (newDeps: [...TDeps]) => {\n deps = newDeps\n }\n\n return memoizedFunction\n}\n\nexport function notUndefined(value: T | undefined, msg?: string): T {\n if (value === undefined) {\n throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)\n } else {\n return value\n }\n}\n\nexport const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1.01\n\nexport const debounce = (\n targetWindow: Window & typeof globalThis,\n fn: Function,\n ms: number,\n) => {\n let timeoutId: number\n return function (this: any, ...args: Array) {\n targetWindow.clearTimeout(timeoutId)\n timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms)\n }\n}\n"],"names":[],"mappings":"AAIO,SAAS,KACd,SACA,IACA,MAOA;AACA,MAAI,OAAO,KAAK,eAAe,CAAA;AAC/B,MAAI;AACJ,MAAI,YAAY;AAEhB,WAAS,mBAA4B;AAfhC;AAmBH,UAAM,eACJ,QAAQ,IAAI,aAAa,gBAAgB,CAAC,CAAC,KAAK,OAAO,CAAC,GAAC,UAAK,UAAL;AAC3D,QAAI,UAAU;AACd,QAAI,aAAc,WAAU,KAAK,IAAA;AAEjC,UAAM,UAAU,QAAA;AAEhB,UAAM,cACJ,QAAQ,WAAW,KAAK,UACxB,QAAQ,KAAK,CAAC,KAAU,UAAkB,KAAK,KAAK,MAAM,GAAG;AAE/D,QAAI,CAAC,aAAa;AAChB,aAAO;AAAA,IACT;AAEA,WAAO;AAEP,QAAI,aAAa;AACjB,QAAI,aAAc,cAAa,KAAK,IAAA;AAEpC,aAAS,GAAG,GAAG,OAAO;AAEtB,QAAI,cAAc;AAChB,YAAM,aAAa,KAAK,OAAO,KAAK,QAAQ,WAAW,GAAG,IAAI;AAC9D,YAAM,gBAAgB,KAAK,OAAO,KAAK,QAAQ,cAAc,GAAG,IAAI;AACpE,YAAM,sBAAsB,gBAAgB;AAE5C,YAAM,MAAM,CAAC,KAAsB,QAAgB;AACjD,cAAM,OAAO,GAAG;AAChB,eAAO,IAAI,SAAS,KAAK;AACvB,gBAAM,MAAM;AAAA,QACd;AACA,eAAO;AAAA,MACT;AAEA,cAAQ;AAAA,QACN,OAAO,IAAI,eAAe,CAAC,CAAC,KAAK,IAAI,YAAY,CAAC,CAAC;AAAA,QACnD;AAAA;AAAA;AAAA,yBAGiB,KAAK;AAAA,UAChB;AAAA,UACA,KAAK,IAAI,MAAM,MAAM,qBAAqB,GAAG;AAAA,QAAA,CAC9C;AAAA,QACL,6BAAM;AAAA,MAAA;AAAA,IAEV;AAEA,SAAI,6BAAM,aAAY,EAAE,aAAa,KAAK,sBAAsB;AAC9D,WAAK,SAAS,MAAM;AAAA,IACtB;AAEA,gBAAY;AAEZ,WAAO;AAAA,EACT;AAGA,mBAAiB,aAAa,CAAC,YAAwB;AACrD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,aAAgB,OAAsB,KAAiB;AACrE,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI,MAAM,uBAAuB,MAAM,KAAK,GAAG,KAAK,EAAE,EAAE;AAAA,EAChE,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAEO,MAAM,cAAc,CAAC,GAAW,MAAc,KAAK,IAAI,IAAI,CAAC,IAAI;AAEhE,MAAM,WAAW,CACtB,cACA,IACA,OACG;AACH,MAAI;AACJ,SAAO,YAAwB,MAAkB;AAC/C,iBAAa,aAAa,SAAS;AACnC,gBAAY,aAAa,WAAW,MAAM,GAAG,MAAM,MAAM,IAAI,GAAG,EAAE;AAAA,EACpE;AACF;"} \ No newline at end of file diff --git a/node_modules/@tanstack/virtual-core/package.json b/node_modules/@tanstack/virtual-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ea913bda0a0014ee7b504a72fd9a34e3888d6ad0 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/package.json @@ -0,0 +1,56 @@ +{ + "name": "@tanstack/virtual-core", + "version": "3.17.7", + "description": "Headless UI for virtualizing scrollable elements in TS/JS + Frameworks", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/virtual.git", + "directory": "packages/virtual-core" + }, + "homepage": "https://tanstack.com/virtual", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "react", + "vue", + "solid", + "virtual", + "virtual-core", + "datagrid" + ], + "type": "module", + "types": "dist/esm/index.d.ts", + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "scripts": { + "clean": "premove ./dist ./coverage", + "test:eslint": "eslint ./src", + "test:types": "tsc", + "test:lib": "vitest", + "test:lib:dev": "pnpm run test:lib --watch", + "test:build": "publint --strict", + "build": "vite build" + } +} \ No newline at end of file diff --git a/node_modules/@tanstack/virtual-core/src/index.ts b/node_modules/@tanstack/virtual-core/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e209208a6d1b4e0713f78deab96598819ed697ad --- /dev/null +++ b/node_modules/@tanstack/virtual-core/src/index.ts @@ -0,0 +1,2093 @@ +import { createLazyMeasurementsView } from './lazy-measurements' +import { approxEqual, debounce, memo, notUndefined } from './utils' + +// Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes +// during a momentum-scroll cancel the momentum on iOS WebKit, so we defer +// scroll-position adjustments triggered by mid-scroll resizes until the +// scroll settles. SSR-safe (returns false when navigator is unavailable). +let _isIOSResult: boolean | undefined +const isIOSWebKit = (): boolean => { + if (_isIOSResult !== undefined) return _isIOSResult + if (typeof navigator === 'undefined') return (_isIOSResult = false) + if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true) + // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop. + const mtp = (navigator as Navigator & { maxTouchPoints?: number }) + .maxTouchPoints + return (_isIOSResult = + navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0) +} + +// Test hook: reset the iOS detection cache. Not exported. +export const _resetIOSDetectionForTests = () => { + _isIOSResult = undefined +} + +export { approxEqual, debounce, memo, notUndefined } from './utils' +export type { NoInfer, PartialKeys } from './utils' + +// + +type ScrollDirection = 'forward' | 'backward' + +type ScrollAlignment = 'start' | 'center' | 'end' | 'auto' + +type ScrollBehavior = 'auto' | 'smooth' | 'instant' + +type ScrollAnchor = 'start' | 'end' + +type FollowOnAppend = boolean | ScrollBehavior + +export interface ScrollToOptions { + align?: ScrollAlignment + behavior?: ScrollBehavior +} + +type ScrollToOffsetOptions = ScrollToOptions + +type ScrollToIndexOptions = ScrollToOptions + +type ScrollToEndOptions = Pick + +export interface Range { + startIndex: number + endIndex: number + overscan: number + count: number +} + +type Key = number | string | bigint + +export interface VirtualItem { + key: Key + index: number + start: number + end: number + size: number + lane: number +} + +export interface Rect { + width: number + height: number +} + +// + +const getRect = (element: HTMLElement): Rect => { + const { offsetWidth, offsetHeight } = element + return { width: offsetWidth, height: offsetHeight } +} + +export const defaultKeyExtractor = (index: number) => index + +export const defaultRangeExtractor = (range: Range) => { + const start = Math.max(range.startIndex - range.overscan, 0) + const end = Math.min(range.endIndex + range.overscan, range.count - 1) + const len = end - start + 1 + + const arr = new Array(len) + for (let i = 0; i < len; i++) { + arr[i] = start + i + } + return arr +} + +export const observeElementRect = ( + instance: Virtualizer, + cb: (rect: Rect) => void, +) => { + const element = instance.scrollElement + if (!element) { + return + } + const targetWindow = instance.targetWindow + if (!targetWindow) { + return + } + + const handler = (rect: Rect) => { + const { width, height } = rect + cb({ width: Math.round(width), height: Math.round(height) }) + } + + handler(getRect(element as unknown as HTMLElement)) + + if (!targetWindow.ResizeObserver) { + return () => {} + } + + const observer = new targetWindow.ResizeObserver((entries) => { + const run = () => { + const entry = entries[0] + if (entry?.borderBoxSize) { + const box = entry.borderBoxSize[0] + if (box) { + handler({ width: box.inlineSize, height: box.blockSize }) + return + } + } + handler(getRect(element as unknown as HTMLElement)) + } + + instance.options.useAnimationFrameWithResizeObserver + ? requestAnimationFrame(run) + : run() + }) + + observer.observe(element, { box: 'border-box' }) + + return () => { + observer.unobserve(element) + } +} + +const addEventListenerOptions = { + passive: true, +} + +export const observeWindowRect = ( + instance: Virtualizer, + cb: (rect: Rect) => void, +) => { + const element = instance.scrollElement + if (!element) { + return + } + + const handler = () => { + cb({ width: element.innerWidth, height: element.innerHeight }) + } + handler() + + element.addEventListener('resize', handler, addEventListenerOptions) + + return () => { + element.removeEventListener('resize', handler) + } +} + +const supportsScrollend = + typeof window == 'undefined' ? true : 'onscrollend' in window + +type ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void + +// Shared core: both element and window variants attach scroll/scrollend +// listeners with the same lifecycle; they only differ in how to read the +// current offset from the scroll target. +const observeOffset = ( + instance: Virtualizer, + cb: ObserveOffsetCallBack, + readOffset: (target: T) => number, +) => { + const element = instance.scrollElement + if (!element) { + return + } + const targetWindow = instance.targetWindow + if (!targetWindow) { + return + } + + const registerScrollendEvent = + instance.options.useScrollendEvent && supportsScrollend + + let offset = 0 + const fallback = registerScrollendEvent + ? null + : debounce( + targetWindow, + () => cb(offset, false), + instance.options.isScrollingResetDelay, + ) + + const createHandler = (isScrolling: boolean) => () => { + offset = readOffset(element) + fallback?.() + cb(offset, isScrolling) + } + const handler = createHandler(true) + const endHandler = createHandler(false) + + element.addEventListener('scroll', handler, addEventListenerOptions) + if (registerScrollendEvent) { + element.addEventListener('scrollend', endHandler, addEventListenerOptions) + } + return () => { + element.removeEventListener('scroll', handler) + if (registerScrollendEvent) { + element.removeEventListener('scrollend', endHandler) + } + } +} + +export const observeElementOffset = ( + instance: Virtualizer, + cb: ObserveOffsetCallBack, +) => + observeOffset(instance, cb, (el) => { + const { horizontal, isRtl } = instance.options + return horizontal ? el.scrollLeft * ((isRtl && -1) || 1) : el.scrollTop + }) + +export const observeWindowOffset = ( + instance: Virtualizer, + cb: ObserveOffsetCallBack, +) => + observeOffset(instance, cb, (win) => + instance.options.horizontal ? win.scrollX : win.scrollY, + ) + +export const measureElement = ( + element: TItemElement, + entry: ResizeObserverEntry | undefined, + instance: Virtualizer, +) => { + // When useCachedMeasurements is enabled, return the cached size + // (or estimateSize as fallback) instead of measuring the DOM. + if (instance.options.useCachedMeasurements) { + const index = instance.indexFromElement(element) + const key = instance.options.getItemKey(index) + return ( + instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index) + ) + } + + if (entry?.borderBoxSize) { + const box = entry.borderBoxSize[0] + if (box) { + const size = Math.round( + box[instance.options.horizontal ? 'inlineSize' : 'blockSize'], + ) + return size + } + } + + // When called without a ResizeObserverEntry (sync measurement path), + // return the previously measured size if available. This avoids a + // synchronous layout read (offsetWidth/offsetHeight) on re-renders. + // The ResizeObserver is already observing the element and will deliver + // the accurate size asynchronously if it changed. + // Users who need synchronous DOM reads can provide a custom measureElement. + if (!entry) { + const index = instance.indexFromElement(element) + const key = instance.options.getItemKey(index) + const cachedSize = instance.itemSizeCache.get(key) + if (cachedSize !== undefined) { + return cachedSize + } + } + + return (element as unknown as HTMLElement)[ + instance.options.horizontal ? 'offsetWidth' : 'offsetHeight' + ] +} + +const scrollWithAdjustments = ( + offset: number, + { + adjustments = 0, + behavior, + }: { adjustments?: number; behavior?: ScrollBehavior }, + instance: Virtualizer, +) => { + instance.scrollElement?.scrollTo?.({ + [instance.options.horizontal ? 'left' : 'top']: offset + adjustments, + behavior, + }) +} + +export const windowScroll: ( + offset: number, + options: { adjustments?: number; behavior?: ScrollBehavior }, + instance: Virtualizer, +) => void = scrollWithAdjustments + +export const elementScroll: ( + offset: number, + options: { adjustments?: number; behavior?: ScrollBehavior }, + instance: Virtualizer, +) => void = scrollWithAdjustments + +type LaneAssignmentMode = 'estimate' | 'measured' + +export interface VirtualizerOptions< + TScrollElement extends Element | Window, + TItemElement extends Element, +> { + // Required from the user + count: number + getScrollElement: () => TScrollElement | null + estimateSize: (index: number) => number + + // Required from the framework adapter (but can be overridden) + scrollToFn: ( + offset: number, + options: { adjustments?: number; behavior?: ScrollBehavior }, + instance: Virtualizer, + ) => void + observeElementRect: ( + instance: Virtualizer, + cb: (rect: Rect) => void, + ) => void | (() => void) + observeElementOffset: ( + instance: Virtualizer, + cb: ObserveOffsetCallBack, + ) => void | (() => void) + // Optional + debug?: boolean + initialRect?: Rect + onChange?: ( + instance: Virtualizer, + sync: boolean, + ) => void + measureElement?: ( + element: TItemElement, + entry: ResizeObserverEntry | undefined, + instance: Virtualizer, + ) => number + overscan?: number + horizontal?: boolean + paddingStart?: number + paddingEnd?: number + scrollPaddingStart?: number + scrollPaddingEnd?: number + initialOffset?: number | (() => number) + getItemKey?: (index: number) => Key + rangeExtractor?: (range: Range) => Array + scrollMargin?: number + gap?: number + indexAttribute?: string + initialMeasurementsCache?: Array + lanes?: number + anchorTo?: ScrollAnchor + followOnAppend?: FollowOnAppend + scrollEndThreshold?: number + isScrollingResetDelay?: number + useScrollendEvent?: boolean + enabled?: boolean + isRtl?: boolean + useAnimationFrameWithResizeObserver?: boolean + laneAssignmentMode?: LaneAssignmentMode + useCachedMeasurements?: boolean +} + +type ScrollState = { + // what we want + index: number | null + align: ScrollAlignment + behavior: ScrollBehavior + + // lifecycle + startedAt: number + + // target tracking + lastTargetOffset: number + + // settling + stableFrames: number +} + +type PendingScrollAnchor = [ + key: Key | null, + offset: number, + followOnAppend: ScrollBehavior | null, + anchorDelta: number, +] + +export class Virtualizer< + TScrollElement extends Element | Window, + TItemElement extends Element, +> { + private unsubs: Array void)> = [] + options!: Required> + scrollElement: TScrollElement | null = null + targetWindow: (Window & typeof globalThis) | null = null + isScrolling = false + private scrollState: ScrollState | null = null + measurementsCache: Array = [] + // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...]. + // null until the first single-lane build; reused (and grown) across rebuilds. + private _flatMeasurements: Float64Array | null = null + itemSizeCache = new Map() + private itemSizeCacheVersion = 0 + private laneAssignments = new Map() // index → lane cache + // Earliest index dirtied since last getMeasurements() rebuild, or null. + private pendingMin: number | null = null + private prevLanes: number | undefined = undefined + private lanesChangedFlag = false + private lanesSettling = false + private pendingScrollAnchor: PendingScrollAnchor | null = null + scrollRect: Rect | null = null + scrollOffset: number | null = null + scrollDirection: ScrollDirection | null = null + scrollAdjustments = 0 + // Sum of size-change deltas above-viewport that were skipped during + // iOS momentum scroll (writing scrollTop mid-momentum cancels it). + // Flushed in a single scrollTo when iOS is fully settled. + private _iosDeferredAdjustment = 0 + // Touch state. iOS WebKit cancels momentum when scrollTop is written, so + // we defer adjustments not only during `isScrolling` but also through the + // touchstart→touchend window (active drag) and a short tail after + // touchend (early-momentum window — iOS only fires touch events once at + // the start of momentum, so we use a timer rather than another event). + private _iosTouching = false + private _iosJustTouchEnded = false + private _iosTouchEndTimerId: number | null = null + // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs) + // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5 + // but the browser reports back 12346, the next reconcileScroll sees a + // "target changed" and re-fires scrollTo — a feedback loop that the + // approxEqual(<1.01) tolerance otherwise absorbs as a workaround. + // By remembering the intended value of our most-recent self-driven + // scrollTo, we can match the browser's rounded read back to the intended + // value when the diff is < 1.5 px, distinguishing it from a real user + // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases. + private _intendedScrollOffset: number | null = null + shouldAdjustScrollPositionOnItemSizeChange: + | undefined + | (( + item: VirtualItem, + delta: number, + instance: Virtualizer, + ) => boolean) + elementsCache = new Map() + private now = () => this.targetWindow?.performance?.now?.() ?? Date.now() + private observer = (() => { + let _ro: ResizeObserver | null = null + + const get = () => { + if (_ro) { + return _ro + } + + if (!this.targetWindow || !this.targetWindow.ResizeObserver) { + return null + } + + return (_ro = new this.targetWindow.ResizeObserver((entries) => { + entries.forEach((entry) => { + const run = () => { + const node = entry.target as TItemElement + const index = this.indexFromElement(node) + + if (!node.isConnected) { + this.observer.unobserve(node) + // Find the cache entry pointing to this exact node and remove + // it. We can't call getItemKey(index) here because items may + // have been removed since this node was rendered — the index + // could be stale and out-of-bounds in the user's data array + // (regression test in e2e/.../stale-index.spec.ts, fix #1148). + // The === comparison naturally handles the React-replaced- + // a-node-for-the-same-key case: that entry now points to a + // different node, so this loop won't match. + for (const [cacheKey, cachedNode] of this.elementsCache) { + if (cachedNode === node) { + this.elementsCache.delete(cacheKey) + break + } + } + return + } + + if (this.shouldMeasureDuringScroll(index)) { + this.resizeItem( + index, + this.options.measureElement(node, entry, this), + ) + } + } + this.options.useAnimationFrameWithResizeObserver + ? requestAnimationFrame(run) + : run() + }) + })) + } + + return { + disconnect: () => { + get()?.disconnect() + _ro = null + }, + observe: (target: Element) => + get()?.observe(target, { box: 'border-box' }), + unobserve: (target: Element) => get()?.unobserve(target), + } + })() + range: { startIndex: number; endIndex: number } | null = null + + constructor(opts: VirtualizerOptions) { + this.setOptions(opts) + } + + setOptions = (opts: VirtualizerOptions) => { + // Skip `{...defaults, ...opts}` because explicit `undefined` values in + // opts would override defaults with `undefined`. + const merged = { + debug: false, + initialOffset: 0, + overscan: 1, + paddingStart: 0, + paddingEnd: 0, + scrollPaddingStart: 0, + scrollPaddingEnd: 0, + horizontal: false, + getItemKey: defaultKeyExtractor, + rangeExtractor: defaultRangeExtractor, + onChange: () => {}, + measureElement, + initialRect: { width: 0, height: 0 }, + scrollMargin: 0, + gap: 0, + indexAttribute: 'data-index', + initialMeasurementsCache: [], + lanes: 1, + anchorTo: 'start', + followOnAppend: false, + scrollEndThreshold: 1, + isScrollingResetDelay: 150, + enabled: true, + isRtl: false, + useScrollendEvent: false, + useAnimationFrameWithResizeObserver: false, + laneAssignmentMode: 'estimate', + useCachedMeasurements: false, + } as unknown as Required> + + for (const key in opts) { + const v = (opts as any)[key] + if (v !== undefined) (merged as any)[key] = v + } + + const prevOptions = this.options as + | Required> + | undefined + let anchor: [Key, number] | null = null + let followOnAppend: ScrollBehavior | null = null + let edgeKeysChanged = false + + if ( + prevOptions !== undefined && + prevOptions.enabled && + merged.enabled && + merged.anchorTo === 'end' && + this.scrollElement !== null + ) { + const prevCount = prevOptions.count + const nextCount = merged.count + const measurements = this.getMeasurements() + const prevFirstKey = + prevCount > 0 + ? (measurements[0]?.key ?? prevOptions.getItemKey(0)) + : null + const prevLastKey = + prevCount > 0 + ? (measurements[prevCount - 1]?.key ?? + prevOptions.getItemKey(prevCount - 1)) + : null + const didCountChange = nextCount !== prevCount + const didEdgeKeysChange = + didCountChange || + (prevCount > 0 && + nextCount > 0 && + (merged.getItemKey(0) !== prevFirstKey || + merged.getItemKey(nextCount - 1) !== prevLastKey)) + + if (didEdgeKeysChange) { + edgeKeysChanged = true + const item = + prevCount > 0 + ? (this.getVirtualItemForOffset(this.getScrollOffset()) ?? + measurements[0]) + : null + + if (item) { + anchor = [item.key, this.getScrollOffset() - item.start] + } + + const behavior = + merged.followOnAppend === true + ? 'auto' + : merged.followOnAppend || null + + if ( + behavior && + nextCount > prevCount && + this.isAtEnd(prevOptions.scrollEndThreshold) && + (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey) + ) { + followOnAppend = behavior + } + } + } + + this.options = merged + + // When edge keys changed (prepend, trim, reorder, etc.) the key→index + // mapping has shifted. Force a full measurement rebuild so the anchor + // resolution below reads positions from the new layout, not the stale + // memoised cache. Without this, a stable `getItemKey` reference + + // unchanged `count` would let getMeasurements() return the old layout. + if (edgeKeysChanged) { + this.pendingMin = 0 + this.itemSizeCacheVersion++ + } + + // Eagerly adjust scrollOffset so the virtualizer computes the correct + // visible range during the current render pass — before _willUpdate + // syncs the DOM scroll position in a layout effect. Without this, + // the virtualizer would render the wrong items for one frame (the + // estimate-based positions are stale) and then correct in the next + // frame, producing a visible "jump" on prepend with dynamic sizes. + let anchorResolved = false + let anchorDelta = 0 + if (anchor && this.scrollOffset !== null) { + const [anchorKey, anchorOffset] = anchor + const newMeasurements = this.getMeasurements() + const { count, getItemKey } = this.options + let idx = 0 + while (idx < count && getItemKey(idx) !== anchorKey) { + idx++ + } + if (idx < count) { + const anchorItem = newMeasurements[idx] + if (anchorItem) { + // Clamp to the reachable range's lower bound — anchorOffset may + // have been derived from a transiently negative scrollOffset + // (rubber-band), and a negative tracked offset never self-heals + // when the element cannot scroll (#1229). + const newOffset = Math.max(0, anchorItem.start + anchorOffset) + if (newOffset !== this.scrollOffset) { + anchorDelta = newOffset - this.scrollOffset + this.scrollOffset = newOffset + anchorResolved = true + } + } + } + } + + if (anchorResolved || followOnAppend) { + this.pendingScrollAnchor = [ + anchorResolved ? anchor![0] : null, + anchorResolved ? anchor![1] : 0, + followOnAppend, + anchorDelta, + ] + } + } + + private notify = (sync: boolean) => { + this.options.onChange?.(this, sync) + } + + // Returns `true` when it performed a synchronous `scrollTop` write this + // tick, `false` when the delta was zero or the write was deferred (iOS). + // `resizeItem` uses that to decide whether the follow-up `notify` must be + // synchronous so the grown transforms commit in the same paint (#1227). + private applyScrollAdjustment( + delta: number, + behavior?: ScrollBehavior, + ): boolean { + if (delta === 0) return false + + if (process.env.NODE_ENV !== 'production' && this.options.debug) { + console.info('correction', delta) + } + + if ( + isIOSWebKit() && + (this.isScrolling || this._iosTouching || this._iosJustTouchEnded) + ) { + this._iosDeferredAdjustment += delta + return false + } else { + this._scrollToOffset(this.getScrollOffset(), { + adjustments: (this.scrollAdjustments += delta), + behavior, + }) + // Eagerly carry the intended target in `scrollOffset` so callers that + // read it before the next scroll event — notably the next `resizeItem` + // tick's `getVirtualDistanceFromEnd()` / `wasAtEnd` check — see the + // post-adjustment position even when the DOM `scrollTop` write was + // clamped because the consumer hasn't grown the sizer yet (`notify()` + // runs after this in `resizeItem`). Same idea as the eager + // `scrollOffset` adjustment for prepend in `setOptions` (#1176). The + // adjustment is now baked into `scrollOffset`, so zero + // `scrollAdjustments` to keep their sum invariant. + if (this.scrollOffset !== null) { + this.scrollOffset += this.scrollAdjustments + // Clamp only the lower bound: a negative offset is unreachable, and + // on an unscrollable element (content fits the viewport) no scroll + // event ever fires to correct it, permanently skewing + // getDistanceFromEnd() and wedging _flushIosDeferredIfReady (#1229). + // Upper-bound overflow stays untouched — it is transiently + // legitimate mid-prepend while the consumer's sizer catches up. + if (this.scrollOffset < 0) this.scrollOffset = 0 + this.scrollAdjustments = 0 + } + return true + } + } + + private maybeNotify = memo( + () => { + this.calculateRange() + + return [ + this.isScrolling, + this.range ? this.range.startIndex : null, + this.range ? this.range.endIndex : null, + ] + }, + (isScrolling) => { + this.notify(isScrolling) + }, + { + key: process.env.NODE_ENV !== 'production' && 'maybeNotify', + debug: () => this.options.debug, + initialDeps: [ + this.isScrolling, + this.range ? this.range.startIndex : null, + this.range ? this.range.endIndex : null, + ] as [boolean, number | null, number | null], + }, + ) + + private cleanup = () => { + this.unsubs.filter(Boolean).forEach((d) => d!()) + this.unsubs = [] + this.observer.disconnect() + if (this.rafId != null && this.targetWindow) { + this.targetWindow.cancelAnimationFrame(this.rafId) + this.rafId = null + } + this.scrollState = null + // The iOS gesture/deferral state is scoped to the current scroll + // element: the touch listeners that maintain it were just removed, and + // an in-flight touch keeps targeting the old element (implicit touch + // capture), so the new element never reports it. Carrying the state + // over would replay a stale deferred delta on the new element's first + // flush, and a cleanup that lands mid-touch or inside the post-touchend + // grace window would strand _iosTouching / _iosJustTouchEnded as true + // (the listener unsub clears the grace timer, and with it the only + // pending reset of the flag), deferring every adjustment on the new + // element until its next touch cycle. + this._iosDeferredAdjustment = 0 + this._iosTouching = false + this._iosJustTouchEnded = false + this.scrollElement = null + this.targetWindow = null + } + + _didMount = () => { + return () => { + this.cleanup() + } + } + + _willUpdate = () => { + const scrollElement = this.options.enabled + ? this.options.getScrollElement() + : null + + if (this.scrollElement !== scrollElement) { + this.cleanup() + + if (!scrollElement) { + this.maybeNotify() + return + } + + this.scrollElement = scrollElement + + if (this.scrollElement && 'ownerDocument' in this.scrollElement) { + this.targetWindow = this.scrollElement.ownerDocument.defaultView + } else { + this.targetWindow = this.scrollElement?.window ?? null + } + + this.elementsCache.forEach((cached) => { + this.observer.observe(cached) + }) + + this.unsubs.push( + this.options.observeElementRect(this, (rect) => { + this.scrollRect = rect + this.maybeNotify() + }), + ) + + this.unsubs.push( + this.options.observeElementOffset(this, (offset, isScrolling) => { + // A scroll event that reports movement but lands on the offset we + // already hold — and isn't a self-write read-back — is a spurious + // no-op re-emit that Safari/Firefox fire after a re-render's layout + // (Chrome doesn't). Treating it as scrolling re-arms `isScrolling`, + // which forces a render that triggers another such event: an + // infinite re-render loop. Ignore it. (Self-writes are handled by + // the `_intendedScrollOffset` reconciliation just below.) + if ( + isScrolling && + this._intendedScrollOffset === null && + offset === this.scrollOffset + ) { + return + } + + // If this scroll event looks like the browser's read-back of a + // value we just wrote, prefer our intended (sub-pixel-accurate) + // value over the browser's rounded one. The 1.5 px tolerance is + // tight enough to avoid mistaking a real user scroll for a + // self-write — by the time the user has moved 1.5 px, the + // intended value will already have been consumed by a prior + // scroll event and cleared. + if ( + this._intendedScrollOffset !== null && + Math.abs(offset - this._intendedScrollOffset) < 1.5 + ) { + offset = this._intendedScrollOffset + } + this._intendedScrollOffset = null + + this.scrollAdjustments = 0 + // If the offset hasn't moved, this is the echo of our own + // adjustment write — `applyScrollAdjustment` already folded it + // into `scrollOffset`. There's no direction to infer, so leave + // it alone; a real gesture always moves the offset. + const prevOffset = this.getScrollOffset() + this.scrollDirection = isScrolling + ? prevOffset === offset + ? this.scrollDirection + : prevOffset < offset + ? 'forward' + : 'backward' + : null + this.scrollOffset = offset + this.isScrolling = isScrolling + + // Flush deferred iOS adjustments if we're now fully settled. + // "Fully settled" means: not actively scrolling, no finger on + // screen, and the post-touchend grace window has expired. + this._flushIosDeferredIfReady() + + if (this.scrollState) { + this.scheduleScrollReconcile() + } + this.maybeNotify() + }), + ) + + // Touch event listeners (iOS-aware deferral). We attach unconditionally + // — the listeners are passive and cheap; on non-touch devices they + // simply never fire. The gating by isIOSWebKit() lives in resizeItem + // and _flushIosDeferredIfReady so we only burn the path on iOS. + if ('addEventListener' in this.scrollElement) { + const scrollEl = this.scrollElement as unknown as EventTarget + const onTouchStart = () => { + this._iosTouching = true + this._iosJustTouchEnded = false + if (this._iosTouchEndTimerId !== null && this.targetWindow != null) { + this.targetWindow.clearTimeout(this._iosTouchEndTimerId) + this._iosTouchEndTimerId = null + } + } + const onTouchEnd = () => { + this._iosTouching = false + if (!isIOSWebKit() || this.targetWindow == null) { + // Non-iOS: nothing more to track. Just clear the touching flag. + return + } + this._iosJustTouchEnded = true + // After ~150 ms with no scroll/touch events, momentum is done. + this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => { + this._iosJustTouchEnded = false + this._iosTouchEndTimerId = null + // After the grace window, attempt to flush. The scroll event + // for momentum decay may have already fired before our timer. + this._flushIosDeferredIfReady() + }, 150) + } + scrollEl.addEventListener( + 'touchstart', + onTouchStart, + addEventListenerOptions, + ) + scrollEl.addEventListener( + 'touchend', + onTouchEnd, + addEventListenerOptions, + ) + this.unsubs.push(() => { + scrollEl.removeEventListener('touchstart', onTouchStart) + scrollEl.removeEventListener('touchend', onTouchEnd) + if (this._iosTouchEndTimerId !== null && this.targetWindow != null) { + this.targetWindow.clearTimeout(this._iosTouchEndTimerId) + this._iosTouchEndTimerId = null + } + }) + } + + this._scrollToOffset(this.getScrollOffset(), { + adjustments: undefined, + behavior: undefined, + }) + } + + const anchor = this.pendingScrollAnchor + this.pendingScrollAnchor = null + + if (anchor && this.scrollElement && this.options.enabled) { + const [key, _offset, followOnAppend, anchorDelta] = anchor + + if (key !== null && !followOnAppend) { + // scrollOffset was eagerly adjusted in setOptions so the + // virtualizer already computed the correct range during render. + // Now sync the browser's actual scroll position to match. + // Skip when followOnAppend is set — scrollToEnd will handle it. + // + // On iOS WebKit, writing scrollTop during touch/momentum cancels + // the in-flight scroll. Defer the DOM sync the same way + // applyScrollAdjustment does — accumulate the delta and let + // _flushIosDeferredIfReady handle it once the scroll settles. + if ( + isIOSWebKit() && + (this.isScrolling || this._iosTouching || this._iosJustTouchEnded) + ) { + if (anchorDelta !== 0) { + this._iosDeferredAdjustment += anchorDelta + } + } else { + this._scrollToOffset(this.getScrollOffset(), { + adjustments: undefined, + behavior: undefined, + }) + } + } + + if (followOnAppend) { + this.scrollToEnd({ behavior: followOnAppend }) + } + } + } + + // Apply any accumulated iOS-deferred scroll adjustment, but only when we're + // truly settled — not actively scrolling, not under an active touch, and + // past the post-touchend grace window. Called from the scroll callback + // and the touchend grace-timer. + private _flushIosDeferredIfReady = () => { + if (this._iosDeferredAdjustment === 0) return + if (this.isScrolling) return + if (this._iosTouching) return + if (this._iosJustTouchEnded) return + // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go + // negative or beyond scrollHeight - clientHeight. Writing scrollTop + // while in that zone snaps the page back to the clamped value at the + // end of the bounce, often discarding the user's intent. Skip the + // flush; the next in-bounds scroll event will retry. + const cur = this.getScrollOffset() + const max = this.getMaxScrollOffset() + if (cur < 0 || cur > max) return + // At the end clamp the browser already absorbed a shrink above the + // viewport (it clamped scrollTop onto the new bottom), so replaying our + // deferred negative delta would lift the view off the bottom — drop it. + // Positive deltas still replay: growth above doesn't clamp. (#1233) + if (this._iosDeferredAdjustment < 0 && cur >= max - 1) { + this._iosDeferredAdjustment = 0 + return + } + const delta = this._iosDeferredAdjustment + this._iosDeferredAdjustment = 0 + // Roll the deferred delta into the running accumulator so any resize + // landing between now and the resulting scroll event computes from the + // post-flush offset rather than the stale one. + this._scrollToOffset(cur, { + adjustments: (this.scrollAdjustments += delta), + behavior: undefined, + }) + } + + private rafId: number | null = null + private scheduleScrollReconcile() { + if (!this.targetWindow) { + this.scrollState = null + return + } + if (this.rafId != null) return + this.rafId = this.targetWindow.requestAnimationFrame(() => { + this.rafId = null + this.reconcileScroll() + }) + } + private reconcileScroll() { + if (!this.scrollState) return + + const el = this.scrollElement + if (!el) return + + // Safety valve: bail out if reconciliation has been running too long + const MAX_RECONCILE_MS = 5000 + if (this.now() - this.scrollState.startedAt > MAX_RECONCILE_MS) { + this.scrollState = null + return + } + + const offsetInfo = + this.scrollState.index != null + ? this.getOffsetForIndex(this.scrollState.index, this.scrollState.align) + : undefined + const targetOffset = offsetInfo + ? offsetInfo[0] + : this.scrollState.lastTargetOffset + + // Require one stable frame where target matches scroll offset. + // approxEqual() already tolerates minor fluctuations, so one frame is sufficient + // to confirm scroll has reached its target without premature cleanup. + const STABLE_FRAMES = 1 + + const targetChanged = targetOffset !== this.scrollState.lastTargetOffset + + if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) { + this.scrollState.stableFrames++ + if (this.scrollState.stableFrames >= STABLE_FRAMES) { + // Final-pass exact landing. The reconcile-stable check uses a 1.01px + // tolerance (approxEqual) so we don't fight subpixel browser rounding + // during the converging phase. Once we're definitively settled, + // commit the exact target so consumers calling scrollToIndex(N) + // end up at the EXACT computed position of item N — matching + // virtuoso's 0px landing accuracy rather than our prior 0.5-1px. + if (this.getScrollOffset() !== targetOffset) { + this._scrollToOffset(targetOffset, { + adjustments: undefined, + behavior: 'auto', + }) + } + this.scrollState = null + return + } + } else { + this.scrollState.stableFrames = 0 + + if (targetChanged) { + // When the target moves during smooth scroll (because items came into + // view and got measured, shifting positions), the original logic was + // to immediately snap to 'auto' — visibly jarring on long + // scroll-to-index calls. Now: keep smooth while we're still far + // (more than a viewport) from the new target. Only fall back to + // 'auto' for the final approach, so the user sees one continuous + // motion that smoothly adjusts its endpoint as measurements arrive. + const viewport = this.getSize() || 600 + const distance = Math.abs(targetOffset - this.getScrollOffset()) + const keepSmooth = + this.scrollState.behavior === 'smooth' && distance > viewport + + this.scrollState.lastTargetOffset = targetOffset + if (!keepSmooth) { + this.scrollState.behavior = 'auto' + } + + this._scrollToOffset(targetOffset, { + adjustments: undefined, + behavior: keepSmooth ? 'smooth' : 'auto', + }) + } + } + + // Always reschedule while scrollState is active to guarantee + // the safety valve timeout runs even if no scroll events fire + // (e.g. no-op scrollToFn, detached element) + this.scheduleScrollReconcile() + } + + private getSize = () => { + if (!this.options.enabled) { + this.scrollRect = null + return 0 + } + + this.scrollRect = this.scrollRect ?? this.options.initialRect + + return this.scrollRect[this.options.horizontal ? 'width' : 'height'] + } + + private getScrollOffset = () => { + if (!this.options.enabled) { + this.scrollOffset = null + return 0 + } + + this.scrollOffset = + this.scrollOffset ?? + (typeof this.options.initialOffset === 'function' + ? this.options.initialOffset() + : this.options.initialOffset) + + return this.scrollOffset + } + + private getMeasurementOptions = memo( + () => [ + this.options.count, + this.options.paddingStart, + this.options.scrollMargin, + this.options.getItemKey, + this.options.enabled, + this.options.lanes, + this.options.laneAssignmentMode, + this.options.gap, + ], + ( + count, + paddingStart, + scrollMargin, + getItemKey, + enabled, + lanes, + laneAssignmentMode, + gap, + ) => { + const lanesChanged = + this.prevLanes !== undefined && this.prevLanes !== lanes + + if (lanesChanged) { + // Set flag for getMeasurements to handle + this.lanesChangedFlag = true + } + + this.prevLanes = lanes + this.pendingMin = null + + return { + count, + paddingStart, + scrollMargin, + getItemKey, + enabled, + lanes, + laneAssignmentMode, + gap, + } + }, + { + key: false, + }, + ) + + private getMeasurements = memo( + () => [this.getMeasurementOptions(), this.itemSizeCacheVersion], + ( + { + count, + paddingStart, + scrollMargin, + getItemKey, + enabled, + lanes, + laneAssignmentMode, + gap, + }, + _itemSizeCacheVersion, + ) => { + const itemSizeCache = this.itemSizeCache + if (!enabled) { + this.measurementsCache = [] + this.itemSizeCache.clear() + this.laneAssignments.clear() + return [] + } + + // Clean up stale lane cache entries when count decreases + if (this.laneAssignments.size > count) { + for (const index of this.laneAssignments.keys()) { + if (index >= count) { + this.laneAssignments.delete(index) + } + } + } + + // ✅ Force complete recalculation when lanes change + if (this.lanesChangedFlag) { + this.lanesChangedFlag = false // Reset immediately + this.lanesSettling = true // Start settling period + this.measurementsCache = [] + this.itemSizeCache.clear() + this.laneAssignments.clear() // Clear lane cache for new lane count + // Force min = 0 on the rebuild + this.pendingMin = null + } + + // Don't restore from initialMeasurementsCache during lane changes + // as it contains stale lane assignments from the previous lane count + if (this.measurementsCache.length === 0 && !this.lanesSettling) { + this.measurementsCache = this.options.initialMeasurementsCache + this.measurementsCache.forEach((item) => { + this.itemSizeCache.set(item.key, item.size) + }) + } + + // During lanes settling, ignore pendingMin to prevent repositioning + const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0) + this.pendingMin = null + + // ✅ End settling period when cache is fully built + if (this.lanesSettling && this.measurementsCache.length === count) { + this.lanesSettling = false + } + + // ─── Fast path: single-lane lazy materialization ──────────────────── + // For lanes === 1 (the default and most common case), skip the + // per-item VirtualItem object allocation. We write start/size pairs + // into a Float64Array and return a Proxy that builds VirtualItem + // objects on demand (only the indices a consumer actually reads). + // + // At n=100k this drops cold-mount cost from ~2.5ms (eager object + // allocation) to roughly the cost of a single typed-array fill. + if (lanes === 1) { + // Reuse flat backing if large enough; else grow (preserving data + // before `min` to mirror the slice-and-rebuild contract). + const need = count * 2 + let flat = this._flatMeasurements + if (!flat || flat.length < need) { + const next = new Float64Array(need) + if (flat && min > 0) next.set(flat.subarray(0, min * 2)) + flat = next + this._flatMeasurements = flat + } + + let runningStart: number + if (min === 0) { + runningStart = paddingStart + scrollMargin + } else { + // Continue from where we left off + const prevIdx = min - 1 + runningStart = flat[prevIdx * 2]! + flat[prevIdx * 2 + 1]! + gap + } + + for (let i = min; i < count; i++) { + const key = getItemKey(i) + const measuredSize = itemSizeCache.get(key) + const size = + typeof measuredSize === 'number' + ? measuredSize + : this.options.estimateSize(i) + flat[i * 2] = runningStart + flat[i * 2 + 1] = size + runningStart += size + gap + } + + const view = createLazyMeasurementsView(count, flat, getItemKey) + this.measurementsCache = view + return view + } + + const measurements = this.measurementsCache.slice(0, min) + + // ✅ Performance: Track last item index per lane for O(1) lookup + const laneLastIndex: Array = new Array(lanes).fill( + undefined, + ) + // Running end position of each lane's last item, so the shortest lane + // can be found with an O(lanes) argmin instead of the old backward walk + // through `measurements` (getFurthestMeasurement). `filledLanes` tracks + // how many lanes have at least one item, mirroring the previous + // "all lanes seen → shortest lane, else i % lanes" branch. + const laneEnds = new Float64Array(lanes) + let filledLanes = 0 + + // Initialize from existing measurements (before min) + for (let m = 0; m < min; m++) { + const item = measurements[m] + if (item) { + if (laneLastIndex[item.lane] === undefined) filledLanes++ + laneLastIndex[item.lane] = m + laneEnds[item.lane] = item.end + } + } + + for (let i = min; i < count; i++) { + const key = getItemKey(i) + + // Check for cached lane assignment + const cachedLane = this.laneAssignments.get(i) + let lane: number + let start: number + + const shouldCacheLane = + laneAssignmentMode === 'estimate' || itemSizeCache.has(key) + + if (cachedLane !== undefined && this.options.lanes > 1) { + // Use cached lane - O(1) lookup for previous item in same lane + lane = cachedLane + const prevIndex = laneLastIndex[lane] + const prevInLane = + prevIndex !== undefined ? measurements[prevIndex] : undefined + start = prevInLane + ? prevInLane.end + gap + : paddingStart + scrollMargin + } else if (filledLanes === lanes) { + // No cache, every lane seeded: place in the shortest lane. + // Read the running per-lane ends (O(lanes) argmin) instead of the + // old backward scan. Tie-break on the lane's last-item index to + // preserve the previous sort-by-(end, index) placement exactly. + let bestLane = 0 + let bestEnd = laneEnds[0]! + let bestIdx = laneLastIndex[0]! + for (let l = 1; l < lanes; l++) { + const e = laneEnds[l]! + if (e < bestEnd || (e === bestEnd && laneLastIndex[l]! < bestIdx)) { + bestLane = l + bestEnd = e + bestIdx = laneLastIndex[l]! + } + } + lane = bestLane + start = bestEnd + gap + + if (shouldCacheLane) { + this.laneAssignments.set(i, lane) + } + } else { + // No cache and not every lane seeded yet — seed lanes in order, + // matching the previous `i % lanes` fallback for the first row. + lane = i % this.options.lanes + start = paddingStart + scrollMargin + + if (shouldCacheLane) { + this.laneAssignments.set(i, lane) + } + } + + const measuredSize = itemSizeCache.get(key) + const size = + typeof measuredSize === 'number' + ? measuredSize + : this.options.estimateSize(i) + + const end = start + size + + measurements[i] = { + index: i, + start, + size, + end, + key, + lane, + } + + // ✅ Performance: Update lane's last item index + running end + if (laneLastIndex[lane] === undefined) filledLanes++ + laneLastIndex[lane] = i + laneEnds[lane] = end + } + + this.measurementsCache = measurements + + return measurements + }, + { + key: process.env.NODE_ENV !== 'production' && 'getMeasurements', + debug: () => this.options.debug, + }, + ) + + calculateRange = memo( + () => [ + this.getMeasurements(), + this.getSize(), + this.getScrollOffset(), + this.options.lanes, + ], + (measurements, outerSize, scrollOffset, lanes) => { + if (measurements.length === 0 || outerSize === 0) { + this.range = null + return null + } + this.range = calculateRangeImpl( + measurements, + outerSize, + scrollOffset, + lanes, + // Pass the typed array so binary search + forward-walk can read + // start/end directly from Float64Array, skipping the Proxy traps. + lanes === 1 && this._flatMeasurements != null + ? this._flatMeasurements + : null, + ) + return this.range + }, + { + key: process.env.NODE_ENV !== 'production' && 'calculateRange', + debug: () => this.options.debug, + }, + ) + + getVirtualIndexes = memo( + () => { + let startIndex: number | null = null + let endIndex: number | null = null + const range = this.calculateRange() + if (range) { + startIndex = range.startIndex + endIndex = range.endIndex + } + this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex]) + return [ + this.options.rangeExtractor, + this.options.overscan, + this.options.count, + startIndex, + endIndex, + ] + }, + (rangeExtractor, overscan, count, startIndex, endIndex) => { + return startIndex === null || endIndex === null + ? [] + : rangeExtractor({ + startIndex, + endIndex, + overscan, + count, + }) + }, + { + key: process.env.NODE_ENV !== 'production' && 'getVirtualIndexes', + debug: () => this.options.debug, + }, + ) + + indexFromElement = (node: TItemElement) => { + const attributeName = this.options.indexAttribute + const indexStr = node.getAttribute(attributeName) + + if (!indexStr) { + console.warn( + `Missing attribute name '${attributeName}={index}' on measured element.`, + ) + return -1 + } + + return parseInt(indexStr, 10) + } + + /** + * Determines if an item at the given index should be measured during smooth scroll. + * During smooth scroll, only items within a buffer range around the target are measured + * to prevent items far from the target from pushing it away. + */ + private shouldMeasureDuringScroll = (index: number): boolean => { + // No scroll state or not smooth scroll - always allow measurements + if (!this.scrollState || this.scrollState.behavior !== 'smooth') { + return true + } + + const scrollIndex = + this.scrollState.index ?? + this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index + + if (scrollIndex !== undefined && this.range) { + // Allow measurements within a buffer range around the scroll target + const bufferSize = Math.max( + this.options.overscan, + Math.ceil((this.range.endIndex - this.range.startIndex) / 2), + ) + const minIndex = Math.max(0, scrollIndex - bufferSize) + const maxIndex = Math.min( + this.options.count - 1, + scrollIndex + bufferSize, + ) + return index >= minIndex && index <= maxIndex + } + + return true + } + + measureElement = (node: TItemElement | null) => { + if (!node) { + this.elementsCache.forEach((cached, key) => { + if (!cached.isConnected) { + this.observer.unobserve(cached) + this.elementsCache.delete(key) + } + }) + return + } + + const index = this.indexFromElement(node) + const key = this.options.getItemKey(index) + const prevNode = this.elementsCache.get(key) + + if (prevNode !== node) { + if (prevNode) { + this.observer.unobserve(prevNode) + } + this.observer.observe(node) + this.elementsCache.set(key, node) + } + + // Sync-measure when idle (initial render) or during programmatic scrolling + // (scrollToIndex/scrollToOffset) where reconcileScroll needs sizes in the same frame. + // During normal user scrolling, skip sync measurement — the RO callback handles it async. + if ( + (!this.isScrolling || this.scrollState) && + this.shouldMeasureDuringScroll(index) + ) { + this.resizeItem(index, this.options.measureElement(node, undefined, this)) + } + } + + resizeItem = (index: number, size: number) => { + if (index < 0 || index >= this.options.count) return + + // Fast field reads. For lanes===1 we read raw start/size from the flat + // typed array, avoiding a Proxy.get + VirtualItem allocation per call. + // For lanes>1 we fall back to the cached VirtualItem array. + let cachedSize: number + let itemStart: number + let key: Key + const flat = this._flatMeasurements + if (this.options.lanes === 1 && flat !== null) { + key = this.options.getItemKey(index) + itemStart = flat[index * 2]! + cachedSize = flat[index * 2 + 1]! + } else { + const item = this.measurementsCache[index] + if (!item) return + key = item.key + itemStart = item.start + cachedSize = item.size + } + + const itemSize = this.itemSizeCache.get(key) ?? cachedSize + const delta = size - itemSize + + if (delta !== 0) { + const wasAtEnd = + this.options.anchorTo === 'end' && + this.scrollState?.behavior !== 'smooth' && + this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold + const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0 + // Default anchoring predicate (used unless the consumer supplies a + // custom shouldAdjustScrollPositionOnItemSizeChange). + const scrollOffsetWithAdj = + this.getScrollOffset() + this.scrollAdjustments + const isFirstMeasure = !this.itemSizeCache.has(key) + const defaultShouldAdjust = isFirstMeasure + ? // First measurement: compensate any item whose top sits above the + // fold — the estimate→actual delta must be corrected regardless of + // scroll direction, since the whole estimated block was above it. + itemStart < scrollOffsetWithAdj + : // Re-measurement: only compensate an item that is ENTIRELY above the + // fold. An item that merely *spans* the fold (top above, bottom + // below — e.g. a streaming chat message growing at its bottom) + // changes size *below* the anchor point, so shifting scrollTop by the + // delta would drag the viewport downward on every growth (#1218). + // Also skip during backward scroll to avoid the "items jump while + // scrolling up" cascade. + itemStart + itemSize <= scrollOffsetWithAdj && + this.scrollDirection !== 'backward' + const shouldAdjustScroll = + this.scrollState?.behavior !== 'smooth' && + (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined + ? this.shouldAdjustScrollPositionOnItemSizeChange( + // The callback expects a VirtualItem; build one lazily only + // when the consumer actually supplied a custom predicate. + this.measurementsCache[index] ?? { + index, + key, + start: itemStart, + size: cachedSize, + end: itemStart + cachedSize, + lane: 0, + }, + delta, + this, + ) + : defaultShouldAdjust) + + if (this.pendingMin === null || index < this.pendingMin) { + this.pendingMin = index + } + this.itemSizeCache.set(key, size) + this.itemSizeCacheVersion++ + + let adjustedSync = false + if (wasAtEnd) { + adjustedSync = this.applyScrollAdjustment( + this.getTotalSize() - prevTotalSize, + ) + } else if (shouldAdjustScroll) { + adjustedSync = this.applyScrollAdjustment(delta) + } + + // When we just moved `scrollTop` to compensate for an above-viewport + // resize, the grown item transforms must commit in the SAME frame as + // that write. `applyScrollAdjustment` writes `scrollTop` synchronously + // inside this ResizeObserver callback, but an async `notify` schedules + // the transform render for a later commit — so the browser can paint + // one frame with the new `scrollTop` and the old positions, and the + // viewport visibly jumps by `delta` before snapping back (#1227). A + // synchronous notify flushes the render in this same callback, so both + // land in one paint. When nothing moved (or the write was deferred on + // iOS), keep the cheaper async notify. + this.notify(adjustedSync) + } + } + + getVirtualItems = memo( + () => [this.getVirtualIndexes(), this.getMeasurements()], + (indexes, measurements) => { + const virtualItems: Array = [] + + for (let k = 0, len = indexes.length; k < len; k++) { + const i = indexes[k]! + const measurement = measurements[i]! + + virtualItems.push(measurement) + } + + return virtualItems + }, + { + key: process.env.NODE_ENV !== 'production' && 'getVirtualItems', + debug: () => this.options.debug, + }, + ) + + getVirtualItemForOffset = (offset: number) => { + const measurements = this.getMeasurements() + if (measurements.length === 0) { + return undefined + } + // Same fast-path as calculateRange: read start values directly from the + // typed array during binary search to skip the Proxy.get materialization + // per probe. + const flat = this._flatMeasurements + const useFlat = this.options.lanes === 1 && flat != null + const idx = findNearestBinarySearch( + 0, + measurements.length - 1, + useFlat + ? (i: number) => flat[i * 2]! + : (i: number) => notUndefined(measurements[i]).start, + offset, + ) + return notUndefined(measurements[idx]) + } + + private getMaxScrollOffset = () => { + if (!this.scrollElement) return 0 + + if ('scrollHeight' in this.scrollElement) { + // Element + return this.options.horizontal + ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth + : this.scrollElement.scrollHeight - this.scrollElement.clientHeight + } else { + // Window + const doc = this.scrollElement.document.documentElement + return this.options.horizontal + ? doc.scrollWidth - this.scrollElement.innerWidth + : doc.scrollHeight - this.scrollElement.innerHeight + } + } + + private getVirtualDistanceFromEnd = () => { + return Math.max( + this.getTotalSize() - this.getSize() - this.getScrollOffset(), + 0, + ) + } + + getDistanceFromEnd = () => { + return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0) + } + + isAtEnd = (threshold = this.options.scrollEndThreshold) => { + return this.getDistanceFromEnd() <= threshold + } + + getOffsetForAlignment = ( + toOffset: number, + align: ScrollAlignment, + itemSize = 0, + ) => { + if (!this.scrollElement) return 0 + + const size = this.getSize() + const scrollOffset = this.getScrollOffset() + + if (align === 'auto') { + align = toOffset >= scrollOffset + size ? 'end' : 'start' + } + + if (align === 'center') { + // When aligning to a particular item (e.g. with scrollToIndex), + // adjust offset by the size of the item to center on the item + toOffset += (itemSize - size) / 2 + } else if (align === 'end') { + toOffset -= size + } + + const maxOffset = this.getMaxScrollOffset() + + return Math.max(Math.min(maxOffset, toOffset), 0) + } + + getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => { + index = Math.max(0, Math.min(index, this.options.count - 1)) + + const size = this.getSize() + const scrollOffset = this.getScrollOffset() + + const item = this.measurementsCache[index] + if (!item) return + + if (align === 'auto') { + if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) { + align = 'end' + } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) { + align = 'start' + } else { + return [scrollOffset, align] as const + } + } + + // For the last item with 'end' alignment, use browser's actual max scroll + // to account for borders/padding that aren't in our measurements + if (align === 'end' && index === this.options.count - 1) { + return [this.getMaxScrollOffset(), align] as const + } + + const toOffset = + align === 'end' + ? item.end + this.options.scrollPaddingEnd + : item.start - this.options.scrollPaddingStart + + return [ + this.getOffsetForAlignment(toOffset, align, item.size), + align, + ] as const + } + + scrollToOffset = ( + toOffset: number, + { align = 'start', behavior = 'auto' }: ScrollToOffsetOptions = {}, + ) => { + // An absolute scroll command derives its target from current + // measurements, so any iOS-deferred compensation still pending is stale by + // definition — the command already accounts for the measurements the delta + // was compensating for. Drop it so _flushIosDeferredIfReady doesn't replay + // it onto the just-established position (relative commands like scrollBy + // intentionally keep the deferral, since they build on the current offset). + this._iosDeferredAdjustment = 0 + + const offset = this.getOffsetForAlignment(toOffset, align) + + const now = this.now() + this.scrollState = { + index: null, + align, + behavior, + startedAt: now, + lastTargetOffset: offset, + stableFrames: 0, + } + + this._scrollToOffset(offset, { adjustments: undefined, behavior }) + + this.scheduleScrollReconcile() + } + + scrollToIndex = ( + index: number, + { + align: initialAlign = 'auto', + behavior = 'auto', + }: ScrollToIndexOptions = {}, + ) => { + // See scrollToOffset: an absolute target invalidates any pending + // iOS-deferred compensation. + this._iosDeferredAdjustment = 0 + + index = Math.max(0, Math.min(index, this.options.count - 1)) + + const offsetInfo = this.getOffsetForIndex(index, initialAlign) + if (!offsetInfo) { + return + } + const [offset, align] = offsetInfo + + const now = this.now() + this.scrollState = { + index, + align, + behavior, + startedAt: now, + lastTargetOffset: offset, + stableFrames: 0, + } + + this._scrollToOffset(offset, { adjustments: undefined, behavior }) + + this.scheduleScrollReconcile() + } + + scrollBy = ( + delta: number, + { behavior = 'auto' }: ScrollToOffsetOptions = {}, + ) => { + const offset = this.getScrollOffset() + delta + const now = this.now() + + this.scrollState = { + index: null, + align: 'start', + behavior, + startedAt: now, + lastTargetOffset: offset, + stableFrames: 0, + } + + this._scrollToOffset(offset, { adjustments: undefined, behavior }) + + this.scheduleScrollReconcile() + } + + scrollToEnd = ({ behavior = 'auto' }: ScrollToEndOptions = {}) => { + if (this.options.count > 0) { + this.scrollToIndex(this.options.count - 1, { + align: 'end', + behavior, + }) + return + } + + this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), { + behavior, + }) + } + + getTotalSize = () => { + const measurements = this.getMeasurements() + + let end: number + // If there are no measurements, set the end to paddingStart + // If there is only one lane, use the last measurement's end + // Otherwise find the maximum end value among all measurements + if (measurements.length === 0) { + end = this.options.paddingStart + } else if (this.options.lanes === 1) { + // Fast path: read last item's end directly from the flat typed array + // when available; avoids a Proxy.get + VirtualItem materialization + // just to call getTotalSize (which React renders trigger every commit). + const lastIdx = measurements.length - 1 + const flat = this._flatMeasurements + if (flat != null) { + end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]! + } else { + end = measurements[lastIdx]?.end ?? 0 + } + } else { + const endByLane = Array(this.options.lanes).fill(null) + let endIndex = measurements.length - 1 + while (endIndex >= 0 && endByLane.some((val) => val === null)) { + const item = measurements[endIndex]! + if (endByLane[item.lane] === null) { + endByLane[item.lane] = item.end + } + + endIndex-- + } + + end = Math.max(...endByLane.filter((val): val is number => val !== null)) + } + + return Math.max( + end - this.options.scrollMargin + this.options.paddingEnd, + 0, + ) + } + + /** + * Returns a snapshot of currently-measured items suitable for round- + * tripping through state storage (sessionStorage, history, etc.) and + * passing back as `initialMeasurementsCache` on remount. Pair with the + * current `scrollOffset` to restore exact scroll position after navigation. + * + * Only items the consumer has actually rendered (and thus measured) appear + * in the snapshot; unmeasured items will fall back to `estimateSize` on + * restore. Returns an empty array if no items have been measured. + */ + takeSnapshot = (): Array => { + const snapshot: Array = [] + if (this.itemSizeCache.size === 0) return snapshot + // Iterate measurementsCache only for indices whose key is in itemSizeCache + // (i.e., have been measured). We build VirtualItem objects with the + // current start/size/end so they can be persisted as plain data. + const m = this.getMeasurements() + for (const item of m) { + if (item && this.itemSizeCache.has(item.key)) { + // Force materialization (lazy path) and copy plain fields. + snapshot.push({ + index: item.index, + key: item.key, + start: item.start, + size: item.size, + end: item.end, + lane: item.lane, + }) + } + } + return snapshot + } + + private _scrollToOffset = ( + offset: number, + { + adjustments, + behavior, + }: { + adjustments: number | undefined + behavior: ScrollBehavior | undefined + }, + ) => { + // Record the intended logical scroll target so the next scroll event + // can reconcile against subpixel rounding by the browser. + this._intendedScrollOffset = offset + (adjustments ?? 0) + this.options.scrollToFn(offset, { behavior, adjustments }, this) + } + + measure = () => { + // Reset pendingMin so the next getMeasurements rebuilds from index 0. + // Without this, a prior resizeItem() that left pendingMin > 0 would + // cause the rebuild to preserve stale items before that index. + this.pendingMin = null + this.itemSizeCache.clear() + this.laneAssignments.clear() // Clear lane cache for full re-layout + this.itemSizeCacheVersion++ + this.notify(false) + } +} + +const findNearestBinarySearch = ( + low: number, + high: number, + getCurrentValue: (i: number) => number, + value: number, +) => { + while (low <= high) { + const middle = ((low + high) / 2) | 0 + const currentValue = getCurrentValue(middle) + + if (currentValue < value) { + low = middle + 1 + } else if (currentValue > value) { + high = middle - 1 + } else { + return middle + } + } + + if (low > 0) { + return low - 1 + } else { + return 0 + } +} + +// Monomorphic Float64Array variant — reads start values directly at stride +// 2 instead of through a getter closure. JITs the inner load to a typed- +// array bounds-check + load with no indirect call. +function findNearestBinarySearchFlat( + flat: Float64Array, + high: number, + value: number, +) { + let low = 0 + while (low <= high) { + const middle = ((low + high) / 2) | 0 + const currentValue = flat[middle * 2]! + + if (currentValue < value) { + low = middle + 1 + } else if (currentValue > value) { + high = middle - 1 + } else { + return middle + } + } + return low > 0 ? low - 1 : 0 +} + +function calculateRangeImpl( + measurements: Array, + outerSize: number, + scrollOffset: number, + lanes: number, + flat: Float64Array | null, +) { + const lastIndex = measurements.length - 1 + + // handle case when item count is less than or equal to lanes + if (measurements.length <= lanes) { + return { startIndex: 0, endIndex: lastIndex } + } + + if (lanes === 1 && flat !== null) { + // Hot single-lane path: typed-array reads, no closures, no Proxy traps. + const startIndex = findNearestBinarySearchFlat( + flat, + lastIndex, + scrollOffset, + ) + let endIndex = startIndex + const limit = scrollOffset + outerSize + while ( + endIndex < lastIndex && + flat[endIndex * 2]! + flat[endIndex * 2 + 1]! < limit + ) { + endIndex++ + } + return { startIndex, endIndex } + } + + // Fallback (lanes > 1 or no flat array): closure-based reads. + const getStart = (index: number) => measurements[index]!.start + let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset) + let endIndex = startIndex + + if (lanes === 1) { + while ( + endIndex < lastIndex && + measurements[endIndex]!.end < scrollOffset + outerSize + ) { + endIndex++ + } + } else if (lanes > 1) { + // Expand forward until we include the visible items from all lanes + // which are closer to the end of the virtualizer window + const endPerLane = Array(lanes).fill(0) + while ( + endIndex < lastIndex && + endPerLane.some((pos) => pos < scrollOffset + outerSize) + ) { + const item = measurements[endIndex]! + endPerLane[item.lane] = item.end + endIndex++ + } + + // Expand backward until we include all lanes' visible items + // closer to the top + const startPerLane = Array(lanes).fill(scrollOffset + outerSize) + while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) { + const item = measurements[startIndex]! + startPerLane[item.lane] = item.start + startIndex-- + } + + // Align startIndex to the beginning of its lane + startIndex = Math.max(0, startIndex - (startIndex % lanes)) + // Align endIndex to the end of its lane + endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - (endIndex % lanes))) + } + + return { startIndex, endIndex } +} diff --git a/node_modules/@tanstack/virtual-core/src/lazy-measurements.ts b/node_modules/@tanstack/virtual-core/src/lazy-measurements.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b8cd425d3c50811aaecc13aac256fee3a3fcd41 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/src/lazy-measurements.ts @@ -0,0 +1,44 @@ +// Lazy materialization for the lanes===1 fast path. Backed by a +// Float64Array (stride 2: start, size, …); VirtualItems are constructed on +// first indexed read and cached. Saves the per-item object allocation at +// large list counts where most items are never visible. + +import type { VirtualItem } from './index' + +type Key = number | string | bigint + +export function createLazyMeasurementsView( + count: number, + flat: Float64Array, + getItemKey: (i: number) => Key, +): Array { + const cache: Array = new Array(count) + return new Proxy(cache as any, { + get(target, prop, receiver) { + if (typeof prop === 'string') { + // Cheap digit-prefix sniff before number coerce. + const c = prop.charCodeAt(0) + if (c >= 48 && c <= 57) { + const i = +prop + if (Number.isInteger(i) && i >= 0 && i < count) { + let v = target[i] + if (!v) { + const s = flat[i * 2]! + v = target[i] = { + index: i, + key: getItemKey(i), + start: s, + size: flat[i * 2 + 1]!, + end: s + flat[i * 2 + 1]!, + lane: 0, + } + } + return v + } + } + if (prop === 'length') return count + } + return Reflect.get(target, prop, receiver) + }, + }) as Array +} diff --git a/node_modules/@tanstack/virtual-core/src/utils.ts b/node_modules/@tanstack/virtual-core/src/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e16080cd0f92c1814b082280a3513debed5e119 --- /dev/null +++ b/node_modules/@tanstack/virtual-core/src/utils.ts @@ -0,0 +1,109 @@ +export type NoInfer = [A][A extends any ? 0 : never] + +export type PartialKeys = Omit & Partial> + +export function memo, TResult>( + getDeps: () => [...TDeps], + fn: (...args: NoInfer<[...TDeps]>) => TResult, + opts: { + key: false | string + debug?: () => boolean + onChange?: (result: TResult) => void + initialDeps?: TDeps + skipInitialOnChange?: boolean + }, +) { + let deps = opts.initialDeps ?? [] + let result: TResult | undefined + let isInitial = true + + function memoizedFunction(): TResult { + // Debug-only timing. In production builds, `process.env.NODE_ENV !== + // 'production'` is constant-folded to `false` by downstream minifiers + // (Terser/esbuild/swc with `define`), which DCEs the entire block. + const debugEnabled = + process.env.NODE_ENV !== 'production' && !!opts.key && !!opts.debug?.() + let depTime = 0 + if (debugEnabled) depTime = Date.now() + + const newDeps = getDeps() + + const depsChanged = + newDeps.length !== deps.length || + newDeps.some((dep: any, index: number) => deps[index] !== dep) + + if (!depsChanged) { + return result! + } + + deps = newDeps + + let resultTime = 0 + if (debugEnabled) resultTime = Date.now() + + result = fn(...newDeps) + + if (debugEnabled) { + const depEndTime = Math.round((Date.now() - depTime) * 100) / 100 + const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100 + const resultFpsPercentage = resultEndTime / 16 + + const pad = (str: number | string, num: number) => { + str = String(str) + while (str.length < num) { + str = ' ' + str + } + return str + } + + console.info( + `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, + ` + font-size: .6rem; + font-weight: bold; + color: hsl(${Math.max( + 0, + Math.min(120 - 120 * resultFpsPercentage, 120), + )}deg 100% 31%);`, + opts?.key, + ) + } + + if (opts?.onChange && !(isInitial && opts.skipInitialOnChange)) { + opts.onChange(result) + } + + isInitial = false + + return result + } + + // Attach updateDeps to the function itself + memoizedFunction.updateDeps = (newDeps: [...TDeps]) => { + deps = newDeps + } + + return memoizedFunction +} + +export function notUndefined(value: T | undefined, msg?: string): T { + if (value === undefined) { + throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`) + } else { + return value + } +} + +export const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1.01 + +export const debounce = ( + targetWindow: Window & typeof globalThis, + fn: Function, + ms: number, +) => { + let timeoutId: number + return function (this: any, ...args: Array) { + targetWindow.clearTimeout(timeoutId) + timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms) + } +} diff --git a/node_modules/@testing-library/dom/LICENSE b/node_modules/@testing-library/dom/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4c43675bc4da5d353732ebb199ebaaf5eeeef014 --- /dev/null +++ b/node_modules/@testing-library/dom/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2017 Kent C. Dodds + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@testing-library/dom/README.md b/node_modules/@testing-library/dom/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2011260acf6436e88aecb2197debae83aac4d3b9 --- /dev/null +++ b/node_modules/@testing-library/dom/README.md @@ -0,0 +1,402 @@ +
+

DOM Testing Library

+ +
+ octopus + + +

Simple and complete DOM testing utilities that encourage good testing +practices.

+ +[**Read the docs**](https://testing-library.com/dom) | +[Edit the docs](https://github.com/testing-library/testing-library-docs) + +
+ +
+ + +[![Build Status][build-badge]][build] +[![Code Coverage][coverage-badge]][coverage] +[![version][version-badge]][package] +[![downloads][downloads-badge]][npmtrends] +[![MIT License][license-badge]][license] +[![All Contributors][all-contributors-badge]](#contributors) +[![PRs Welcome][prs-badge]][prs] +[![Code of Conduct][coc-badge]][coc] +[![Discord][discord-badge]][discord] + +[![Watch on GitHub][github-watch-badge]][github-watch] +[![Star on GitHub][github-star-badge]][github-star] +[![Tweet][twitter-badge]][twitter] + + +
+ + TestingJavaScript.com Learn the smart, efficient way to test any JavaScript application. + +
+ +## Table of Contents + + + + +- [The Problem](#the-problem) +- [This Solution](#this-solution) +- [Installation](#installation) +- [Documentation](#documentation) +- [Guiding Principles](#guiding-principles) +- [Contributors](#contributors) +- [LICENSE](#license) + + + +## The Problem + +You want to write maintainable tests for your Web UI. As a part of this goal, +you want your tests to avoid including implementation details of your components +and rather focus on making your tests give you the confidence for which they are +intended. As part of this, you want your testbase to be maintainable in the long +run so refactors of your components (changes to implementation but not +functionality) don't break your tests and slow you and your team down. + +## This Solution + +The `DOM Testing Library` is a very light-weight solution for testing DOM nodes +(whether simulated with [`JSDOM`](https://github.com/jsdom/jsdom) as provided by +default with [Jest][] or in the browser). The main utilities it provides involve +querying the DOM for nodes in a way that's similar to how the user finds +elements on the page. In this way, the library helps ensure your tests give you +confidence in your UI code. The `DOM Testing Library`'s primary guiding +principle is: + +> [The more your tests resemble the way your software is used, the more +> confidence they can give you.][guiding-principle] + +## Installation + +This module is distributed via [npm][npm] which is bundled with [node][node] and +should be installed as one of your project's `devDependencies`: + +``` +npm install --save-dev @testing-library/dom +``` + +> [**Docs**](https://testing-library.com/docs/install) + +## Documentation + +Read the docs (and discover framework and tool-specific implementations) at +[testing-library.com](https://testing-library.com/dom) + +## Guiding Principles + +> [The more your tests resemble the way your software is used, the more +> confidence they can give you.][guiding-principle] + +We try to only expose methods and utilities that encourage you to write tests +that closely resemble how your web pages are used. + +Utilities are included in this project based on the following guiding +principles: + +1. If it relates to rendering components, it deals with DOM nodes rather than + component instances, nor should it encourage dealing with component + instances. +2. It should be generally useful for testing the application components in the + way the user would use it. We _are_ making some trade-offs here because + we're using a computer and often a simulated browser environment, but in + general, utilities should encourage tests that use the components the way + they're intended to be used. +3. Utility implementations and APIs should be simple and flexible. + +At the end of the day, what we want is for this library to be pretty +light-weight, simple, and understandable. + +## Contributors + +Thanks goes to these people ([emoji key][emojis]): + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Kent C. Dodds
Kent C. Dodds

💻 📖 🚇 ⚠️
Greg Bergé
Greg Bergé

🤔
Ryan Castner
Ryan Castner

📖
Daniel Sandiego
Daniel Sandiego

💻
Paweł Mikołajczyk
Paweł Mikołajczyk

💻
Alejandro Ñáñez Ortiz
Alejandro Ñáñez Ortiz

📖
Matt Parrish
Matt Parrish

🐛 💻 📖 ⚠️
Justin Hall
Justin Hall

📦
Anto Aravinth
Anto Aravinth

💻 ⚠️ 📖
Jonah Moses
Jonah Moses

📖
Łukasz Gandecki
Łukasz Gandecki

💻 ⚠️ 📖
Ivan Babak
Ivan Babak

🐛 🤔 💻 📖
Jesse Day
Jesse Day

💻
Ernesto García
Ernesto García

💬 💻 📖
Josef Maxx Blake
Josef Maxx Blake

💻 📖 ⚠️
Alex Cook
Alex Cook

📖 💡 👀
Daniel Cook
Daniel Cook

💻 📖 ⚠️
Thomas Chia
Thomas Chia

🐛 💻
Tim Deschryver
Tim Deschryver

💻 ⚠️ 👀
Alex Krolick
Alex Krolick

💻
Maddi Joyce
Maddi Joyce

💻
Peter Kamps
Peter Kamps

🐛 💻 ⚠️
Jonathan Stoye
Jonathan Stoye

📖 💻
Sanghyeon Lee
Sanghyeon Lee

💡
Justice Mba
Justice Mba

💻 📖 🤔
Wayne Crouch
Wayne Crouch

💻
Ben Elliott
Ben Elliott

💻
Ruben Costa
Ruben Costa

💻
Robert Smith
Robert Smith

🐛 🤔 📖
dadamssg
dadamssg

💻
Neil Kistner
Neil Kistner

💻 ⚠️
Ben Chauvette
Ben Chauvette

💻
Jeff Baumgardt
Jeff Baumgardt

💻 📖
Matan Kushner
Matan Kushner

💻 📖 🤔 ⚠️
Alex Wendte
Alex Wendte

💻 📖 ⚠️
Tamas Fodor
Tamas Fodor

📖
Benjamin Eckardt
Benjamin Eckardt

💻
Ryan Campbell
Ryan Campbell

📖
Taylor Briggs
Taylor Briggs

⚠️
John Gozde
John Gozde

💻
C. T. Lin
C. T. Lin

📖
Terrence Wong
Terrence Wong

💻
Soo Jae Hwang
Soo Jae Hwang

💻
Royston Shufflebotham
Royston Shufflebotham

🐛 💻 📖 ⚠️
Vadim Brodsky
Vadim Brodsky

💻
Eunjae Lee
Eunjae Lee

💻
David Peter
David Peter

💻
Shy Alter
Shy Alter

💻 📖
Łukasz Makuch
Łukasz Makuch

📦
Tyler Haas
Tyler Haas

💻 ⚠️
Vesa Laakso
Vesa Laakso

💻 ⚠️
Tulsi Sapkota
Tulsi Sapkota

💻
Tiago Nunes
Tiago Nunes

💻 ⚠️
JaxCavalera
JaxCavalera

💻 👀
bopfer
bopfer

⚠️
Jan Pfitzner
Jan Pfitzner

💻
David
David

💻
Diego Hernandez
Diego Hernandez

💻 ⚠️
Alex Young
Alex Young

💻
Paul Armstrong
Paul Armstrong

💻 ⚠️
Tamás Szabó
Tamás Szabó

💻 ⚠️
Dylan Piercey
Dylan Piercey

💻 ⚠️
Michael Lasky
Michael Lasky

💻 ⚠️ 📖
Sebastian Silbermann
Sebastian Silbermann

💻 ⚠️ 📖 🚇 👀
Dylan Vann
Dylan Vann

💻
Adrià Fontcuberta
Adrià Fontcuberta

💻 ⚠️ 📖
Thomas Lombart
Thomas Lombart

💻
Sam Horton
Sam Horton

💻 ⚠️
Andrew Hill
Andrew Hill

💻
Jan Amann
Jan Amann

💻 ⚠️
Brais Piñeiro
Brais Piñeiro

💻 ⚠️
Dominykas Blyžė
Dominykas Blyžė

💻 ⚠️
Olzhas Askar
Olzhas Askar

💻 ⚠️ 📖
Max Belsky
Max Belsky

💻 ⚠️
Michael Mantel
Michael Mantel

⚠️
Tom Nagle
Tom Nagle

💻
Westbrook Johnson
Westbrook Johnson

💻
Mohammad Aziz
Mohammad Aziz

💻 ⚠️
seetdev
seetdev

⚠️ 💻
Xavier Garcia Buils
Xavier Garcia Buils

💻 ⚠️
aw-davidson
aw-davidson

💻 ⚠️
Michaël De Boey
Michaël De Boey

💻
Minh Nguyen
Minh Nguyen

💻
Egill Sveinbjörnsson
Egill Sveinbjörnsson

💻
Pavel Pustovalov
Pavel Pustovalov

📖
Adam Palaniuk
Adam Palaniuk

💻 ⚠️
Yama-Tomo
Yama-Tomo

💻 ⚠️
Aaron Pettengill
Aaron Pettengill

💻 ⚠️
Kate W. Boyd
Kate W. Boyd

💻
Rahul Suryakanth
Rahul Suryakanth

💻 ⚠️
Jamie
Jamie

💻 ⚠️
Nicolas Stepien
Nicolas Stepien

💻
Ken Powers
Ken Powers

💻
Michał Zdunek
Michał Zdunek

💻
Ali Nasserzadeh
Ali Nasserzadeh

💻
Darek Kay
Darek Kay

📖 💻 ⚠️
Lukas
Lukas

💻 ⚠️
Tom Crockett
Tom Crockett

💻 ⚠️
Kevin Brewer
Kevin Brewer

💻 ⚠️
Ben Monro
Ben Monro

💻 🤔 ⚠️ 📖
Stephan Meijer
Stephan Meijer

🤔 💻 ⚠️
João Forja
João Forja

💻 ⚠️
Nick McCurdy
Nick McCurdy

📖 💻 ⚠️ 👀 🚇
Caleb Meredith
Caleb Meredith

💻
Marco Moretti
Marco Moretti

💻 ⚠️ 👀
Travis Jefferson
Travis Jefferson

💻 ⚠️
Maciej Jastrzebski
Maciej Jastrzebski

🐛
Geoff Harcourt
Geoff Harcourt

💻
Josh Goldberg
Josh Goldberg

💻 ⚠️
Ken Gregory
Ken Gregory

💻 ⚠️
Jacob Paris
Jacob Paris

💻 ⚠️
keiya sasaki
keiya sasaki

📖
Idan Entin
Idan Entin

💻 ⚠️
Deniz Susman
Deniz Susman

💻
Bianca Del Carretto
Bianca Del Carretto

⚠️ 💻
Josh Lalonde
Josh Lalonde

💻 ⚠️
Ioannis Papadopoulos
Ioannis Papadopoulos

💻 ⚠️
Maxwell Newlands
Maxwell Newlands

💻 ⚠️
Jared Luxenberg
Jared Luxenberg

💻 ⚠️
snizhana
snizhana

💻 ⚠️
Michael van Engelshoven
Michael van Engelshoven

👀
Asher Tuggle
Asher Tuggle

🐛
Winter LaMon
Winter LaMon

💻 ⚠️
Victor Cordova
Victor Cordova

💻 ⚠️
slowselfip
slowselfip

🐛
Dmitry Semigradsky
Dmitry Semigradsky

💻
Adam
Adam

💻 ⚠️
balavishnuvj
balavishnuvj

💻
Chris Colborne
Chris Colborne

💻
Romain Trotard
Romain Trotard

💻
Thomas Marshall
Thomas Marshall

💻 ⚠️
johnjessewood
johnjessewood

🐛 💻
Ari Perkkiö
Ari Perkkiö

🐛 💻 📖
Nathan Force
Nathan Force

💻
Philipp Fritsche
Philipp Fritsche

💻
Renato Alencar
Renato Alencar

💻 ⚠️
Simen Bekkhus
Simen Bekkhus

🐛
Dan Abramov
Dan Abramov

🐛 👀
Matan Borenkraout
Matan Borenkraout

💻
simcha90
simcha90

💻
Amit Miran
Amit Miran

🚇
Dominik Lesch
Dominik Lesch

📖
Gareth Jones
Gareth Jones

💻 ⚠️
Rayat Rahman
Rayat Rahman

💻
Nik Savchenko
Nik Savchenko

💻
Kevin Fleischman
Kevin Fleischman

💻 ⚠️
Beth Hitch
Beth Hitch

💻
Jack Laurence
Jack Laurence

💻
SantoJambit
SantoJambit

💻
Yashu Mittal
Yashu Mittal

📖
Ian VanSchooten
Ian VanSchooten

💻
Vanya Prokopovich
Vanya Prokopovich

🐛
James Nail
James Nail

🐛
Rob Caldecott
Rob Caldecott

🐛
Dennis273
Dennis273

💻
Jackson Hardaker
Jackson Hardaker

⚠️
Robin Drexler
Robin Drexler

💻
Omer Dolev
Omer Dolev

💻
Lirlev48
Lirlev48

💻
Tarnay Kálmán
Tarnay Kálmán

💻
Than Hutchins
Than Hutchins

💻
Raphaël LEMIEUX
Raphaël LEMIEUX

💻
Arthur Lauck Vilas Boas
Arthur Lauck Vilas Boas

📖
Daniel Acuña
Daniel Acuña

💻
Craig Morten
Craig Morten

💻 💬
Naor Peled
Naor Peled

💻
Julien Wajsberg
Julien Wajsberg

💻 🐛
Kevin BON
Kevin BON

💻 🐛
sieem
sieem

💻
+ + + + + + +This project follows the [all-contributors][all-contributors] specification. +Contributions of any kind welcome! + +## LICENSE + +[MIT](LICENSE) + + + +[npm]: https://www.npmjs.com/ +[node]: https://nodejs.org +[build-badge]: https://img.shields.io/github/workflow/status/testing-library/dom-testing-library/validate?logo=github&style=flat-square +[build]: https://github.com/testing-library/dom-testing-library/actions?query=workflow%3Avalidate +[coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/dom-testing-library.svg?style=flat-square +[coverage]: https://codecov.io/github/testing-library/dom-testing-library +[version-badge]: https://img.shields.io/npm/v/@testing-library/dom.svg?style=flat-square +[package]: https://www.npmjs.com/package/@testing-library/dom +[downloads-badge]: https://img.shields.io/npm/dm/@testing-library/dom.svg?style=flat-square +[npmtrends]: http://www.npmtrends.com/@testing-library/dom +[license-badge]: https://img.shields.io/npm/l/@testing-library/dom.svg?style=flat-square +[license]: https://github.com/testing-library/dom-testing-library/blob/main/LICENSE +[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square +[prs]: http://makeapullrequest.com +[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square +[coc]: https://github.com/testing-library/dom-testing-library/blob/main/CODE_OF_CONDUCT.md +[github-watch-badge]: https://img.shields.io/github/watchers/testing-library/dom-testing-library.svg?style=social +[github-watch]: https://github.com/testing-library/dom-testing-library/watchers +[github-star-badge]: https://img.shields.io/github/stars/testing-library/dom-testing-library.svg?style=social +[github-star]: https://github.com/testing-library/dom-testing-library/stargazers +[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20dom-testing-library%20by%20%40testing-library%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fdom-testing-library%20%F0%9F%91%8D +[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/dom-testing-library.svg?style=social +[emojis]: https://github.com/all-contributors/all-contributors#emoji-key +[all-contributors]: https://github.com/all-contributors/all-contributors +[all-contributors-badge]: https://img.shields.io/github/all-contributors/testing-library/dom-testing-library?color=orange&style=flat-square +[set-immediate]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate +[guiding-principle]: https://twitter.com/kentcdodds/status/977018512689455106 +[jest]: https://facebook.github.io/jest +[discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square +[discord]: https://discord.gg/testing-library + + diff --git a/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js b/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..d23e7ab1e322613392d2ad04263fadee68e10ab1 --- /dev/null +++ b/node_modules/@testing-library/dom/dist/@testing-library/dom.cjs.js @@ -0,0 +1,2951 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var prettyFormat = require('pretty-format'); +var domAccessibilityApi = require('dom-accessibility-api'); +var ariaQuery = require('aria-query'); +var lzString = require('lz-string'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var prettyFormat__namespace = /*#__PURE__*/_interopNamespace(prettyFormat); +var lzString__default = /*#__PURE__*/_interopDefaultLegacy(lzString); + +/** + * Source: https://github.com/facebook/jest/blob/e7bb6a1e26ffab90611b2593912df15b69315611/packages/pretty-format/src/plugins/DOMElement.ts + */ +/* eslint-disable -- trying to stay as close to the original as possible */ +/* istanbul ignore file */ + +function escapeHTML(str) { + return str.replace(//g, '>'); +} +// Return empty string if keys is empty. +const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys.map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = config.spacingOuter + indentationNext + printed + config.spacingOuter + indentation; + } + printed = '{' + printed + '}'; + } + return config.spacingInner + indentation + colors.prop.open + key + colors.prop.close + '=' + colors.value.open + printed + colors.value.close; + }).join(''); +}; + +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants +const NodeTypeTextNode = 3; + +// Return empty string if children is empty. +const printChildren = (children, config, indentation, depth, refs, printer) => children.map(child => { + const printedChild = typeof child === 'string' ? printText(child, config) : printer(child, config, indentation, depth, refs); + if (printedChild === '' && typeof child === 'object' && child !== null && child.nodeType !== NodeTypeTextNode) { + // A plugin serialized this Node to '' meaning we should ignore it. + return ''; + } + return config.spacingOuter + indentation + printedChild; +}).join(''); +const printText = (text, config) => { + const contentColor = config.colors.content; + return contentColor.open + escapeHTML(text) + contentColor.close; +}; +const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return commentColor.open + '' + commentColor.close; +}; + +// Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. +const printElement = (type, printedProps, printedChildren, config, indentation) => { + const tagColor = config.colors.tag; + return tagColor.open + '<' + type + (printedProps && tagColor.close + printedProps + config.spacingOuter + indentation + tagColor.open) + (printedChildren ? '>' + tagColor.close + printedChildren + config.spacingOuter + indentation + tagColor.open + '' + tagColor.close; +}; +const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return tagColor.open + '<' + type + tagColor.close + ' …' + tagColor.open + ' />' + tagColor.close; +}; +const ELEMENT_NODE$1 = 1; +const TEXT_NODE$1 = 3; +const COMMENT_NODE$1 = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; +const isCustomElement = val => { + const { + tagName + } = val; + return Boolean(typeof tagName === 'string' && tagName.includes('-') || typeof val.hasAttribute === 'function' && val.hasAttribute('is')); +}; +const testNode = val => { + const constructorName = val.constructor.name; + const { + nodeType + } = val; + return nodeType === ELEMENT_NODE$1 && (ELEMENT_REGEXP.test(constructorName) || isCustomElement(val)) || nodeType === TEXT_NODE$1 && constructorName === 'Text' || nodeType === COMMENT_NODE$1 && constructorName === 'Comment' || nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment'; +}; +function nodeIsText(node) { + return node.nodeType === TEXT_NODE$1; +} +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE$1; +} +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} +function createDOMElementFilter(filterNode) { + return { + test: val => { + var _val$constructor2; + return ((val == null || (_val$constructor2 = val.constructor) == null ? void 0 : _val$constructor2.name) || isCustomElement(val)) && testNode(val); + }, + serialize: (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return printText(node.data, config); + } + if (nodeIsComment(node)) { + return printComment(node.data, config); + } + const type = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase(); + if (++depth > config.maxDepth) { + return printElementAsLeaf(type, config); + } + return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes).map(attr => attr.name).sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), config, indentation + config.indent, depth, refs, printer), printChildren(Array.prototype.slice.call(node.childNodes || node.children).filter(filterNode), config, indentation + config.indent, depth, refs, printer), config, indentation); + } + }; +} + +// We try to load node dependencies +let picocolors = null; +let readFileSync = null; +let codeFrameColumns = null; +try { + const nodeRequire = module && module.require; + readFileSync = nodeRequire.call(module, 'fs').readFileSync; + codeFrameColumns = nodeRequire.call(module, '@babel/code-frame').codeFrameColumns; + picocolors = nodeRequire.call(module, 'picocolors'); +} catch { + // We're in a browser environment +} + +// frame has the form "at myMethod (location/to/my/file.js:10:2)" +function getCodeFrame(frame) { + const locationStart = frame.indexOf('(') + 1; + const locationEnd = frame.indexOf(')'); + const frameLocation = frame.slice(locationStart, locationEnd); + const frameLocationElements = frameLocation.split(':'); + const [filename, line, column] = [frameLocationElements[0], parseInt(frameLocationElements[1], 10), parseInt(frameLocationElements[2], 10)]; + let rawFileContents = ''; + try { + rawFileContents = readFileSync(filename, 'utf-8'); + } catch { + return ''; + } + const codeFrame = codeFrameColumns(rawFileContents, { + start: { + line, + column + } + }, { + highlightCode: true, + linesBelow: 0 + }); + return picocolors.dim(frameLocation) + "\n" + codeFrame + "\n"; +} +function getUserCodeFrame() { + // If we couldn't load dependencies, we can't generate the user trace + /* istanbul ignore next */ + if (!readFileSync || !codeFrameColumns) { + return ''; + } + const err = new Error(); + const firstClientCodeFrame = err.stack.split('\n').slice(1) // Remove first line which has the form "Error: TypeError" + .find(frame => !frame.includes('node_modules/')); // Ignore frames from 3rd party libraries + + return getCodeFrame(firstClientCodeFrame); +} + +// Constant node.nodeType for text nodes, see: +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#Node_type_constants +const TEXT_NODE = 3; +function jestFakeTimersAreEnabled() { + /* istanbul ignore else */ + // eslint-disable-next-line + if (typeof jest !== 'undefined' && jest !== null) { + return ( + // legacy timers + setTimeout._isMockFunction === true || + // modern timers + // eslint-disable-next-line prefer-object-has-own -- not supported by our support matrix + Object.prototype.hasOwnProperty.call(setTimeout, 'clock') + ); + } + // istanbul ignore next + return false; +} +function getDocument() { + /* istanbul ignore if */ + if (typeof window === 'undefined') { + throw new Error('Could not find default container'); + } + return window.document; +} +function getWindowFromNode(node) { + if (node.defaultView) { + // node is document + return node.defaultView; + } else if (node.ownerDocument && node.ownerDocument.defaultView) { + // node is a DOM node + return node.ownerDocument.defaultView; + } else if (node.window) { + // node is window + return node.window; + } else if (node.ownerDocument && node.ownerDocument.defaultView === null) { + throw new Error("It looks like the window object is not available for the provided node."); + } else if (node.then instanceof Function) { + throw new Error("It looks like you passed a Promise object instead of a DOM node. Did you do something like `fireEvent.click(screen.findBy...` when you meant to use a `getBy` query `fireEvent.click(screen.getBy...`, or await the findBy query `fireEvent.click(await screen.findBy...`?"); + } else if (Array.isArray(node)) { + throw new Error("It looks like you passed an Array instead of a DOM node. Did you do something like `fireEvent.click(screen.getAllBy...` when you meant to use a `getBy` query `fireEvent.click(screen.getBy...`?"); + } else if (typeof node.debug === 'function' && typeof node.logTestingPlaygroundURL === 'function') { + throw new Error("It looks like you passed a `screen` object. Did you do something like `fireEvent.click(screen, ...` when you meant to use a query, e.g. `fireEvent.click(screen.getBy..., `?"); + } else { + // The user passed something unusual to a calling function + throw new Error("The given node is not an Element, the node type is: " + typeof node + "."); + } +} +function checkContainerType(container) { + if (!container || !(typeof container.querySelector === 'function') || !(typeof container.querySelectorAll === 'function')) { + throw new TypeError("Expected container to be an Element, a Document or a DocumentFragment but got " + getTypeName(container) + "."); + } + function getTypeName(object) { + if (typeof object === 'object') { + return object === null ? 'null' : object.constructor.name; + } + return typeof object; + } +} + +const shouldHighlight = () => { + if (typeof process === 'undefined') { + // Don't colorize in non-node environments (e.g. Browsers) + return false; + } + let colors; + // Try to safely parse env COLORS: We will default behavior if any step fails. + try { + var _process$env; + const colorsJSON = (_process$env = process.env) == null ? void 0 : _process$env.COLORS; + if (colorsJSON) { + colors = JSON.parse(colorsJSON); + } + } catch { + // If this throws, process.env?.COLORS wasn't parsable. Since we only + // care about `true` or `false`, we can safely ignore the error. + } + if (typeof colors === 'boolean') { + // If `colors` is set explicitly (both `true` and `false`), use that value. + return colors; + } else { + // If `colors` is not set, colorize if we're in node. + return process.versions !== undefined && process.versions.node !== undefined; + } +}; +const { + DOMCollection +} = prettyFormat__namespace.plugins; + +// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#node_type_constants +const ELEMENT_NODE = 1; +const COMMENT_NODE = 8; + +// https://github.com/facebook/jest/blob/615084195ae1ae61ddd56162c62bbdda17587569/packages/pretty-format/src/plugins/DOMElement.ts#L50 +function filterCommentsAndDefaultIgnoreTagsTags(value) { + return value.nodeType !== COMMENT_NODE && (value.nodeType !== ELEMENT_NODE || !value.matches(getConfig().defaultIgnore)); +} +function prettyDOM(dom, maxLength, options) { + if (options === void 0) { + options = {}; + } + if (!dom) { + dom = getDocument().body; + } + if (typeof maxLength !== 'number') { + maxLength = typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.DEBUG_PRINT_LIMIT || 7000; + } + if (maxLength === 0) { + return ''; + } + if (dom.documentElement) { + dom = dom.documentElement; + } + let domTypeName = typeof dom; + if (domTypeName === 'object') { + domTypeName = dom.constructor.name; + } else { + // To don't fall with `in` operator + dom = {}; + } + if (!('outerHTML' in dom)) { + throw new TypeError("Expected an element or document but got " + domTypeName); + } + const { + filterNode = filterCommentsAndDefaultIgnoreTagsTags, + ...prettyFormatOptions + } = options; + const debugContent = prettyFormat__namespace.format(dom, { + plugins: [createDOMElementFilter(filterNode), DOMCollection], + printFunctionName: false, + highlight: shouldHighlight(), + ...prettyFormatOptions + }); + return maxLength !== undefined && dom.outerHTML.length > maxLength ? debugContent.slice(0, maxLength) + "..." : debugContent; +} +const logDOM = function () { + const userCodeFrame = getUserCodeFrame(); + if (userCodeFrame) { + console.log(prettyDOM(...arguments) + "\n\n" + userCodeFrame); + } else { + console.log(prettyDOM(...arguments)); + } +}; + +// It would be cleaner for this to live inside './queries', but +// other parts of the code assume that all exports from +// './queries' are query functions. +let config = { + testIdAttribute: 'data-testid', + asyncUtilTimeout: 1000, + // asyncWrapper and advanceTimersWrapper is to support React's async `act` function. + // forcing react-testing-library to wrap all async functions would've been + // a total nightmare (consider wrapping every findBy* query and then also + // updating `within` so those would be wrapped too. Total nightmare). + // so we have this config option that's really only intended for + // react-testing-library to use. For that reason, this feature will remain + // undocumented. + asyncWrapper: cb => cb(), + unstable_advanceTimersWrapper: cb => cb(), + eventWrapper: cb => cb(), + // default value for the `hidden` option in `ByRole` queries + defaultHidden: false, + // default value for the `ignore` option in `ByText` queries + defaultIgnore: 'script, style', + // showOriginalStackTrace flag to show the full error stack traces for async errors + showOriginalStackTrace: false, + // throw errors w/ suggestions for better queries. Opt in so off by default. + throwSuggestions: false, + // called when getBy* queries fail. (message, container) => Error + getElementError(message, container) { + const prettifiedDOM = prettyDOM(container); + const error = new Error([message, "Ignored nodes: comments, " + config.defaultIgnore + "\n" + prettifiedDOM].filter(Boolean).join('\n\n')); + error.name = 'TestingLibraryElementError'; + return error; + }, + _disableExpensiveErrorDiagnostics: false, + computedStyleSupportsPseudoElements: false +}; +function runWithExpensiveErrorDiagnosticsDisabled(callback) { + try { + config._disableExpensiveErrorDiagnostics = true; + return callback(); + } finally { + config._disableExpensiveErrorDiagnostics = false; + } +} +function configure(newConfig) { + if (typeof newConfig === 'function') { + // Pass the existing config out to the provided function + // and accept a delta in return + newConfig = newConfig(config); + } + + // Merge the incoming config delta + config = { + ...config, + ...newConfig + }; +} +function getConfig() { + return config; +} + +const labelledNodeNames = ['button', 'meter', 'output', 'progress', 'select', 'textarea', 'input']; +function getTextContent(node) { + if (labelledNodeNames.includes(node.nodeName.toLowerCase())) { + return ''; + } + if (node.nodeType === TEXT_NODE) return node.textContent; + return Array.from(node.childNodes).map(childNode => getTextContent(childNode)).join(''); +} +function getLabelContent(element) { + let textContent; + if (element.tagName.toLowerCase() === 'label') { + textContent = getTextContent(element); + } else { + textContent = element.value || element.textContent; + } + return textContent; +} + +// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352 +function getRealLabels(element) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- types are not aware of older browsers that don't implement `labels` + if (element.labels !== undefined) { + var _labels; + return (_labels = element.labels) != null ? _labels : []; + } + if (!isLabelable(element)) return []; + const labels = element.ownerDocument.querySelectorAll('label'); + return Array.from(labels).filter(label => label.control === element); +} +function isLabelable(element) { + return /BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/.test(element.tagName) || element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden'; +} +function getLabels(container, element, _temp) { + let { + selector = '*' + } = _temp === void 0 ? {} : _temp; + const ariaLabelledBy = element.getAttribute('aria-labelledby'); + const labelsId = ariaLabelledBy ? ariaLabelledBy.split(' ') : []; + return labelsId.length ? labelsId.map(labelId => { + const labellingElement = container.querySelector("[id=\"" + labelId + "\"]"); + return labellingElement ? { + content: getLabelContent(labellingElement), + formControl: null + } : { + content: '', + formControl: null + }; + }) : Array.from(getRealLabels(element)).map(label => { + const textToMatch = getLabelContent(label); + const formControlSelector = 'button, input, meter, output, progress, select, textarea'; + const labelledFormControl = Array.from(label.querySelectorAll(formControlSelector)).filter(formControlElement => formControlElement.matches(selector))[0]; + return { + content: textToMatch, + formControl: labelledFormControl + }; + }); +} + +function assertNotNullOrUndefined(matcher) { + if (matcher === null || matcher === undefined) { + throw new Error(// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- implicitly converting `T` to `string` + "It looks like " + matcher + " was passed instead of a matcher. Did you do something like getByText(" + matcher + ")?"); + } +} +function fuzzyMatches(textToMatch, node, matcher, normalizer) { + if (typeof textToMatch !== 'string') { + return false; + } + assertNotNullOrUndefined(matcher); + const normalizedText = normalizer(textToMatch); + if (typeof matcher === 'string' || typeof matcher === 'number') { + return normalizedText.toLowerCase().includes(matcher.toString().toLowerCase()); + } else if (typeof matcher === 'function') { + return matcher(normalizedText, node); + } else { + return matchRegExp(matcher, normalizedText); + } +} +function matches(textToMatch, node, matcher, normalizer) { + if (typeof textToMatch !== 'string') { + return false; + } + assertNotNullOrUndefined(matcher); + const normalizedText = normalizer(textToMatch); + if (matcher instanceof Function) { + return matcher(normalizedText, node); + } else if (matcher instanceof RegExp) { + return matchRegExp(matcher, normalizedText); + } else { + return normalizedText === String(matcher); + } +} +function getDefaultNormalizer(_temp) { + let { + trim = true, + collapseWhitespace = true + } = _temp === void 0 ? {} : _temp; + return text => { + let normalizedText = text; + normalizedText = trim ? normalizedText.trim() : normalizedText; + normalizedText = collapseWhitespace ? normalizedText.replace(/\s+/g, ' ') : normalizedText; + return normalizedText; + }; +} + +/** + * Constructs a normalizer to pass to functions in matches.js + * @param {boolean|undefined} trim The user-specified value for `trim`, without + * any defaulting having been applied + * @param {boolean|undefined} collapseWhitespace The user-specified value for + * `collapseWhitespace`, without any defaulting having been applied + * @param {Function|undefined} normalizer The user-specified normalizer + * @returns {Function} A normalizer + */ + +function makeNormalizer(_ref) { + let { + trim, + collapseWhitespace, + normalizer + } = _ref; + if (!normalizer) { + // No custom normalizer specified. Just use default. + return getDefaultNormalizer({ + trim, + collapseWhitespace + }); + } + if (typeof trim !== 'undefined' || typeof collapseWhitespace !== 'undefined') { + // They've also specified a value for trim or collapseWhitespace + throw new Error('trim and collapseWhitespace are not supported with a normalizer. ' + 'If you want to use the default trim and collapseWhitespace logic in your normalizer, ' + 'use "getDefaultNormalizer({trim, collapseWhitespace})" and compose that into your normalizer'); + } + return normalizer; +} +function matchRegExp(matcher, text) { + const match = matcher.test(text); + if (matcher.global && matcher.lastIndex !== 0) { + console.warn("To match all elements we had to reset the lastIndex of the RegExp because the global flag is enabled. We encourage to remove the global flag from the RegExp."); + matcher.lastIndex = 0; + } + return match; +} + +function getNodeText(node) { + if (node.matches('input[type=submit], input[type=button], input[type=reset]')) { + return node.value; + } + return Array.from(node.childNodes).filter(child => child.nodeType === TEXT_NODE && Boolean(child.textContent)).map(c => c.textContent).join(''); +} + +const elementRoleList = buildElementRoleList(ariaQuery.elementRoles); + +/** + * @param {Element} element - + * @returns {boolean} - `true` if `element` and its subtree are inaccessible + */ +function isSubtreeInaccessible(element) { + if (element.hidden === true) { + return true; + } + if (element.getAttribute('aria-hidden') === 'true') { + return true; + } + const window = element.ownerDocument.defaultView; + if (window.getComputedStyle(element).display === 'none') { + return true; + } + return false; +} + +/** + * Partial implementation https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion + * which should only be used for elements with a non-presentational role i.e. + * `role="none"` and `role="presentation"` will not be excluded. + * + * Implements aria-hidden semantics (i.e. parent overrides child) + * Ignores "Child Presentational: True" characteristics + * + * @param {Element} element - + * @param {object} [options] - + * @param {function (element: Element): boolean} options.isSubtreeInaccessible - + * can be used to return cached results from previous isSubtreeInaccessible calls + * @returns {boolean} true if excluded, otherwise false + */ +function isInaccessible(element, options) { + if (options === void 0) { + options = {}; + } + const { + isSubtreeInaccessible: isSubtreeInaccessibleImpl = isSubtreeInaccessible + } = options; + const window = element.ownerDocument.defaultView; + // since visibility is inherited we can exit early + if (window.getComputedStyle(element).visibility === 'hidden') { + return true; + } + let currentElement = element; + while (currentElement) { + if (isSubtreeInaccessibleImpl(currentElement)) { + return true; + } + currentElement = currentElement.parentElement; + } + return false; +} +function getImplicitAriaRoles(currentNode) { + // eslint bug here: + // eslint-disable-next-line no-unused-vars + for (const { + match, + roles + } of elementRoleList) { + if (match(currentNode)) { + return [...roles]; + } + } + return []; +} +function buildElementRoleList(elementRolesMap) { + function makeElementSelector(_ref) { + let { + name, + attributes + } = _ref; + return "" + name + attributes.map(_ref2 => { + let { + name: attributeName, + value, + constraints = [] + } = _ref2; + const shouldNotExist = constraints.indexOf('undefined') !== -1; + const shouldBeNonEmpty = constraints.indexOf('set') !== -1; + const hasExplicitValue = typeof value !== 'undefined'; + if (hasExplicitValue) { + return "[" + attributeName + "=\"" + value + "\"]"; + } else if (shouldNotExist) { + return ":not([" + attributeName + "])"; + } else if (shouldBeNonEmpty) { + return "[" + attributeName + "]:not([" + attributeName + "=\"\"])"; + } + return "[" + attributeName + "]"; + }).join(''); + } + function getSelectorSpecificity(_ref3) { + let { + attributes = [] + } = _ref3; + return attributes.length; + } + function bySelectorSpecificity(_ref4, _ref5) { + let { + specificity: leftSpecificity + } = _ref4; + let { + specificity: rightSpecificity + } = _ref5; + return rightSpecificity - leftSpecificity; + } + function match(element) { + let { + attributes = [] + } = element; + + // https://github.com/testing-library/dom-testing-library/issues/814 + const typeTextIndex = attributes.findIndex(attribute => attribute.value && attribute.name === 'type' && attribute.value === 'text'); + if (typeTextIndex >= 0) { + // not using splice to not mutate the attributes array + attributes = [...attributes.slice(0, typeTextIndex), ...attributes.slice(typeTextIndex + 1)]; + } + const selector = makeElementSelector({ + ...element, + attributes + }); + return node => { + if (typeTextIndex >= 0 && node.type !== 'text') { + return false; + } + return node.matches(selector); + }; + } + let result = []; + + // eslint bug here: + // eslint-disable-next-line no-unused-vars + for (const [element, roles] of elementRolesMap.entries()) { + result = [...result, { + match: match(element), + roles: Array.from(roles), + specificity: getSelectorSpecificity(element) + }]; + } + return result.sort(bySelectorSpecificity); +} +function getRoles(container, _temp) { + let { + hidden = false + } = _temp === void 0 ? {} : _temp; + function flattenDOM(node) { + return [node, ...Array.from(node.children).reduce((acc, child) => [...acc, ...flattenDOM(child)], [])]; + } + return flattenDOM(container).filter(element => { + return hidden === false ? isInaccessible(element) === false : true; + }).reduce((acc, node) => { + let roles = []; + // TODO: This violates html-aria which does not allow any role on every element + if (node.hasAttribute('role')) { + roles = node.getAttribute('role').split(' ').slice(0, 1); + } else { + roles = getImplicitAriaRoles(node); + } + return roles.reduce((rolesAcc, role) => Array.isArray(rolesAcc[role]) ? { + ...rolesAcc, + [role]: [...rolesAcc[role], node] + } : { + ...rolesAcc, + [role]: [node] + }, acc); + }, {}); +} +function prettyRoles(dom, _ref6) { + let { + hidden, + includeDescription + } = _ref6; + const roles = getRoles(dom, { + hidden + }); + // We prefer to skip generic role, we don't recommend it + return Object.entries(roles).filter(_ref7 => { + let [role] = _ref7; + return role !== 'generic'; + }).map(_ref8 => { + let [role, elements] = _ref8; + const delimiterBar = '-'.repeat(50); + const elementsString = elements.map(el => { + const nameString = "Name \"" + domAccessibilityApi.computeAccessibleName(el, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + "\":\n"; + const domString = prettyDOM(el.cloneNode(false)); + if (includeDescription) { + const descriptionString = "Description \"" + domAccessibilityApi.computeAccessibleDescription(el, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + "\":\n"; + return "" + nameString + descriptionString + domString; + } + return "" + nameString + domString; + }).join('\n\n'); + return role + ":\n\n" + elementsString + "\n\n" + delimiterBar; + }).join('\n'); +} +const logRoles = function (dom, _temp2) { + let { + hidden = false + } = _temp2 === void 0 ? {} : _temp2; + return console.log(prettyRoles(dom, { + hidden + })); +}; + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)selected, undefined if not selectable + */ +function computeAriaSelected(element) { + // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings + // https://www.w3.org/TR/html-aam-1.0/#details-id-97 + if (element.tagName === 'OPTION') { + return element.selected; + } + + // explicit value + return checkBooleanAttribute(element, 'aria-selected'); +} + +/** + * @param {Element} element - + * @returns {boolean} - + */ +function computeAriaBusy(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-busy + return element.getAttribute('aria-busy') === 'true'; +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)checked, undefined if not checked-able + */ +function computeAriaChecked(element) { + // implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings + // https://www.w3.org/TR/html-aam-1.0/#details-id-56 + // https://www.w3.org/TR/html-aam-1.0/#details-id-67 + if ('indeterminate' in element && element.indeterminate) { + return undefined; + } + if ('checked' in element) { + return element.checked; + } + + // explicit value + return checkBooleanAttribute(element, 'aria-checked'); +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)pressed, undefined if not press-able + */ +function computeAriaPressed(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-pressed + return checkBooleanAttribute(element, 'aria-pressed'); +} + +/** + * @param {Element} element - + * @returns {boolean | string | null} - + */ +function computeAriaCurrent(element) { + var _ref9, _checkBooleanAttribut; + // https://www.w3.org/TR/wai-aria-1.1/#aria-current + return (_ref9 = (_checkBooleanAttribut = checkBooleanAttribute(element, 'aria-current')) != null ? _checkBooleanAttribut : element.getAttribute('aria-current')) != null ? _ref9 : false; +} + +/** + * @param {Element} element - + * @returns {boolean | undefined} - false/true if (not)expanded, undefined if not expand-able + */ +function computeAriaExpanded(element) { + // https://www.w3.org/TR/wai-aria-1.1/#aria-expanded + return checkBooleanAttribute(element, 'aria-expanded'); +} +function checkBooleanAttribute(element, attribute) { + const attributeValue = element.getAttribute(attribute); + if (attributeValue === 'true') { + return true; + } + if (attributeValue === 'false') { + return false; + } + return undefined; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - number if implicit heading or aria-level present, otherwise undefined + */ +function computeHeadingLevel(element) { + // https://w3c.github.io/html-aam/#el-h1-h6 + // https://w3c.github.io/html-aam/#el-h1-h6 + const implicitHeadingLevels = { + H1: 1, + H2: 2, + H3: 3, + H4: 4, + H5: 5, + H6: 6 + }; + // explicit aria-level value + // https://www.w3.org/TR/wai-aria-1.2/#aria-level + const ariaLevelAttribute = element.getAttribute('aria-level') && Number(element.getAttribute('aria-level')); + return ariaLevelAttribute || implicitHeadingLevels[element.tagName]; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueNow(element) { + const valueNow = element.getAttribute('aria-valuenow'); + return valueNow === null ? undefined : +valueNow; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueMax(element) { + const valueMax = element.getAttribute('aria-valuemax'); + return valueMax === null ? undefined : +valueMax; +} + +/** + * @param {Element} element - + * @returns {number | undefined} - + */ +function computeAriaValueMin(element) { + const valueMin = element.getAttribute('aria-valuemin'); + return valueMin === null ? undefined : +valueMin; +} + +/** + * @param {Element} element - + * @returns {string | undefined} - + */ +function computeAriaValueText(element) { + const valueText = element.getAttribute('aria-valuetext'); + return valueText === null ? undefined : valueText; +} + +const normalize = getDefaultNormalizer(); +function escapeRegExp(string) { + return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} +function getRegExpMatcher(string) { + return new RegExp(escapeRegExp(string.toLowerCase()), 'i'); +} +function makeSuggestion(queryName, element, content, _ref) { + let { + variant, + name + } = _ref; + let warning = ''; + const queryOptions = {}; + const queryArgs = [['Role', 'TestId'].includes(queryName) ? content : getRegExpMatcher(content)]; + if (name) { + queryOptions.name = getRegExpMatcher(name); + } + if (queryName === 'Role' && isInaccessible(element)) { + queryOptions.hidden = true; + warning = "Element is inaccessible. This means that the element and all its children are invisible to screen readers.\n If you are using the aria-hidden prop, make sure this is the right choice for your case.\n "; + } + if (Object.keys(queryOptions).length > 0) { + queryArgs.push(queryOptions); + } + const queryMethod = variant + "By" + queryName; + return { + queryName, + queryMethod, + queryArgs, + variant, + warning, + toString() { + if (warning) { + console.warn(warning); + } + let [text, options] = queryArgs; + text = typeof text === 'string' ? "'" + text + "'" : text; + options = options ? ", { " + Object.entries(options).map(_ref2 => { + let [k, v] = _ref2; + return k + ": " + v; + }).join(', ') + " }" : ''; + return queryMethod + "(" + text + options + ")"; + } + }; +} +function canSuggest(currentMethod, requestedMethod, data) { + return data && (!requestedMethod || requestedMethod.toLowerCase() === currentMethod.toLowerCase()); +} +function getSuggestedQuery(element, variant, method) { + var _element$getAttribute, _getImplicitAriaRoles; + if (variant === void 0) { + variant = 'get'; + } + // don't create suggestions for script and style elements + if (element.matches(getConfig().defaultIgnore)) { + return undefined; + } + + //We prefer to suggest something else if the role is generic + const role = (_element$getAttribute = element.getAttribute('role')) != null ? _element$getAttribute : (_getImplicitAriaRoles = getImplicitAriaRoles(element)) == null ? void 0 : _getImplicitAriaRoles[0]; + if (role !== 'generic' && canSuggest('Role', method, role)) { + return makeSuggestion('Role', element, role, { + variant, + name: domAccessibilityApi.computeAccessibleName(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }) + }); + } + const labelText = getLabels(document, element).map(label => label.content).join(' '); + if (canSuggest('LabelText', method, labelText)) { + return makeSuggestion('LabelText', element, labelText, { + variant + }); + } + const placeholderText = element.getAttribute('placeholder'); + if (canSuggest('PlaceholderText', method, placeholderText)) { + return makeSuggestion('PlaceholderText', element, placeholderText, { + variant + }); + } + const textContent = normalize(getNodeText(element)); + if (canSuggest('Text', method, textContent)) { + return makeSuggestion('Text', element, textContent, { + variant + }); + } + if (canSuggest('DisplayValue', method, element.value)) { + return makeSuggestion('DisplayValue', element, normalize(element.value), { + variant + }); + } + const alt = element.getAttribute('alt'); + if (canSuggest('AltText', method, alt)) { + return makeSuggestion('AltText', element, alt, { + variant + }); + } + const title = element.getAttribute('title'); + if (canSuggest('Title', method, title)) { + return makeSuggestion('Title', element, title, { + variant + }); + } + const testId = element.getAttribute(getConfig().testIdAttribute); + if (canSuggest('TestId', method, testId)) { + return makeSuggestion('TestId', element, testId, { + variant + }); + } + return undefined; +} + +// This is so the stack trace the developer sees is one that's +// closer to their code (because async stack traces are hard to follow). +function copyStackTrace(target, source) { + target.stack = source.stack.replace(source.message, target.message); +} +function waitFor(callback, _ref) { + let { + container = getDocument(), + timeout = getConfig().asyncUtilTimeout, + showOriginalStackTrace = getConfig().showOriginalStackTrace, + stackTraceError, + interval = 50, + onTimeout = error => { + Object.defineProperty(error, 'message', { + value: getConfig().getElementError(error.message, container).message + }); + return error; + }, + mutationObserverOptions = { + subtree: true, + childList: true, + attributes: true, + characterData: true + } + } = _ref; + if (typeof callback !== 'function') { + throw new TypeError('Received `callback` arg must be a function'); + } + return new Promise(async (resolve, reject) => { + let lastError, intervalId, observer; + let finished = false; + let promiseStatus = 'idle'; + const overallTimeoutTimer = setTimeout(handleTimeout, timeout); + const usingJestFakeTimers = jestFakeTimersAreEnabled(); + if (usingJestFakeTimers) { + const { + unstable_advanceTimersWrapper: advanceTimersWrapper + } = getConfig(); + checkCallback(); + // this is a dangerous rule to disable because it could lead to an + // infinite loop. However, eslint isn't smart enough to know that we're + // setting finished inside `onDone` which will be called when we're done + // waiting or when we've timed out. + // eslint-disable-next-line no-unmodified-loop-condition + while (!finished) { + if (!jestFakeTimersAreEnabled()) { + const error = new Error("Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830"); + if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); + reject(error); + return; + } + + // In this rare case, we *need* to wait for in-flight promises + // to resolve before continuing. We don't need to take advantage + // of parallelization so we're fine. + // https://stackoverflow.com/a/59243586/971592 + // eslint-disable-next-line no-await-in-loop + await advanceTimersWrapper(async () => { + // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's + // possible that could make this loop go on forever if someone is using + // third party code that's setting up recursive timers so rapidly that + // the user's timer's don't get a chance to resolve. So we'll advance + // by an interval instead. (We have a test for this case). + jest.advanceTimersByTime(interval); + }); + + // Could have timed-out + if (finished) { + break; + } + // It's really important that checkCallback is run *before* we flush + // in-flight promises. To be honest, I'm not sure why, and I can't quite + // think of a way to reproduce the problem in a test, but I spent + // an entire day banging my head against a wall on this. + checkCallback(); + } + } else { + try { + checkContainerType(container); + } catch (e) { + reject(e); + return; + } + intervalId = setInterval(checkRealTimersCallback, interval); + const { + MutationObserver + } = getWindowFromNode(container); + observer = new MutationObserver(checkRealTimersCallback); + observer.observe(container, mutationObserverOptions); + checkCallback(); + } + function onDone(error, result) { + finished = true; + clearTimeout(overallTimeoutTimer); + if (!usingJestFakeTimers) { + clearInterval(intervalId); + observer.disconnect(); + } + if (error) { + reject(error); + } else { + resolve(result); + } + } + function checkRealTimersCallback() { + if (jestFakeTimersAreEnabled()) { + const error = new Error("Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830"); + if (!showOriginalStackTrace) copyStackTrace(error, stackTraceError); + return reject(error); + } else { + return checkCallback(); + } + } + function checkCallback() { + if (promiseStatus === 'pending') return; + try { + const result = runWithExpensiveErrorDiagnosticsDisabled(callback); + if (typeof (result == null ? void 0 : result.then) === 'function') { + promiseStatus = 'pending'; + result.then(resolvedValue => { + promiseStatus = 'resolved'; + onDone(null, resolvedValue); + }, rejectedValue => { + promiseStatus = 'rejected'; + lastError = rejectedValue; + }); + } else { + onDone(null, result); + } + // If `callback` throws, wait for the next mutation, interval, or timeout. + } catch (error) { + // Save the most recent callback error to reject the promise with it in the event of a timeout + lastError = error; + } + } + function handleTimeout() { + let error; + if (lastError) { + error = lastError; + if (!showOriginalStackTrace && error.name === 'TestingLibraryElementError') { + copyStackTrace(error, stackTraceError); + } + } else { + error = new Error('Timed out in waitFor.'); + if (!showOriginalStackTrace) { + copyStackTrace(error, stackTraceError); + } + } + onDone(onTimeout(error), null); + } + }); +} +function waitForWrapper(callback, options) { + // create the error here so its stack trace is as close to the + // calling code as possible + const stackTraceError = new Error('STACK_TRACE_MESSAGE'); + return getConfig().asyncWrapper(() => waitFor(callback, { + stackTraceError, + ...options + })); +} + +/* +eslint + max-lines-per-function: ["error", {"max": 200}], +*/ + +function getElementError(message, container) { + return getConfig().getElementError(message, container); +} +function getMultipleElementsFoundError(message, container) { + return getElementError(message + "\n\n(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).", container); +} +function queryAllByAttribute(attribute, container, text, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll("[" + attribute + "]")).filter(node => matcher(node.getAttribute(attribute), node, text, matchNormalizer)); +} +function queryByAttribute(attribute, container, text, options) { + const els = queryAllByAttribute(attribute, container, text, options); + if (els.length > 1) { + throw getMultipleElementsFoundError("Found multiple elements by [" + attribute + "=" + text + "]", container); + } + return els[0] || null; +} + +// this accepts a query function and returns a function which throws an error +// if more than one elements is returned, otherwise it returns the first +// element or null +function makeSingleQuery(allQuery, getMultipleError) { + return function (container) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + const els = allQuery(container, ...args); + if (els.length > 1) { + const elementStrings = els.map(element => getElementError(null, element).message).join('\n\n'); + throw getMultipleElementsFoundError(getMultipleError(container, ...args) + "\n\nHere are the matching elements:\n\n" + elementStrings, container); + } + return els[0] || null; + }; +} +function getSuggestionError(suggestion, container) { + return getConfig().getElementError("A better query is available, try this:\n" + suggestion.toString() + "\n", container); +} + +// this accepts a query function and returns a function which throws an error +// if an empty list of elements is returned +function makeGetAllQuery(allQuery, getMissingError) { + return function (container) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + const els = allQuery(container, ...args); + if (!els.length) { + throw getConfig().getElementError(getMissingError(container, ...args), container); + } + return els; + }; +} + +// this accepts a getter query function and returns a function which calls +// waitFor and passing a function which invokes the getter. +function makeFindQuery(getter) { + return (container, text, options, waitForOptions) => { + return waitForWrapper(() => { + return getter(container, text, options); + }, { + container, + ...waitForOptions + }); + }; +} +const wrapSingleQueryWithSuggestion = (query, queryAllByName, variant) => function (container) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + const element = query(container, ...args); + const [{ + suggest = getConfig().throwSuggestions + } = {}] = args.slice(-1); + if (element && suggest) { + const suggestion = getSuggestedQuery(element, variant); + if (suggestion && !queryAllByName.endsWith(suggestion.queryName)) { + throw getSuggestionError(suggestion.toString(), container); + } + } + return element; +}; +const wrapAllByQueryWithSuggestion = (query, queryAllByName, variant) => function (container) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + const els = query(container, ...args); + const [{ + suggest = getConfig().throwSuggestions + } = {}] = args.slice(-1); + if (els.length && suggest) { + // get a unique list of all suggestion messages. We are only going to make a suggestion if + // all the suggestions are the same + const uniqueSuggestionMessages = [...new Set(els.map(element => { + var _getSuggestedQuery; + return (_getSuggestedQuery = getSuggestedQuery(element, variant)) == null ? void 0 : _getSuggestedQuery.toString(); + }))]; + if ( + // only want to suggest if all the els have the same suggestion. + uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith( + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime? + getSuggestedQuery(els[0], variant).queryName)) { + throw getSuggestionError(uniqueSuggestionMessages[0], container); + } + } + return els; +}; + +// TODO: This deviates from the published declarations +// However, the implementation always required a dyadic (after `container`) not variadic `queryAllBy` considering the implementation of `makeFindQuery` +// This is at least statically true and can be verified by accepting `QueryMethod` +function buildQueries(queryAllBy, getMultipleError, getMissingError) { + const queryBy = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllBy, getMultipleError), queryAllBy.name, 'query'); + const getAllBy = makeGetAllQuery(queryAllBy, getMissingError); + const getBy = makeSingleQuery(getAllBy, getMultipleError); + const getByWithSuggestions = wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'get'); + const getAllWithSuggestions = wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name.replace('query', 'get'), 'getAll'); + const findAllBy = makeFindQuery(wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name, 'findAll')); + const findBy = makeFindQuery(wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'find')); + return [queryBy, getAllWithSuggestions, getByWithSuggestions, findAllBy, findBy]; +} + +var queryHelpers = /*#__PURE__*/Object.freeze({ + __proto__: null, + getElementError: getElementError, + wrapAllByQueryWithSuggestion: wrapAllByQueryWithSuggestion, + wrapSingleQueryWithSuggestion: wrapSingleQueryWithSuggestion, + getMultipleElementsFoundError: getMultipleElementsFoundError, + queryAllByAttribute: queryAllByAttribute, + queryByAttribute: queryByAttribute, + makeSingleQuery: makeSingleQuery, + makeGetAllQuery: makeGetAllQuery, + makeFindQuery: makeFindQuery, + buildQueries: buildQueries +}); + +function queryAllLabels(container) { + return Array.from(container.querySelectorAll('label,input')).map(node => { + return { + node, + textToMatch: getLabelContent(node) + }; + }).filter(_ref => { + let { + textToMatch + } = _ref; + return textToMatch !== null; + }); +} +const queryAllLabelsByText = function (container, text, _temp) { + let { + exact = true, + trim, + collapseWhitespace, + normalizer + } = _temp === void 0 ? {} : _temp; + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const textToMatchByLabels = queryAllLabels(container); + return textToMatchByLabels.filter(_ref2 => { + let { + node, + textToMatch + } = _ref2; + return matcher(textToMatch, node, text, matchNormalizer); + }).map(_ref3 => { + let { + node + } = _ref3; + return node; + }); +}; +const queryAllByLabelText = function (container, text, _temp2) { + let { + selector = '*', + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp2 === void 0 ? {} : _temp2; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const matchingLabelledElements = Array.from(container.querySelectorAll('*')).filter(element => { + return getRealLabels(element).length || element.hasAttribute('aria-labelledby'); + }).reduce((labelledElements, labelledElement) => { + const labelList = getLabels(container, labelledElement, { + selector + }); + labelList.filter(label => Boolean(label.formControl)).forEach(label => { + if (matcher(label.content, label.formControl, text, matchNormalizer) && label.formControl) { + labelledElements.push(label.formControl); + } + }); + const labelsValue = labelList.filter(label => Boolean(label.content)).map(label => label.content); + if (matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + if (labelsValue.length > 1) { + labelsValue.forEach((labelValue, index) => { + if (matcher(labelValue, labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + const labelsFiltered = [...labelsValue]; + labelsFiltered.splice(index, 1); + if (labelsFiltered.length > 1) { + if (matcher(labelsFiltered.join(' '), labelledElement, text, matchNormalizer)) { + labelledElements.push(labelledElement); + } + } + }); + } + return labelledElements; + }, []).concat(queryAllByAttribute('aria-label', container, text, { + exact, + normalizer: matchNormalizer + })); + return Array.from(new Set(matchingLabelledElements)).filter(element => element.matches(selector)); +}; + +// the getAll* query would normally look like this: +// const getAllByLabelText = makeGetAllQuery( +// queryAllByLabelText, +// (c, text) => `Unable to find a label with the text of: ${text}`, +// ) +// however, we can give a more helpful error message than the generic one, +// so we're writing this one out by hand. +const getAllByLabelText = function (container, text) { + for (var _len = arguments.length, rest = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + rest[_key - 2] = arguments[_key]; + } + const els = queryAllByLabelText(container, text, ...rest); + if (!els.length) { + const labels = queryAllLabelsByText(container, text, ...rest); + if (labels.length) { + const tagNames = labels.map(label => getTagNameOfElementAssociatedWithLabelViaFor(container, label)).filter(tagName => !!tagName); + if (tagNames.length) { + throw getConfig().getElementError(tagNames.map(tagName => "Found a label with the text of: " + text + ", however the element associated with this label (<" + tagName + " />) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a <" + tagName + " />, you can use aria-label or aria-labelledby instead.").join('\n\n'), container); + } else { + throw getConfig().getElementError("Found a label with the text of: " + text + ", however no form control was found associated to that label. Make sure you're using the \"for\" attribute or \"aria-labelledby\" attribute correctly.", container); + } + } else { + throw getConfig().getElementError("Unable to find a label with the text of: " + text, container); + } + } + return els; +}; +function getTagNameOfElementAssociatedWithLabelViaFor(container, label) { + const htmlFor = label.getAttribute('for'); + if (!htmlFor) { + return null; + } + const element = container.querySelector("[id=\"" + htmlFor + "\"]"); + return element ? element.tagName.toLowerCase() : null; +} + +// the reason mentioned above is the same reason we're not using buildQueries +const getMultipleError$7 = (c, text) => "Found multiple elements with the text of: " + text; +const queryByLabelText = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllByLabelText, getMultipleError$7), queryAllByLabelText.name, 'query'); +const getByLabelText = makeSingleQuery(getAllByLabelText, getMultipleError$7); +const findAllByLabelText = makeFindQuery(wrapAllByQueryWithSuggestion(getAllByLabelText, getAllByLabelText.name, 'findAll')); +const findByLabelText = makeFindQuery(wrapSingleQueryWithSuggestion(getByLabelText, getAllByLabelText.name, 'find')); +const getAllByLabelTextWithSuggestions = wrapAllByQueryWithSuggestion(getAllByLabelText, getAllByLabelText.name, 'getAll'); +const getByLabelTextWithSuggestions = wrapSingleQueryWithSuggestion(getByLabelText, getAllByLabelText.name, 'get'); +const queryAllByLabelTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByLabelText, queryAllByLabelText.name, 'queryAll'); + +const queryAllByPlaceholderText = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + checkContainerType(args[0]); + return queryAllByAttribute('placeholder', ...args); +}; +const getMultipleError$6 = (c, text) => "Found multiple elements with the placeholder text of: " + text; +const getMissingError$6 = (c, text) => "Unable to find an element with the placeholder text of: " + text; +const queryAllByPlaceholderTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByPlaceholderText, queryAllByPlaceholderText.name, 'queryAll'); +const [queryByPlaceholderText, getAllByPlaceholderText, getByPlaceholderText, findAllByPlaceholderText, findByPlaceholderText] = buildQueries(queryAllByPlaceholderText, getMultipleError$6, getMissingError$6); + +const queryAllByText = function (container, text, _temp) { + let { + selector = '*', + exact = true, + collapseWhitespace, + trim, + ignore = getConfig().defaultIgnore, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + let baseArray = []; + if (typeof container.matches === 'function' && container.matches(selector)) { + baseArray = [container]; + } + return [...baseArray, ...Array.from(container.querySelectorAll(selector))] + // TODO: `matches` according lib.dom.d.ts can get only `string` but according our code it can handle also boolean :) + .filter(node => !ignore || !node.matches(ignore)).filter(node => matcher(getNodeText(node), node, text, matchNormalizer)); +}; +const getMultipleError$5 = (c, text) => "Found multiple elements with the text: " + text; +const getMissingError$5 = function (c, text, options) { + if (options === void 0) { + options = {}; + } + const { + collapseWhitespace, + trim, + normalizer, + selector + } = options; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + const normalizedText = matchNormalizer(text.toString()); + const isNormalizedDifferent = normalizedText !== text.toString(); + const isCustomSelector = (selector != null ? selector : '*') !== '*'; + return "Unable to find an element with the text: " + (isNormalizedDifferent ? normalizedText + " (normalized from '" + text + "')" : text) + (isCustomSelector ? ", which matches selector '" + selector + "'" : '') + ". This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."; +}; +const queryAllByTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByText, queryAllByText.name, 'queryAll'); +const [queryByText, getAllByText, getByText, findAllByText, findByText] = buildQueries(queryAllByText, getMultipleError$5, getMissingError$5); + +const queryAllByDisplayValue = function (container, value, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll("input,textarea,select")).filter(node => { + if (node.tagName === 'SELECT') { + const selectedOptions = Array.from(node.options).filter(option => option.selected); + return selectedOptions.some(optionNode => matcher(getNodeText(optionNode), optionNode, value, matchNormalizer)); + } else { + return matcher(node.value, node, value, matchNormalizer); + } + }); +}; +const getMultipleError$4 = (c, value) => "Found multiple elements with the display value: " + value + "."; +const getMissingError$4 = (c, value) => "Unable to find an element with the display value: " + value + "."; +const queryAllByDisplayValueWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByDisplayValue, queryAllByDisplayValue.name, 'queryAll'); +const [queryByDisplayValue, getAllByDisplayValue, getByDisplayValue, findAllByDisplayValue, findByDisplayValue] = buildQueries(queryAllByDisplayValue, getMultipleError$4, getMissingError$4); + +// Valid tags are img, input, area and custom elements +const VALID_TAG_REGEXP = /^(img|input|area|.+-.+)$/i; +const queryAllByAltText = function (container, alt, options) { + if (options === void 0) { + options = {}; + } + checkContainerType(container); + return queryAllByAttribute('alt', container, alt, options).filter(node => VALID_TAG_REGEXP.test(node.tagName)); +}; +const getMultipleError$3 = (c, alt) => "Found multiple elements with the alt text: " + alt; +const getMissingError$3 = (c, alt) => "Unable to find an element with the alt text: " + alt; +const queryAllByAltTextWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByAltText, queryAllByAltText.name, 'queryAll'); +const [queryByAltText, getAllByAltText, getByAltText, findAllByAltText, findByAltText] = buildQueries(queryAllByAltText, getMultipleError$3, getMissingError$3); + +const isSvgTitle = node => { + var _node$parentElement; + return node.tagName.toLowerCase() === 'title' && ((_node$parentElement = node.parentElement) == null ? void 0 : _node$parentElement.tagName.toLowerCase()) === 'svg'; +}; +const queryAllByTitle = function (container, text, _temp) { + let { + exact = true, + collapseWhitespace, + trim, + normalizer + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + const matcher = exact ? matches : fuzzyMatches; + const matchNormalizer = makeNormalizer({ + collapseWhitespace, + trim, + normalizer + }); + return Array.from(container.querySelectorAll('[title], svg > title')).filter(node => matcher(node.getAttribute('title'), node, text, matchNormalizer) || isSvgTitle(node) && matcher(getNodeText(node), node, text, matchNormalizer)); +}; +const getMultipleError$2 = (c, title) => "Found multiple elements with the title: " + title + "."; +const getMissingError$2 = (c, title) => "Unable to find an element with the title: " + title + "."; +const queryAllByTitleWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByTitle, queryAllByTitle.name, 'queryAll'); +const [queryByTitle, getAllByTitle, getByTitle, findAllByTitle, findByTitle] = buildQueries(queryAllByTitle, getMultipleError$2, getMissingError$2); + +/* eslint-disable complexity */ +const queryAllByRole = function (container, role, _temp) { + let { + hidden = getConfig().defaultHidden, + name, + description, + queryFallbacks = false, + selected, + busy, + checked, + pressed, + current, + level, + expanded, + value: { + now: valueNow, + min: valueMin, + max: valueMax, + text: valueText + } = {} + } = _temp === void 0 ? {} : _temp; + checkContainerType(container); + if (selected !== undefined) { + var _allRoles$get; + // guard against unknown roles + if (((_allRoles$get = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get.props['aria-selected']) === undefined) { + throw new Error("\"aria-selected\" is not supported on role \"" + role + "\"."); + } + } + if (busy !== undefined) { + var _allRoles$get2; + // guard against unknown roles + if (((_allRoles$get2 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get2.props['aria-busy']) === undefined) { + throw new Error("\"aria-busy\" is not supported on role \"" + role + "\"."); + } + } + if (checked !== undefined) { + var _allRoles$get3; + // guard against unknown roles + if (((_allRoles$get3 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get3.props['aria-checked']) === undefined) { + throw new Error("\"aria-checked\" is not supported on role \"" + role + "\"."); + } + } + if (pressed !== undefined) { + var _allRoles$get4; + // guard against unknown roles + if (((_allRoles$get4 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get4.props['aria-pressed']) === undefined) { + throw new Error("\"aria-pressed\" is not supported on role \"" + role + "\"."); + } + } + if (current !== undefined) { + var _allRoles$get5; + /* istanbul ignore next */ + // guard against unknown roles + // All currently released ARIA versions support `aria-current` on all roles. + // Leaving this for symmetry and forward compatibility + if (((_allRoles$get5 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get5.props['aria-current']) === undefined) { + throw new Error("\"aria-current\" is not supported on role \"" + role + "\"."); + } + } + if (level !== undefined) { + // guard against using `level` option with any role other than `heading` + if (role !== 'heading') { + throw new Error("Role \"" + role + "\" cannot have \"level\" property."); + } + } + if (valueNow !== undefined) { + var _allRoles$get6; + // guard against unknown roles + if (((_allRoles$get6 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get6.props['aria-valuenow']) === undefined) { + throw new Error("\"aria-valuenow\" is not supported on role \"" + role + "\"."); + } + } + if (valueMax !== undefined) { + var _allRoles$get7; + // guard against unknown roles + if (((_allRoles$get7 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get7.props['aria-valuemax']) === undefined) { + throw new Error("\"aria-valuemax\" is not supported on role \"" + role + "\"."); + } + } + if (valueMin !== undefined) { + var _allRoles$get8; + // guard against unknown roles + if (((_allRoles$get8 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get8.props['aria-valuemin']) === undefined) { + throw new Error("\"aria-valuemin\" is not supported on role \"" + role + "\"."); + } + } + if (valueText !== undefined) { + var _allRoles$get9; + // guard against unknown roles + if (((_allRoles$get9 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get9.props['aria-valuetext']) === undefined) { + throw new Error("\"aria-valuetext\" is not supported on role \"" + role + "\"."); + } + } + if (expanded !== undefined) { + var _allRoles$get0; + // guard against unknown roles + if (((_allRoles$get0 = ariaQuery.roles.get(role)) == null ? void 0 : _allRoles$get0.props['aria-expanded']) === undefined) { + throw new Error("\"aria-expanded\" is not supported on role \"" + role + "\"."); + } + } + const subtreeIsInaccessibleCache = new WeakMap(); + function cachedIsSubtreeInaccessible(element) { + if (!subtreeIsInaccessibleCache.has(element)) { + subtreeIsInaccessibleCache.set(element, isSubtreeInaccessible(element)); + } + return subtreeIsInaccessibleCache.get(element); + } + return Array.from(container.querySelectorAll( + // Only query elements that can be matched by the following filters + makeRoleSelector(role))).filter(node => { + const isRoleSpecifiedExplicitly = node.hasAttribute('role'); + if (isRoleSpecifiedExplicitly) { + const roleValue = node.getAttribute('role'); + if (queryFallbacks) { + return roleValue.split(' ').filter(Boolean).some(roleAttributeToken => roleAttributeToken === role); + } + // other wise only send the first token to match + const [firstRoleAttributeToken] = roleValue.split(' '); + return firstRoleAttributeToken === role; + } + const implicitRoles = getImplicitAriaRoles(node); + return implicitRoles.some(implicitRole => { + return implicitRole === role; + }); + }).filter(element => { + if (selected !== undefined) { + return selected === computeAriaSelected(element); + } + if (busy !== undefined) { + return busy === computeAriaBusy(element); + } + if (checked !== undefined) { + return checked === computeAriaChecked(element); + } + if (pressed !== undefined) { + return pressed === computeAriaPressed(element); + } + if (current !== undefined) { + return current === computeAriaCurrent(element); + } + if (expanded !== undefined) { + return expanded === computeAriaExpanded(element); + } + if (level !== undefined) { + return level === computeHeadingLevel(element); + } + if (valueNow !== undefined || valueMax !== undefined || valueMin !== undefined || valueText !== undefined) { + let valueMatches = true; + if (valueNow !== undefined) { + valueMatches && (valueMatches = valueNow === computeAriaValueNow(element)); + } + if (valueMax !== undefined) { + valueMatches && (valueMatches = valueMax === computeAriaValueMax(element)); + } + if (valueMin !== undefined) { + valueMatches && (valueMatches = valueMin === computeAriaValueMin(element)); + } + if (valueText !== undefined) { + var _computeAriaValueText; + valueMatches && (valueMatches = matches((_computeAriaValueText = computeAriaValueText(element)) != null ? _computeAriaValueText : null, element, valueText, text => text)); + } + return valueMatches; + } + // don't care if aria attributes are unspecified + return true; + }).filter(element => { + if (name === undefined) { + // Don't care + return true; + } + return matches(domAccessibilityApi.computeAccessibleName(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }), element, name, text => text); + }).filter(element => { + if (description === undefined) { + // Don't care + return true; + } + return matches(domAccessibilityApi.computeAccessibleDescription(element, { + computedStyleSupportsPseudoElements: getConfig().computedStyleSupportsPseudoElements + }), element, description, text => text); + }).filter(element => { + return hidden === false ? isInaccessible(element, { + isSubtreeInaccessible: cachedIsSubtreeInaccessible + }) === false : true; + }); +}; +function makeRoleSelector(role) { + var _roleElements$get; + const explicitRoleSelector = "*[role~=\"" + role + "\"]"; + const roleRelations = (_roleElements$get = ariaQuery.roleElements.get(role)) != null ? _roleElements$get : new Set(); + const implicitRoleSelectors = new Set(Array.from(roleRelations).map(_ref => { + let { + name + } = _ref; + return name; + })); + + // Current transpilation config sometimes assumes `...` is always applied to arrays. + // `...` is equivalent to `Array.prototype.concat` for arrays. + // If you replace this code with `[explicitRoleSelector, ...implicitRoleSelectors]`, make sure every transpilation target retains the `...` in favor of `Array.prototype.concat`. + return [explicitRoleSelector].concat(Array.from(implicitRoleSelectors)).join(','); +} +const getNameHint = name => { + let nameHint = ''; + if (name === undefined) { + nameHint = ''; + } else if (typeof name === 'string') { + nameHint = " and name \"" + name + "\""; + } else { + nameHint = " and name `" + name + "`"; + } + return nameHint; +}; +const getMultipleError$1 = function (c, role, _temp2) { + let { + name + } = _temp2 === void 0 ? {} : _temp2; + return "Found multiple elements with the role \"" + role + "\"" + getNameHint(name); +}; +const getMissingError$1 = function (container, role, _temp3) { + let { + hidden = getConfig().defaultHidden, + name, + description + } = _temp3 === void 0 ? {} : _temp3; + if (getConfig()._disableExpensiveErrorDiagnostics) { + return "Unable to find role=\"" + role + "\"" + getNameHint(name); + } + let roles = ''; + Array.from(container.children).forEach(childElement => { + roles += prettyRoles(childElement, { + hidden, + includeDescription: description !== undefined + }); + }); + let roleMessage; + if (roles.length === 0) { + if (hidden === false) { + roleMessage = 'There are no accessible roles. But there might be some inaccessible roles. ' + 'If you wish to access them, then set the `hidden` option to `true`. ' + 'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole'; + } else { + roleMessage = 'There are no available roles.'; + } + } else { + roleMessage = ("\nHere are the " + (hidden === false ? 'accessible' : 'available') + " roles:\n\n " + roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n') + "\n").trim(); + } + let nameHint = ''; + if (name === undefined) { + nameHint = ''; + } else if (typeof name === 'string') { + nameHint = " and name \"" + name + "\""; + } else { + nameHint = " and name `" + name + "`"; + } + let descriptionHint = ''; + if (description === undefined) { + descriptionHint = ''; + } else if (typeof description === 'string') { + descriptionHint = " and description \"" + description + "\""; + } else { + descriptionHint = " and description `" + description + "`"; + } + return ("\nUnable to find an " + (hidden === false ? 'accessible ' : '') + "element with the role \"" + role + "\"" + nameHint + descriptionHint + "\n\n" + roleMessage).trim(); +}; +const queryAllByRoleWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByRole, queryAllByRole.name, 'queryAll'); +const [queryByRole, getAllByRole, getByRole, findAllByRole, findByRole] = buildQueries(queryAllByRole, getMultipleError$1, getMissingError$1); + +const getTestIdAttribute = () => getConfig().testIdAttribute; +const queryAllByTestId = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + checkContainerType(args[0]); + return queryAllByAttribute(getTestIdAttribute(), ...args); +}; +const getMultipleError = (c, id) => "Found multiple elements by: [" + getTestIdAttribute() + "=\"" + id + "\"]"; +const getMissingError = (c, id) => "Unable to find an element by: [" + getTestIdAttribute() + "=\"" + id + "\"]"; +const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion(queryAllByTestId, queryAllByTestId.name, 'queryAll'); +const [queryByTestId, getAllByTestId, getByTestId, findAllByTestId, findByTestId] = buildQueries(queryAllByTestId, getMultipleError, getMissingError); + +var queries = /*#__PURE__*/Object.freeze({ + __proto__: null, + queryAllByLabelText: queryAllByLabelTextWithSuggestions, + queryByLabelText: queryByLabelText, + getAllByLabelText: getAllByLabelTextWithSuggestions, + getByLabelText: getByLabelTextWithSuggestions, + findAllByLabelText: findAllByLabelText, + findByLabelText: findByLabelText, + queryByPlaceholderText: queryByPlaceholderText, + queryAllByPlaceholderText: queryAllByPlaceholderTextWithSuggestions, + getByPlaceholderText: getByPlaceholderText, + getAllByPlaceholderText: getAllByPlaceholderText, + findAllByPlaceholderText: findAllByPlaceholderText, + findByPlaceholderText: findByPlaceholderText, + queryByText: queryByText, + queryAllByText: queryAllByTextWithSuggestions, + getByText: getByText, + getAllByText: getAllByText, + findAllByText: findAllByText, + findByText: findByText, + queryByDisplayValue: queryByDisplayValue, + queryAllByDisplayValue: queryAllByDisplayValueWithSuggestions, + getByDisplayValue: getByDisplayValue, + getAllByDisplayValue: getAllByDisplayValue, + findAllByDisplayValue: findAllByDisplayValue, + findByDisplayValue: findByDisplayValue, + queryByAltText: queryByAltText, + queryAllByAltText: queryAllByAltTextWithSuggestions, + getByAltText: getByAltText, + getAllByAltText: getAllByAltText, + findAllByAltText: findAllByAltText, + findByAltText: findByAltText, + queryByTitle: queryByTitle, + queryAllByTitle: queryAllByTitleWithSuggestions, + getByTitle: getByTitle, + getAllByTitle: getAllByTitle, + findAllByTitle: findAllByTitle, + findByTitle: findByTitle, + queryByRole: queryByRole, + queryAllByRole: queryAllByRoleWithSuggestions, + getAllByRole: getAllByRole, + getByRole: getByRole, + findAllByRole: findAllByRole, + findByRole: findByRole, + queryByTestId: queryByTestId, + queryAllByTestId: queryAllByTestIdWithSuggestions, + getByTestId: getByTestId, + getAllByTestId: getAllByTestId, + findAllByTestId: findAllByTestId, + findByTestId: findByTestId +}); + +/** + * @typedef {{[key: string]: Function}} FuncMap + */ + +/** + * @param {HTMLElement} element container + * @param {FuncMap} queries object of functions + * @param {Object} initialValue for reducer + * @returns {FuncMap} returns object of functions bound to container + */ +function getQueriesForElement(element, queries$1, initialValue) { + if (queries$1 === void 0) { + queries$1 = queries; + } + if (initialValue === void 0) { + initialValue = {}; + } + return Object.keys(queries$1).reduce((helpers, key) => { + const fn = queries$1[key]; + helpers[key] = fn.bind(null, element); + return helpers; + }, initialValue); +} + +const isRemoved = result => !result || Array.isArray(result) && !result.length; + +// Check if the element is not present. +// As the name implies, waitForElementToBeRemoved should check `present` --> `removed` +function initialCheck(elements) { + if (isRemoved(elements)) { + throw new Error('The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.'); + } +} +async function waitForElementToBeRemoved(callback, options) { + // created here so we get a nice stacktrace + const timeoutError = new Error('Timed out in waitForElementToBeRemoved.'); + if (typeof callback !== 'function') { + initialCheck(callback); + const elements = Array.isArray(callback) ? callback : [callback]; + const getRemainingElements = elements.map(element => { + let parent = element.parentElement; + if (parent === null) return () => null; + while (parent.parentElement) parent = parent.parentElement; + return () => parent.contains(element) ? element : null; + }); + callback = () => getRemainingElements.map(c => c()).filter(Boolean); + } + initialCheck(callback()); + return waitForWrapper(() => { + let result; + try { + result = callback(); + } catch (error) { + if (error.name === 'TestingLibraryElementError') { + return undefined; + } + throw error; + } + if (!isRemoved(result)) { + throw timeoutError; + } + return undefined; + }, options); +} + +/* +eslint + require-await: "off" +*/ + +const eventMap = { + // Clipboard Events + copy: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + cut: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + paste: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Composition Events + compositionEnd: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + compositionStart: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + compositionUpdate: { + EventType: 'CompositionEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Keyboard Events + keyDown: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + keyPress: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + keyUp: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + charCode: 0, + composed: true + } + }, + // Focus Events + focus: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + blur: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + focusIn: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + focusOut: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + // Form Events + change: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + input: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + invalid: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: true + } + }, + submit: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + }, + reset: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + }, + // Mouse Events + click: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + button: 0, + composed: true + } + }, + contextMenu: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dblClick: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + drag: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragEnd: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragEnter: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragExit: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragLeave: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + dragOver: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dragStart: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + drop: { + EventType: 'DragEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseDown: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseEnter: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseLeave: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseMove: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseOut: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseOver: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseUp: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Selection Events + select: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + // Touch Events + touchCancel: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + touchEnd: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + touchMove: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + touchStart: { + EventType: 'TouchEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // UI Events + resize: { + EventType: 'UIEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + scroll: { + EventType: 'UIEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + // Wheel Events + wheel: { + EventType: 'WheelEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + // Media Events + abort: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + canPlay: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + canPlayThrough: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + durationChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + emptied: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + encrypted: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + ended: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadedData: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadedMetadata: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + loadStart: { + EventType: 'ProgressEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + pause: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + play: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + playing: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + progress: { + EventType: 'ProgressEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + rateChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + seeked: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + seeking: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + stalled: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + suspend: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + timeUpdate: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + volumeChange: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + waiting: { + EventType: 'Event', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + // Events + load: { + // TODO: load events can be UIEvent or Event depending on what generated them + // This is where this abstraction breaks down. + // But the common targets are , or