From 5384225cc6639fa611a6d503297e5bc149e4b592 Mon Sep 17 00:00:00 2001 From: dev-intj <42313770+sudo-ezekiel@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:35:03 +0300 Subject: [PATCH 1/4] feat: headless useVirtualWindow, viewport reveal, and scroll control The windowing engine becomes a public hook. useVirtualWindow takes a count and an estimated size and returns the items to render with their offsets, a ref for the scroll container, a per-item ref that measures rows and corrects the offsets below them, totalSize for the sizer, and scrollToIndex / scrollToOffset. It renders nothing and owns no styles, so it fits a table, a grid, or a scroller that already exists. VirtualRenderWave is now built on it. New on the component: revealMode "viewport", which reveals the rows inside the rendered window rather than counting forward from startIndex, so a small batchSize still fills the screen on a long list; initialScrollOffset and initialScrollIndex, both read once, so the first paint and the server markup already show that window; onRangeChange, called after commit whenever the rendered or visible range moves. The handle's scrollTo now accepts { align, behavior } alongside the old behavior string. The height cache is replaced by a keyed size cache, so a measured row keeps its height across a reorder when getItemKey is set. Fixes carried in the same change: - React 18 could not attach a ref to a forwardRef outerElement or innerElement, so the list could not scroll or measure. A dev-only console.error now names a wrapper that swallows the ref. - Package types did not resolve under Node16/NodeNext from either CJS or ESM. The exports map carries a types entry per condition and the build emits both .d.ts and .d.cts. - onEndReached never fired when the content was shorter than the viewport. - Programmatic scrolls near the end of a list of taller-than-estimated rows stopped short of the target and never re-aimed. - initialScrollIndex ignored scrollMargin on the first render. - align "auto" oscillated on an item taller than the viewport. - scrollToIndex(NaN), scrollToOffset(NaN) and a non-finite initialScrollOffset reset the position to the top instead of being ignored. - An itemHeight or estimateSize of 0, NaN or Infinity mounted every row, and a negative or NaN overscan rendered none. - keyboardNavigation took the arrows, Home, End and the page keys from a focused control inside a row. - The fade-in ignored prefers-reduced-motion. - The ref-swallowing warning fired twice under StrictMode. WrapperProps.ref is now optional and typed RefObject, and WrapperComponent may return a promise. That is source-breaking for code reading props.ref.current, and it is what makes a custom wrapper compile in shapes other than a forwardRef typed for HTMLElement. --- demo/main.tsx | 149 ++- package-lock.json | 1704 +++++++++++++++++++++++++- package.json | 31 +- src/VirtualRenderWave.tsx | 356 +++--- src/index.ts | 14 + src/{heightCache.ts => sizeCache.ts} | 54 +- src/types.ts | 71 +- src/useRenderWave.ts | 3 - src/useViewportReveal.ts | 146 +++ src/useVirtualWindow.ts | 754 ++++++++++++ test/heightCache.test.ts | 95 -- tsconfig.build.json | 2 - vite.config.ts | 12 + 13 files changed, 3052 insertions(+), 339 deletions(-) rename src/{heightCache.ts => sizeCache.ts} (50%) create mode 100644 src/useViewportReveal.ts create mode 100644 src/useVirtualWindow.ts delete mode 100644 test/heightCache.test.ts diff --git a/demo/main.tsx b/demo/main.tsx index a2aa5fb..86728b7 100644 --- a/demo/main.tsx +++ b/demo/main.tsx @@ -3,6 +3,10 @@ import { createRoot } from "react-dom/client"; import { RenderWave, VirtualRenderWave, + useVirtualWindow, + type RevealMode, + type ScrollAlign, + type VirtualRange, type VirtualRenderWaveHandle, } from "../src/index"; @@ -33,7 +37,11 @@ function VirtualDemo() { const [snapToBatch, setSnapToBatch] = useState(false); const [transition, setTransition] = useState(true); const [dynamicHeights, setDynamicHeights] = useState(false); + const [revealMode, setRevealMode] = useState("viewport"); + const [batchSize, setBatchSize] = useState(20); const [targetIndex, setTargetIndex] = useState(500); + const [align, setAlign] = useState("start"); + const [range, setRange] = useState(null); const handle = useRef(null); const loadMore = useCallback(() => { @@ -47,7 +55,8 @@ function VirtualDemo() { {rows.length.toLocaleString()} rows, windowed rendering, wave reveal, sticky group headers, keyboard navigation (focus the list, then use the arrow keys, PageUp/PageDown, Home and End). Scrolling to the bottom - appends 500 more rows. + appends 500 more rows. In viewport mode the wave follows the window, so + a small batch size still fills the screen quickly.

+ + -
+

+ {range + ? `onRangeChange: rendering ${range.start} to ${range.end}, ${ + range.visibleEnd - range.visibleStart + } rows in view (${range.visibleStart} to ${range.visibleEnd}).` + : "onRangeChange has not fired yet."} +

row.id} @@ -139,6 +190,97 @@ function VirtualDemo() { ); } +type Message = { id: number; author: string; body: string }; + +const MESSAGES: Message[] = Array.from({ length: 5000 }, (_, i) => ({ + id: i, + author: `user${i % 37}`, + body: LOREM.repeat(1 + (i % 5)).slice(0, 40 + ((i * 37) % 260)), +})); + +function HookDemo() { + const [range, setRange] = useState(null); + const getItemKey = useCallback((index: number) => MESSAGES[index].id, []); + + const { + scrollRef, + measureRef, + virtualItems, + totalSize, + scrollToIndex, + start, + end, + } = useVirtualWindow({ + count: MESSAGES.length, + estimateSize: 72, + overscan: 4, + getItemKey, + initialScrollIndex: 2500, + initialViewportSize: 320, + onRangeChange: setRange, + }); + + return ( +
+

useVirtualWindow

+

+ The same windowing engine with the component peeled away. 5,000 messages + of differing heights, measured as they mount, opened at index 2,500 on + the first paint through initialScrollIndex. Nothing here is + rendered by the library: the hook returns offsets and a ref, and the + markup below is ordinary divs. +

+
+ + + + + rendering {start} to {end} of {MESSAGES.length}, sizer{" "} + {Math.round(totalSize).toLocaleString()}px + {range ? `, ${range.visibleEnd - range.visibleStart} in view` : ""} + +
+
+
+ {virtualItems.map((item) => { + const message = MESSAGES[item.index]; + return ( +
+ + {message.author}{" "} + #{message.id} + +
+ {message.body} +
+
+ ); + })} +
+
+
+ ); +} + function WaveDemo() { const [runId, setRunId] = useState(0); const [done, setDone] = useState(false); @@ -195,6 +337,7 @@ function App() { <>

react-render-wave

+ ); diff --git a/package-lock.json b/package-lock.json index 482acd5..f896410 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,21 +9,101 @@ "version": "3.0.0", "license": "MIT", "devDependencies": { + "@arethetypeswrong/cli": "^0.18.5", + "@microsoft/api-extractor": "^7.59.1", "@testing-library/react": "^16.3.0", "@types/react": "^19.1.3", "@types/react-dom": "^19.1.3", "jsdom": "^26.1.0", + "publint": "^0.3.24", "react": "^19.1.0", "react-dom": "^19.1.0", "typescript": "^5.8.3", "vite": "^6.3.5", + "vite-plugin-dts": "^5.1.0", "vitest": "^3.1.3" }, + "engines": { + "node": ">=18" + }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, + "node_modules/@andrewbranch/untar.js": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@andrewbranch/untar.js/-/untar.js-1.0.4.tgz", + "integrity": "sha512-pVXSwPsLuw8IGLo2Di0EaOfsk+ntVvpkk942J/sHYIkwvtKUakEcPh7HBgZ6tuimgzKSEHgCvO4XgQ05DEbwDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@arethetypeswrong/cli": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/@arethetypeswrong/cli/-/cli-0.18.5.tgz", + "integrity": "sha512-gM+8vRsQOD/Uc7EnBedUhkG5OCsDWE4uoak5QvomGpMpaky0Eh41p04nIMgrWb8EOmqZUJGc6zz9hsP6E56R7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@arethetypeswrong/core": "0.18.5", + "chalk": "^4.1.2", + "cli-table3": "^0.6.3", + "commander": "^10.0.1", + "marked": "^9.1.2", + "marked-terminal": "^7.1.0", + "semver": "^7.5.4" + }, + "bin": { + "attw": "dist/index.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@arethetypeswrong/core": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/@arethetypeswrong/core/-/core-0.18.5.tgz", + "integrity": "sha512-9ytjzGwxjm9Uz7I9avfbt5vlQt6uk9uRRESzJjqrznl6WKvI6dwYTo+vJ3U02Wrq/mR3iql/PzhvHhKdJIAjDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@andrewbranch/untar.js": "^1.0.3", + "@loaderkit/resolve": "^1.0.2", + "cjs-module-lexer": "^1.2.3", + "fflate": "^0.8.3", + "lru-cache": "^11.0.1", + "semver": "^7.5.4", + "typescript": "5.6.1-rc", + "validate-npm-package-name": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@arethetypeswrong/core/node_modules/lru-cache": { + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@arethetypeswrong/core/node_modules/typescript": { + "version": "5.6.1-rc", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.1-rc.tgz", + "integrity": "sha512-E3b2+1zEFu84jB0YQi9BORDjz9+jGbwwy1Zi3G0LUNw7a7cePUrHMRNy8aPh53nXpkFGVHSxIZo5vKTfYaFiBQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/@asamuzakjp/css-color": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", @@ -75,6 +155,24 @@ "node": ">=6.9.0" } }, + "node_modules/@braidai/lang": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@braidai/lang/-/lang-1.1.2.tgz", + "integrity": "sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA==", + "dev": true, + "license": "ISC" + }, + "node_modules/@colors/colors": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", + "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/@csstools/color-helpers": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", @@ -632,6 +730,38 @@ "node": ">=18" } }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", @@ -639,6 +769,159 @@ "dev": true, "license": "MIT" }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@loaderkit/resolve": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@loaderkit/resolve/-/resolve-1.0.6.tgz", + "integrity": "sha512-G8FdIoF5CypfwmD9rl8BXod5HDn8JqB0CCNBXDTaRZ+yRYhARrrSToX1zg1zy9jX3zLqigsELwhT4gNtkdQAUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@braidai/lang": "^1.0.0" + } + }, + "node_modules/@microsoft/api-extractor": { + "version": "7.59.1", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.59.1.tgz", + "integrity": "sha512-GjRUqx1MTY7xuH36urwASkfBPzrdxYG+irVeV7C9JEdRtn509AgMmwit/BhvztQzIoFk9vhFDTVYOp2cjw+9Uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@microsoft/api-extractor-model": "7.33.12", + "@microsoft/tsdoc": "~0.16.0", + "@microsoft/tsdoc-config": "~0.18.1", + "@rushstack/node-core-library": "5.24.1", + "@rushstack/rig-package": "0.7.3", + "@rushstack/terminal": "0.24.4", + "@rushstack/ts-command-line": "5.3.14", + "diff": "~8.0.2", + "minimatch": "10.2.3", + "resolve": "~1.22.1", + "semver": "~7.7.4", + "source-map": "~0.6.1", + "typescript": "5.9.3" + }, + "bin": { + "api-extractor": "bin/api-extractor" + }, + "engines": { + "node": ">=20.9.0" + } + }, + "node_modules/@microsoft/api-extractor-model": { + "version": "7.33.12", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.33.12.tgz", + "integrity": "sha512-TdKOYgwf98xLjNW+y3iXIiCf4ZLQbilGAlqkMTTAqqAWfgRXAn9YCSGMsaiB1U7OPRvslUWg6n08EqQPbP93tA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "~0.16.0", + "@microsoft/tsdoc-config": "~0.18.1", + "@rushstack/node-core-library": "5.24.1" + }, + "engines": { + "node": ">=20.9.0" + } + }, + "node_modules/@microsoft/api-extractor/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@microsoft/tsdoc": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.16.0.tgz", + "integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@microsoft/tsdoc-config": { + "version": "0.18.1", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc-config/-/tsdoc-config-0.18.1.tgz", + "integrity": "sha512-9brPoVdfN9k9g0dcWkFeA7IH9bbcttzDJlXvkf8b2OBzd5MueR1V2wkKBL0abn0otvmkHJC6aapBOTJDDeMCZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "0.16.0", + "ajv": "~8.18.0", + "jju": "~1.4.0", + "resolve": "~1.22.2" + } + }, + "node_modules/@publint/pack": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@publint/pack/-/pack-0.1.7.tgz", + "integrity": "sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyexec": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/@publint/pack/node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.62.3", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.3.tgz", @@ -989,6 +1272,158 @@ "win32" ] }, + "node_modules/@rushstack/node-core-library": { + "version": "5.24.1", + "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-5.24.1.tgz", + "integrity": "sha512-ZlOrzv92MwnsCXA45qWfDj4L/kTasKghXezu+M2WmdtkbnXyPnZSCovfeBZx1Yc5qm+LkElbLw6IeSSWZDhZUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "~8.20.0", + "ajv-draft-04": "~1.0.0", + "ajv-formats": "~3.0.1", + "fs-extra": "~11.3.0", + "import-lazy": "~4.0.0", + "jju": "~1.4.0", + "resolve": "~1.22.1", + "semver": "~7.7.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "peerDependencies": { + "@types/node": "*" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@rushstack/node-core-library/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@rushstack/node-core-library/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@rushstack/problem-matcher": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@rushstack/problem-matcher/-/problem-matcher-0.2.1.tgz", + "integrity": "sha512-gulfhBs6n+I5b7DvjKRfhMGyUejtSgOHTclF/eONr8hcgF1APEDjhxIsfdUYYMzC3rvLwGluqLjbwCFZ8nxrog==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/node": "*" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@rushstack/rig-package": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@rushstack/rig-package/-/rig-package-0.7.3.tgz", + "integrity": "sha512-aAA518n6wxxjCfnTAOjQnm7ngNE0FVHxHAw2pxKlIhxrMn0XQjGcXKF0oKWpjBgJOmsaJpVob/v+zr3zxgPWuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jju": "~1.4.0", + "resolve": "~1.22.1" + } + }, + "node_modules/@rushstack/terminal": { + "version": "0.24.4", + "resolved": "https://registry.npmjs.org/@rushstack/terminal/-/terminal-0.24.4.tgz", + "integrity": "sha512-3fRBWK0IMY293lBx5ycgit1DTMUi+nhOjALHlrIad9hQsqzM9Ak+XdBI1gJ/tZPxW+LraeAc4SsmMdcOflBmAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rushstack/node-core-library": "5.24.1", + "@rushstack/problem-matcher": "0.2.1", + "supports-color": "~8.1.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "peerDependencies": { + "@types/node": "*" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@rushstack/terminal/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/@rushstack/ts-command-line": { + "version": "5.3.14", + "resolved": "https://registry.npmjs.org/@rushstack/ts-command-line/-/ts-command-line-5.3.14.tgz", + "integrity": "sha512-lT2JKZk2dukBMp4GFOh4RaDfVzpZehGgQOGpzpSliUn317NgEmOOCXyd7/d0eU46HHsbRxizP83GAm39s0lAlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rushstack/terminal": "0.24.4", + "@types/argparse": "1.0.38", + "argparse": "~1.0.9", + "string-argv": "~0.3.1" + }, + "engines": { + "node": ">=20.9.0" + } + }, + "node_modules/@sindresorhus/is": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", @@ -1038,6 +1473,13 @@ } } }, + "node_modules/@types/argparse": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/@types/argparse/-/argparse-1.0.38.tgz", + "integrity": "sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/aria-query": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", @@ -1206,6 +1648,48 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@volar/language-core": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz", + "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.28" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz", + "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz", + "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -1216,20 +1700,85 @@ "node": ">= 14" } }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", "dev": true, "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "node_modules/ajv-draft-04": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz", + "integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "ajv": "^8.5.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", @@ -1241,6 +1790,23 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -1262,6 +1828,29 @@ "node": ">=12" } }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -1289,6 +1878,49 @@ "node": ">=18" } }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/check-error": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", @@ -1299,6 +1931,114 @@ "node": ">= 16" } }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-highlight": { + "version": "2.1.11", + "resolved": "https://registry.npmjs.org/cli-highlight/-/cli-highlight-2.1.11.tgz", + "integrity": "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg==", + "dev": true, + "license": "ISC", + "dependencies": { + "chalk": "^4.0.0", + "highlight.js": "^10.7.1", + "mz": "^2.4.0", + "parse5": "^5.1.1", + "parse5-htmlparser2-tree-adapter": "^6.0.0", + "yargs": "^16.0.0" + }, + "bin": { + "highlight": "bin/highlight" + }, + "engines": { + "node": ">=8.0.0", + "npm": ">=5.0.0" + } + }, + "node_modules/cli-highlight/node_modules/parse5": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz", + "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-table3": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", + "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "string-width": "^4.2.0" + }, + "engines": { + "node": "10.* || >= 12.*" + }, + "optionalDependencies": { + "@colors/colors": "1.5.0" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/compare-versions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "dev": true, + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", + "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", + "dev": true, + "license": "MIT" + }, "node_modules/cssstyle": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", @@ -1380,6 +2120,16 @@ "node": ">=6" } }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/dom-accessibility-api": { "version": "0.5.16", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", @@ -1388,6 +2138,20 @@ "license": "MIT", "peer": true }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/emojilib": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/emojilib/-/emojilib-2.4.0.tgz", + "integrity": "sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==", + "dev": true, + "license": "MIT" + }, "node_modules/entities": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", @@ -1401,6 +2165,29 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -1450,6 +2237,16 @@ "@esbuild/win32-x64": "0.25.12" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -1470,6 +2267,37 @@ "node": ">=12.0.0" } }, + "node_modules/exsolve": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.1.tgz", + "integrity": "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", + "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -1488,6 +2316,28 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fs-extra": { + "version": "11.3.6", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.6.tgz", + "integrity": "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1503,6 +2353,73 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -1557,6 +2474,42 @@ "node": ">=0.10.0" } }, + "node_modules/import-lazy": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-4.0.0.tgz", + "integrity": "sha512-rKtvo6a868b5Hu3heneU+L4yEQ4jYKLtjpnPeUdK7h0yzXGmyBTypknlkCvHFBqfX9YlorEiMM6Dnq/5atfHkw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-potential-custom-element-name": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", @@ -1564,6 +2517,13 @@ "dev": true, "license": "MIT" }, + "node_modules/jju": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", + "integrity": "sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==", + "dev": true, + "license": "MIT" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1612,6 +2572,51 @@ } } }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/kolorist": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz", + "integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/local-pkg": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", + "integrity": "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/loupe": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", @@ -1647,6 +2652,125 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/marked": { + "version": "9.1.6", + "resolved": "https://registry.npmjs.org/marked/-/marked-9.1.6.tgz", + "integrity": "sha512-jcByLnIFkd5gSXZmjNvS1TlmRhCXZjIzHYlaGkPlLIekG55JDR2Z4va9tZwCiP+/RDERiNhMOFu01xd6O5ct1Q==", + "dev": true, + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 16" + } + }, + "node_modules/marked-terminal": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/marked-terminal/-/marked-terminal-7.3.0.tgz", + "integrity": "sha512-t4rBvPsHc57uE/2nJOLmMbZCQ4tgAccAED3ngXQqW6g+TxA488JzJ+FK3lQkzBQOI1mRV/r/Kq+1ZlJ4D0owQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "ansi-regex": "^6.1.0", + "chalk": "^5.4.1", + "cli-highlight": "^2.1.11", + "cli-table3": "^0.6.5", + "node-emoji": "^2.2.0", + "supports-hyperlinks": "^3.1.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "marked": ">=1 <16" + } + }, + "node_modules/marked-terminal/node_modules/ansi-regex": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", + "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/marked-terminal/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/minimatch": { + "version": "10.2.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.3.tgz", + "integrity": "sha512-Rwi3pnapEqirPSbWbrZaa6N3nmqq4Xer/2XooiOKyV3q12ML06f7MOuc5DVH8ONZIFhwIYQ3yzPH4nt7iWHaTg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -1654,6 +2778,18 @@ "dev": true, "license": "MIT" }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, "node_modules/nanoid": { "version": "3.3.16", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", @@ -1673,6 +2809,22 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-emoji": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-2.2.0.tgz", + "integrity": "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.6.0", + "char-regex": "^1.0.2", + "emojilib": "^2.4.0", + "skin-tone": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/nwsapi": { "version": "2.2.24", "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.24.tgz", @@ -1680,6 +2832,23 @@ "dev": true, "license": "MIT" }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/package-manager-detector": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.8.0.tgz", + "integrity": "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==", + "dev": true, + "license": "MIT" + }, "node_modules/parse5": { "version": "7.3.0", "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", @@ -1693,6 +2862,37 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", + "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^6.0.1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -1730,6 +2930,18 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkg-types": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", + "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.1", + "pathe": "^2.0.3" + } + }, "node_modules/postcss": { "version": "8.5.24", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.24.tgz", @@ -1765,14 +2977,36 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", - "peer": true, + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/publint": { + "version": "0.3.24", + "resolved": "https://registry.npmjs.org/publint/-/publint-0.3.24.tgz", + "integrity": "sha512-9zS56KrKBoqi5Qt8h92uMP8TTM9AYZSgnmCo4u2priMqkOZvQnTsziZ2p5LJ2ywbYkAjoCDp2jda9u4cgFefIw==", + "dev": true, + "license": "MIT", "dependencies": { - "ansi-regex": "^5.0.1", - "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" + "@publint/pack": "^0.1.7", + "package-manager-detector": "^1.8.0", + "picocolors": "^1.1.1", + "sade": "^1.8.1" + }, + "bin": { + "publint": "src/cli.js" }, "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" } }, "node_modules/punycode": { @@ -1785,6 +3019,23 @@ "node": ">=6" } }, + "node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, "node_modules/react": { "version": "19.2.8", "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", @@ -1816,6 +3067,48 @@ "license": "MIT", "peer": true }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/rollup": { "version": "4.62.3", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.3.tgz", @@ -1868,6 +3161,19 @@ "dev": true, "license": "MIT" }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -1895,6 +3201,19 @@ "dev": true, "license": "MIT" }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -1902,6 +3221,29 @@ "dev": true, "license": "ISC" }, + "node_modules/skin-tone": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/skin-tone/-/skin-tone-2.0.0.tgz", + "integrity": "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "unicode-emoji-modifier-base": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -1912,6 +3254,13 @@ "node": ">=0.10.0" } }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true, + "license": "BSD-3-Clause" + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -1926,6 +3275,44 @@ "dev": true, "license": "MIT" }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-literal": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", @@ -1946,6 +3333,49 @@ "dev": true, "license": "MIT" }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-hyperlinks": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.2.0.tgz", + "integrity": "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">=14.18" + }, + "funding": { + "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", @@ -1953,6 +3383,29 @@ "dev": true, "license": "MIT" }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -2074,6 +3527,114 @@ "node": ">=14.17" } }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicode-emoji-modifier-base": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unicode-emoji-modifier-base/-/unicode-emoji-modifier-base-1.0.0.tgz", + "integrity": "sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unplugin": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.11.tgz", + "integrity": "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "acorn": "^8.15.0", + "picomatch": "^4.0.3", + "webpack-virtual-modules": "^0.6.2" + }, + "engines": { + "node": ">=18.12.0" + } + }, + "node_modules/unplugin-dts": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unplugin-dts/-/unplugin-dts-1.1.0.tgz", + "integrity": "sha512-KZJ+qk+lmd9dJY/PJvDRFL9BUtVubKDiX7Ai/X6mlkCArcQNzwmupKjVqHbRA42uqO5ZfFRFc+o8/OCbQ1GonQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.1.4", + "@volar/typescript": "^2.4.26", + "compare-versions": "^6.1.1", + "debug": "^4.4.0", + "glob-to-regexp": "0.4.1", + "kolorist": "^1.8.0", + "local-pkg": "^1.1.1", + "magic-string": "^0.30.17", + "unplugin": "^2.3.2" + }, + "peerDependencies": { + "@microsoft/api-extractor": ">=7", + "@rspack/core": "^1", + "@vue/language-core": "^3.1.5", + "esbuild": "*", + "rolldown": "*", + "rollup": ">=3", + "typescript": ">=4", + "vite": ">=3", + "webpack": "^4 || ^5" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@rspack/core": { + "optional": true + }, + "@vue/language-core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "rolldown": { + "optional": true + }, + "rollup": { + "optional": true + }, + "vite": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/validate-npm-package-name": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-5.0.1.tgz", + "integrity": "sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/vite": { "version": "6.4.3", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", @@ -2172,6 +3733,32 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/vite-plugin-dts": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vite-plugin-dts/-/vite-plugin-dts-5.1.0.tgz", + "integrity": "sha512-MfLc2G+mXPUDGGxpHQeYbdunavFP9UpT9yxiAsTgUXRxfEd3HqysSAM4E72jhz5eIz3OOexCHkqiVlQq8ok9/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "unplugin-dts": "1.1.0" + }, + "peerDependencies": { + "@microsoft/api-extractor": ">=7", + "rollup": ">=3", + "vite": ">=3" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "rollup": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, "node_modules/vitest": { "version": "3.2.7", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", @@ -2245,6 +3832,13 @@ } } }, + "node_modules/vscode-uri": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz", + "integrity": "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==", + "dev": true, + "license": "MIT" + }, "node_modules/w3c-xmlserializer": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", @@ -2268,6 +3862,13 @@ "node": ">=12" } }, + "node_modules/webpack-virtual-modules": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", + "dev": true, + "license": "MIT" + }, "node_modules/whatwg-encoding": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", @@ -2323,6 +3924,40 @@ "node": ">=8" } }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/ws": { "version": "8.21.1", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz", @@ -2361,6 +3996,45 @@ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true, "license": "MIT" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "16.2.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.2.tgz", + "integrity": "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } } } } diff --git a/package.json b/package.json index 7bf4ef6..e9377fa 100644 --- a/package.json +++ b/package.json @@ -1,31 +1,37 @@ { "name": "react-render-wave", - "version": "3.0.0", + "version": "3.1.0", "description": "Progressive wave rendering and lightweight virtual scrolling for React lists.", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.es.js", - "types": "./dist/types/index.d.ts", + "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/types/index.d.ts", - "import": "./dist/index.es.js", - "require": "./dist/index.cjs", - "default": "./dist/index.es.js" - } + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.es.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" }, "sideEffects": false, "files": [ "dist" ], "scripts": { - "build": "vite build && tsc -p tsconfig.build.json", + "build": "vite build", "prepare": "npm run build", "test": "vitest run", "test:watch": "vitest", "typecheck": "tsc --noEmit", "demo": "vite demo --open", - "prepublishOnly": "npm run test && npm run build" + "prepublishOnly": "npm run test && npm run build && npm run check:pkg", + "check:pkg": "publint && attw --pack ." }, "keywords": [ "react", @@ -46,19 +52,26 @@ "bugs": { "url": "https://github.com/sudo-ezekiel/react-render-wave/issues" }, + "engines": { + "node": ">=18" + }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "devDependencies": { + "@arethetypeswrong/cli": "^0.18.5", + "@microsoft/api-extractor": "^7.59.1", "@testing-library/react": "^16.3.0", "@types/react": "^19.1.3", "@types/react-dom": "^19.1.3", "jsdom": "^26.1.0", + "publint": "^0.3.24", "react": "^19.1.0", "react-dom": "^19.1.0", "typescript": "^5.8.3", "vite": "^6.3.5", + "vite-plugin-dts": "^5.1.0", "vitest": "^3.1.3" } } diff --git a/src/VirtualRenderWave.tsx b/src/VirtualRenderWave.tsx index 4a4a634..c6d97b4 100644 --- a/src/VirtualRenderWave.tsx +++ b/src/VirtualRenderWave.tsx @@ -4,36 +4,36 @@ import React, { useEffect, useImperativeHandle, useInsertionEffect, - useLayoutEffect, + useMemo, useRef, - useState, - type FC, type ReactNode, type Ref, } from "react"; -import { HeightCache } from "./heightCache"; import { useRenderWave } from "./useRenderWave"; +import { useViewportReveal } from "./useViewportReveal"; +import { useVirtualWindow } from "./useVirtualWindow"; +import type { ScrollToIndexOptions } from "./useVirtualWindow"; import type { HTMLTag, VirtualRenderWaveComponent, VirtualRenderWaveHandle, VirtualRenderWaveProps, + WrapperComponent, WrapperProps, } from "./types"; const FADE_ANIMATION = "rrw-fade-in"; -// useLayoutEffect warns during server rendering, where there is no layout to -// read anyway. -const useIsomorphicLayoutEffect = - typeof window !== "undefined" ? useLayoutEffect : useEffect; +/** Quiet period after a scroll before snapToBatch aligns the container. */ +const SNAP_DELAY_MS = 150; let keyframesInjected = false; function injectKeyframes(): void { if (keyframesInjected || typeof document === "undefined") return; const style = document.createElement("style"); style.setAttribute("data-react-render-wave", ""); - style.textContent = `@keyframes ${FADE_ANIMATION} { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }`; + // Scoped to no-preference so reduced motion needs no JS listener. + style.textContent = `@media (prefers-reduced-motion: no-preference) { @keyframes ${FADE_ANIMATION} { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } } }`; document.head.appendChild(style); keyframesInjected = true; } @@ -48,15 +48,18 @@ function getGroupLabel( return value == null ? undefined : String(value); } +// createElement, not JSX, so `ref` travels as an ordinary prop on React 18 and 19 alike. function renderElement( - Component: HTMLTag | FC, + Component: HTMLTag | WrapperComponent, props: WrapperProps ): ReactNode { if (typeof Component === "string") { const { children, ...rest } = props; return React.createElement(Component, rest, children); } - return ; + // The cast keeps one source tree compiling against @types/react 18 and 19. + const Fn = Component as (props: WrapperProps) => ReactNode; + return React.createElement(Fn, props); } function VirtualRenderWaveInner( @@ -68,12 +71,15 @@ function VirtualRenderWaveInner( interval = 50, overscan = 5, startIndex = 0, + revealMode = "sequential", className, style, renderItem, renderSkeleton, getItemKey, scrollToIndex, + initialScrollOffset, + initialScrollIndex, outerElement, innerElement, transition = false, @@ -81,6 +87,7 @@ function VirtualRenderWaveInner( onEndReached, endReachedThreshold = 10, onScroll, + onRangeChange, keyboardNavigation = false, renderStickyHeader, groupByKey, @@ -91,18 +98,6 @@ function VirtualRenderWaveInner( const outerRef = useRef(null); const innerRef = useRef(null); - const cacheRef = useRef(null); - if (cacheRef.current === null) cacheRef.current = new HeightCache(itemHeight); - const cache = cacheRef.current; - cache.setDefaultSize(itemHeight); - cache.setCount(items.length); - - const [, bumpHeightsVersion] = useState(0); - const [scrollTop, setScrollTop] = useState(0); - const [viewportHeight, setViewportHeight] = useState(containerHeight); - - // Handlers read the latest props through this ref so the scroll listener - // only has to be attached once. const latest = useRef({ snapToBatch, itemHeight, @@ -126,177 +121,137 @@ function VirtualRenderWaveInner( if (transition) injectKeyframes(); }, [transition]); - // ---- dynamic height measurement ----------------------------------------- + const keyFnRef = useRef(getItemKey); + keyFnRef.current = getItemKey; + + const keyed = getItemKey !== undefined; + const keyFn = useMemo( + () => + keyed + ? (index: number) => keyFnRef.current!(items[index], index) + : undefined, + [items, keyed] + ); - const observerRef = useRef(null); - const elementToIndex = useRef(new Map()); - const indexToElement = useRef(new Map()); - const refCallbacks = useRef(new Map void>()); + const endReachedFiredRef = useRef(false); + const snapTimerRef = useRef | null>(null); - const getObserver = useCallback(() => { - if (observerRef.current) return observerRef.current; - if (typeof ResizeObserver === "undefined") return null; - observerRef.current = new ResizeObserver((entries) => { - const heightCache = cacheRef.current; - if (!heightCache) return; - let changed = false; - for (const entry of entries) { - const index = elementToIndex.current.get(entry.target); - if (index === undefined) continue; - const height = (entry.target as HTMLElement).offsetHeight; - if (height > 0 && heightCache.measure(index, height)) changed = true; - } - if (changed) bumpHeightsVersion((v) => v + 1); - }); - return observerRef.current; + const checkEndReached = useCallback((el: HTMLElement | null) => { + if (!el) return; + const { onEndReached, endReachedThreshold } = latest.current; + if (!onEndReached) return; + const atEnd = + el.scrollTop + el.clientHeight >= el.scrollHeight - endReachedThreshold; + if (atEnd && !endReachedFiredRef.current) { + endReachedFiredRef.current = true; + onEndReached(); + } else if (!atEnd) { + endReachedFiredRef.current = false; + } }, []); + const handleScroll = useCallback( + (offset: number) => { + latest.current.onScroll?.(offset); + checkEndReached(outerRef.current); + + if (!latest.current.snapToBatch) return; + if (snapTimerRef.current) clearTimeout(snapTimerRef.current); + snapTimerRef.current = setTimeout(() => { + snapTimerRef.current = null; + const el = outerRef.current; + if (!el) return; + const { itemHeight, batchSize } = latest.current; + const batchPx = itemHeight * Math.max(1, batchSize); + if (batchPx <= 0) return; + const maxScroll = Math.max(0, el.scrollHeight - el.clientHeight); + const target = Math.min( + Math.round(el.scrollTop / batchPx) * batchPx, + maxScroll + ); + if (Math.abs(target - el.scrollTop) > 1) { + el.scrollTo({ top: target, behavior: "smooth" }); + } + }, SNAP_DELAY_MS); + }, + [checkEndReached] + ); + useEffect(() => { return () => { - observerRef.current?.disconnect(); - observerRef.current = null; + if (snapTimerRef.current) clearTimeout(snapTimerRef.current); }; }, []); - // Ref callbacks are cached per index so React does not detach and reattach - // them on every render, which would rebuild the observer registrations. - const getItemRef = (index: number) => { - let cb = refCallbacks.current.get(index); - if (!cb) { - cb = (el: HTMLElement | null) => { - const prev = indexToElement.current.get(index); - if (el) { - if (prev === el) return; - if (prev) { - observerRef.current?.unobserve(prev); - elementToIndex.current.delete(prev); - } - indexToElement.current.set(index, el); - elementToIndex.current.set(el, index); - getObserver()?.observe(el); - } else if (prev) { - observerRef.current?.unobserve(prev); - elementToIndex.current.delete(prev); - indexToElement.current.delete(index); - } - }; - refCallbacks.current.set(index, cb); - } - return cb; - }; - - // ResizeObserver delivery is asynchronous, and it is missing entirely in - // some environments. Measuring after every commit means offsets are right - // before the browser paints rather than a frame later; the observer above - // then only has to catch resizes that happen without a re-render, such as - // an image finishing loading. - useIsomorphicLayoutEffect(() => { - const heightCache = cacheRef.current; - if (!heightCache) return; - let changed = false; - for (const [index, el] of indexToElement.current) { - const height = el.offsetHeight; - if (height > 0 && heightCache.measure(index, height)) changed = true; - } - // measure() only reports true on an actual change, so this settles. - if (changed) bumpHeightsVersion((v) => v + 1); + const getScrollElement = useCallback(() => outerRef.current, []); + + const hook = useVirtualWindow({ + count: items.length, + estimateSize: itemHeight, + overscan, + initialViewportSize: containerHeight, + getItemKey: keyFn, + getScrollElement, + initialScrollOffset, + initialScrollIndex: initialScrollIndex ?? scrollToIndex, + onScroll: handleScroll, + onRangeChange, }); - // ---- reveal ------------------------------------------------------------- + const sequential = revealMode !== "viewport"; const { count: revealedCount } = useRenderWave({ length: items.length, batchSize, interval, startIndex, + enabled: sequential, }); const safeStart = Math.max(0, Math.min(startIndex, items.length)); const revealedEnd = Math.min(items.length, safeStart + revealedCount); - // ---- windowing ---------------------------------------------------------- - - const totalHeight = cache.totalSize(); - const firstVisible = cache.indexAt(scrollTop); - const lastVisible = cache.indexAt(scrollTop + Math.max(0, viewportHeight - 1)); - const start = Math.max(0, firstVisible - overscan); - const end = Math.min(items.length, lastVisible + 1 + overscan); - - // ---- scroll, snap, end detection ---------------------------------------- + const viewportReveal = useViewportReveal({ + count: items.length, + start: hook.start, + end: hook.end, + batchSize, + interval, + startIndex, + enabled: !sequential, + getItemKey: keyFn, + }); - const endReachedFiredRef = useRef(false); + const isRevealed = sequential + ? (index: number) => index >= safeStart && index < revealedEnd + : viewportReveal.isRevealed; + const prevItemsLength = useRef(items.length); useEffect(() => { - const el = outerRef.current; - if (!el) return; - - let rafId: number | null = null; - let snapTimer: ReturnType | null = null; - - const handleFrame = () => { - rafId = null; - const top = el.scrollTop; - setScrollTop(top); - latest.current.onScroll?.(top); - - const { onEndReached, endReachedThreshold } = latest.current; - if (onEndReached) { - const atEnd = - top + el.clientHeight >= el.scrollHeight - endReachedThreshold; - if (atEnd && !endReachedFiredRef.current) { - endReachedFiredRef.current = true; - onEndReached(); - } else if (!atEnd) { - endReachedFiredRef.current = false; - } - } - }; - - const handleScroll = () => { - if (rafId === null) rafId = requestAnimationFrame(handleFrame); - - if (latest.current.snapToBatch) { - if (snapTimer) clearTimeout(snapTimer); - snapTimer = setTimeout(() => { - const { itemHeight, batchSize } = latest.current; - const batchPx = itemHeight * Math.max(1, batchSize); - if (batchPx <= 0) return; - const maxScroll = Math.max(0, el.scrollHeight - el.clientHeight); - const target = Math.min( - Math.round(el.scrollTop / batchPx) * batchPx, - maxScroll - ); - if (Math.abs(target - el.scrollTop) > 1) { - el.scrollTo({ top: target, behavior: "smooth" }); - } - }, 150); - } - }; - - el.addEventListener("scroll", handleScroll, { passive: true }); - setScrollTop(el.scrollTop); - - return () => { - el.removeEventListener("scroll", handleScroll); - if (snapTimer) clearTimeout(snapTimer); - if (rafId !== null) cancelAnimationFrame(rafId); - }; - }, []); + if (prevItemsLength.current !== items.length) { + prevItemsLength.current = items.length; + endReachedFiredRef.current = false; + } + checkEndReached(outerRef.current); + }, [items.length, hook.viewportSize, hook.totalSize, checkEndReached]); + const refWarnedRef = useRef(false); useEffect(() => { - const el = outerRef.current; - if (!el) return; - if (el.clientHeight > 0) setViewportHeight(el.clientHeight); - if (typeof ResizeObserver === "undefined") return; - const viewportObserver = new ResizeObserver(() => { - setViewportHeight(el.clientHeight); - }); - viewportObserver.observe(el); - return () => viewportObserver.disconnect(); + if (refWarnedRef.current) return; + refWarnedRef.current = true; + if (outerElement && typeof outerElement !== "string" && !outerRef.current) { + console.error( + "react-render-wave: outerElement did not attach the ref it received, so the list cannot scroll or measure. On React 18 wrap the component in forwardRef and pass the ref to your DOM node." + ); + } + if (innerElement && typeof innerElement !== "string" && !innerRef.current) { + console.error( + "react-render-wave: innerElement did not attach the ref it received, so the list cannot scroll or measure. On React 18 wrap the component in forwardRef and pass the ref to your DOM node." + ); + } }, []); - // ---- keyboard navigation ------------------------------------------------ - const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.target !== e.currentTarget) return; const el = outerRef.current; if (!el) return; const maxScroll = Math.max(0, el.scrollHeight - el.clientHeight); @@ -327,32 +282,50 @@ function VirtualRenderWaveInner( el.scrollTo({ top: target, behavior: "smooth" }); }; - // ---- imperative handle -------------------------------------------------- + const { start, end } = hook; + const scrollIndex = hook.scrollToIndex; + const scrollToOffset = hook.scrollToOffset; + const getEl = hook.getScrollElement; useImperativeHandle( ref, () => ({ - scrollTo: (index: number, behavior: ScrollBehavior = "smooth") => { - outerRef.current?.scrollTo({ top: cache.offsetOf(index), behavior }); + scrollTo: ( + index: number, + options?: ScrollBehavior | ScrollToIndexOptions + ) => { + scrollIndex(index, { + align: "start", + behavior: "smooth", + ...(typeof options === "string" ? { behavior: options } : options), + }); }, scrollToOffset: (px: number, behavior: ScrollBehavior = "smooth") => { - outerRef.current?.scrollTo({ top: px, behavior }); + scrollToOffset(px, { behavior }); }, getVisibleIndexes: () => { const visible: number[] = []; for (let i = start; i < end; i++) { - if (i >= safeStart && i < revealedEnd) visible.push(i); + if (isRevealed(i)) visible.push(i); } return visible; }, - getScrollElement: () => outerRef.current, + getScrollElement: () => getEl(), }), - [start, end, safeStart, revealedEnd, cache] + [ + start, + end, + sequential, + safeStart, + revealedEnd, + viewportReveal.isRevealed, + scrollIndex, + scrollToOffset, + getEl, + ] ); - // ---- controlled scrollToIndex ------------------------------------------- - - const lastScrollToIndexRef = useRef(undefined); + const lastScrollToIndexRef = useRef(scrollToIndex); useEffect(() => { if (typeof scrollToIndex !== "number") { lastScrollToIndexRef.current = undefined; @@ -360,30 +333,27 @@ function VirtualRenderWaveInner( } if (scrollToIndex === lastScrollToIndexRef.current) return; lastScrollToIndexRef.current = scrollToIndex; - outerRef.current?.scrollTo({ top: cache.offsetOf(scrollToIndex) }); - }, [scrollToIndex, cache]); - - // ---- render ------------------------------------------------------------- + scrollIndex(scrollToIndex, { behavior: "auto" }); + }, [scrollToIndex, scrollIndex]); let activeGroup: string | undefined; if (groupByKey && renderStickyHeader && items.length > 0) { - const topIndex = Math.min(cache.indexAt(scrollTop), items.length - 1); + const topIndex = Math.min(hook.visibleStart, items.length - 1); activeGroup = getGroupLabel(items[topIndex], topIndex, groupByKey); } - const children: ReactNode[] = []; - for (let index = start; index < end; index++) { - const revealed = index >= safeStart && index < revealedEnd; - children.push( + const children: ReactNode[] = hook.virtualItems.map((item) => { + const revealed = isRevealed(item.index); + return (
( }} > {revealed - ? renderItem(items[index], index) - : renderSkeleton?.(index) ?? null} + ? renderItem(items[item.index], item.index) + : (renderSkeleton?.(item.index) ?? null)}
); - } + }); return renderElement(outerElement ?? "div", { ref: outerRef, @@ -414,8 +384,6 @@ function VirtualRenderWaveInner( children: ( <> {renderStickyHeader && activeGroup !== undefined && ( - // Positioning only. Give the header its own background, otherwise - // rows scroll visibly behind it.
{renderStickyHeader(activeGroup)}
@@ -425,7 +393,7 @@ function VirtualRenderWaveInner( role: "list", style: { position: "relative", - height: totalHeight, + height: hook.totalSize, width: "100%", }, children, diff --git a/src/index.ts b/src/index.ts index 71dd807..c19e9ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,9 +9,23 @@ export type { RenderWaveProps } from "./RenderWave"; export { VirtualRenderWave } from "./VirtualRenderWave"; export type { + RevealMode, VirtualRenderWaveHandle, VirtualRenderWaveProps, VirtualRenderWaveComponent, WrapperProps, + WrapperComponent, HTMLTag, } from "./types"; + +export { useVirtualWindow } from "./useVirtualWindow"; +export type { + UseVirtualWindowOptions, + UseVirtualWindowResult, + VirtualItem, + VirtualRange, + ScrollAlign, + ScrollToIndexOptions, + ScrollToOffsetOptions, + ItemKey, +} from "./useVirtualWindow"; diff --git a/src/heightCache.ts b/src/sizeCache.ts similarity index 50% rename from src/heightCache.ts rename to src/sizeCache.ts index f688e30..dde9c65 100644 --- a/src/heightCache.ts +++ b/src/sizeCache.ts @@ -1,3 +1,6 @@ +/** Identity of an item, used as the key its measured size is stored under. */ +export type ItemKey = string | number; + /** * Prefix-sum cache of item offsets for the virtualizer. * @@ -5,15 +8,22 @@ * between changes are O(1) for offsets and O(log n) for hit testing, while a * measurement update costs one suffix rebuild on the next query. * - * Measured heights persist even after an item unmounts, so scrolling back to - * a previously measured region never causes layout jumps. + * Measured sizes persist even after an item unmounts, so scrolling back to a + * previously measured region never causes layout jumps. + * + * Sizes are stored per key rather than per index. Without a key function the + * key is the index itself; with one, a reorder of the data moves each measured + * size along with its item. The cost is that a change of key function identity + * dirties everything: one O(count) offset rebuild on the next query. Memoize + * the key function on the data it closes over. */ -export class HeightCache { +export class SizeCache { private offsets: number[] = [0]; - private measured = new Map(); + private measured = new Map(); private dirtyFrom = 0; private count = 0; private defaultSize: number; + private keyFn: ((index: number) => ItemKey) | undefined; constructor(defaultSize: number) { this.defaultSize = defaultSize; @@ -31,17 +41,45 @@ export class HeightCache { this.count = count; } - /** Record a measured height. Returns true when the value changed. */ + /** + * Install the key function. Any change of identity means the index to key + * mapping may have moved, so every offset is rebuilt on the next query. + * Switching the mode (keyed to unkeyed or back) also drops the measurements: + * numeric item keys and index keys share one map and must never collide. + */ + setKeyFn(fn: ((index: number) => ItemKey) | undefined): void { + if (fn === this.keyFn) return; + const modeChanged = (fn === undefined) !== (this.keyFn === undefined); + this.keyFn = fn; + if (modeChanged) this.measured.clear(); + this.dirtyFrom = 0; + } + + keyOf(index: number): ItemKey { + return this.keyFn ? this.keyFn(index) : index; + } + + /** Record a measured size for an index. Returns true when the value changed. */ measure(index: number, size: number): boolean { if (index < 0 || index >= this.count) return false; - if (this.measured.get(index) === size) return false; - this.measured.set(index, size); + return this.measureKey(this.keyOf(index), index, size); + } + + /** + * Record a measured size under a key captured earlier, for measurements that + * are delivered after the data may have moved. The index only says where the + * offsets have to be rebuilt from. + */ + measureKey(key: ItemKey, index: number, size: number): boolean { + if (index < 0 || index >= this.count) return false; + if (this.measured.get(key) === size) return false; + this.measured.set(key, size); this.dirtyFrom = Math.min(this.dirtyFrom, index); return true; } sizeOf(index: number): number { - return this.measured.get(index) ?? this.defaultSize; + return this.measured.get(this.keyOf(index)) ?? this.defaultSize; } /** Pixel offset of the top of the item. offsetOf(count) is the total size. */ diff --git a/src/types.ts b/src/types.ts index 2facfe5..ccec4e9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,16 +1,29 @@ import type { CSSProperties, - FC, JSX, KeyboardEventHandler, ReactNode, Ref, RefObject, } from "react"; +import type { + ItemKey, + ScrollToIndexOptions, + VirtualRange, +} from "./useVirtualWindow"; + +/** How rows are chosen for the next wave. */ +export type RevealMode = "sequential" | "viewport"; export interface VirtualRenderWaveHandle { - /** Scroll so the item at the given index sits at the top of the viewport. */ - scrollTo: (index: number, behavior?: ScrollBehavior) => void; + /** + * Scroll to an item. Pass a behavior string, or { align, behavior }. + * Default align "start", default behavior "smooth". + */ + scrollTo: ( + index: number, + options?: ScrollBehavior | ScrollToIndexOptions + ) => void; /** Scroll to a pixel offset. */ scrollToOffset: (px: number, behavior?: ScrollBehavior) => void; /** Indexes that are currently rendered and revealed. */ @@ -20,12 +33,15 @@ export interface VirtualRenderWaveHandle { } /** - * Props handed to a custom outerElement or innerElement component. - * Spread everything onto your DOM node so scrolling, focus, and keyboard - * navigation keep working. + * Props handed to a custom outerElement or innerElement component. Spread + * every prop onto your DOM node so scrolling, focus, and keyboard navigation + * keep working. On React 19 the ref arrives as a prop; to support React 18 + * too, wrap the component in forwardRef and attach the forwarded ref to the + * node. */ export interface WrapperProps { - ref: RefObject; + /** Attach this to the element you render: the list scrolls and measures through it. */ + ref?: RefObject; style: CSSProperties; className?: string; children: ReactNode; @@ -35,6 +51,18 @@ export interface WrapperProps { "aria-label"?: string; } +/** + * A component accepted as outerElement or innerElement: a function component + * or a forwardRef component taking WrapperProps. Spelled as a bare call + * signature rather than ComponentType, because a forwardRef + * component is not assignable to ComponentType under @types/react 18. The + * return type carries Promise so that a component typed as + * FC is accepted under @types/react 19, where FC allows it. + */ +export type WrapperComponent = ( + props: WrapperProps +) => ReactNode | Promise; + export type HTMLTag = keyof JSX.IntrinsicElements & keyof HTMLElementTagNameMap; export interface VirtualRenderWaveProps { @@ -58,17 +86,35 @@ export interface VirtualRenderWaveProps { overscan?: number; /** Index of the first item to reveal. Default 0. */ startIndex?: number; + /** + * Which rows the wave reveals. Default "sequential", which counts forward + * from startIndex regardless of the scroll position, the behaviour of v3.0. + * "viewport" reveals the rows inside the rendered window in batches and + * never re-hides a revealed row, which lets batchSize stay small on a long + * list. + */ + revealMode?: RevealMode; className?: string; style?: CSSProperties; renderItem: (item: T, index: number) => ReactNode; /** Rendered in place of items the wave has not reached yet. */ renderSkeleton?: (index: number) => ReactNode; /** Stable key per item. Defaults to the item index. */ - getItemKey?: (item: T, index: number) => string | number; + getItemKey?: (item: T, index: number) => ItemKey; /** Scrolls to the index whenever the value changes. */ scrollToIndex?: number; - outerElement?: HTMLTag | FC; - innerElement?: HTMLTag | FC; + /** + * Pixel offset for the first render, read once. The first paint and the + * server markup already show that window. + */ + initialScrollOffset?: number; + /** + * Index to open at, read once. Wins over initialScrollOffset, and is + * corrected once the rows above it have been measured. + */ + initialScrollIndex?: number; + outerElement?: HTMLTag | WrapperComponent; + innerElement?: HTMLTag | WrapperComponent; /** Fade newly revealed items in. Default false. */ transition?: boolean; /** @@ -82,6 +128,11 @@ export interface VirtualRenderWaveProps { endReachedThreshold?: number; /** Called with the current scrollTop, at most once per animation frame. */ onScroll?: (scrollTop: number) => void; + /** + * Called after commit whenever the rendered or the visible range changes. + * Both are half-open: `end` and `visibleEnd` are exclusive. + */ + onRangeChange?: (range: VirtualRange) => void; /** Enable ArrowUp/ArrowDown, PageUp/PageDown, Home and End. Default false. */ keyboardNavigation?: boolean; /** Renders a sticky header for the group of the topmost visible item. */ diff --git a/src/useRenderWave.ts b/src/useRenderWave.ts index 2ed7378..b476342 100644 --- a/src/useRenderWave.ts +++ b/src/useRenderWave.ts @@ -44,9 +44,6 @@ export function useRenderWave({ const batch = Math.max(1, Math.floor(batchSize)); const safeStart = Math.max(0, Math.min(startIndex, length)); - // The only state is the number of waves committed. Everything else is - // derived, so a shrinking or growing `length` can never leave a stale - // cursor pointing past the end of the list. const [steps, setSteps] = useState(0); const cursor = Math.min(safeStart + batch * (steps + 1), length); diff --git a/src/useViewportReveal.ts b/src/useViewportReveal.ts new file mode 100644 index 0000000..3fba56d --- /dev/null +++ b/src/useViewportReveal.ts @@ -0,0 +1,146 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { ItemKey } from "./sizeCache"; + +export interface UseViewportRevealOptions { + /** Total number of items available. */ + count: number; + /** First index of the rendered range, from the windowing layer. */ + start: number; + /** End of the rendered range, exclusive. */ + end: number; + /** Items revealed per wave. Default 20. */ + batchSize?: number; + /** Delay in milliseconds between waves. Default 50. */ + interval?: number; + /** Index of the first item to reveal. Items before it are never revealed. Default 0. */ + startIndex?: number; + /** Set to false to pause the reveal. Nothing new appears, nothing is hidden. Default true. */ + enabled?: boolean; + /** + * Stable key per index. When given, revealed state is tracked by key, so + * sorting or filtering the list does not re-stagger rows the reader has + * already seen. + */ + getItemKey?: (index: number) => ItemKey; +} + +export interface UseViewportRevealResult { + /** True when the item at this index has been revealed. Referentially stable. */ + isRevealed: (index: number) => boolean; + /** Unrevealed items inside the rendered range. */ + pendingCount: number; + /** Forget everything. The next render reveals the first batch of the window. */ + reset: () => void; +} + +/** + * Reveals up to `limit` of the unrevealed rows in [lo, hi), ascending. + * Returns how many were added. + */ +function revealRange( + revealed: Set, + lo: number, + hi: number, + limit: number, + keyOf: (index: number) => ItemKey +): number { + let added = 0; + for (let index = lo; index < hi && added < limit; index++) { + const key = keyOf(index); + if (revealed.has(key)) continue; + revealed.add(key); + added++; + } + return added; +} + +/** + * Reveals the rows inside the rendered window in timed batches. + * + * Where `useRenderWave` counts forward from `startIndex` regardless of where + * the reader is, this follows the window: rows currently on screen are + * revealed first, rows that scroll away stay revealed, and rows that scroll + * into view are picked up by the following waves. Work per wave is bounded by + * the size of the window, not by the length of the list. + */ +export function useViewportReveal({ + count, + start, + end, + batchSize = 20, + interval = 50, + startIndex = 0, + enabled = true, + getItemKey, +}: UseViewportRevealOptions): UseViewportRevealResult { + const batch = Math.max(1, Math.floor(batchSize)); + const safeStart = Math.max(0, startIndex); + const lo = Math.max(start, safeStart, 0); + const hi = Math.min(end, count); + + const revealedRef = useRef>(new Set()); + const keyedRef = useRef(getItemKey !== undefined); + const [version, bumpVersion] = useState(0); + + const keyOf = getItemKey ?? ((index: number) => index); + + const keyed = getItemKey !== undefined; + if (keyedRef.current !== keyed) { + keyedRef.current = keyed; + revealedRef.current = new Set(); + } + + // Revealed during render so the first paint has content and SSR matches; keep it idempotent. + if (revealedRef.current.size === 0 && hi > lo) { + revealRange(revealedRef.current, lo, hi, batch, keyOf); + } + + let pendingCount = 0; + for (let index = lo; index < hi; index++) { + if (!revealedRef.current.has(keyOf(index))) pendingCount++; + } + const hasPending = pendingCount > 0; + + const latest = useRef({ lo, hi, batch, safeStart, keyOf }); + latest.current = { lo, hi, batch, safeStart, keyOf }; + + const isRevealed = useCallback((index: number) => { + const current = latest.current; + return ( + index >= current.safeStart && + revealedRef.current.has(current.keyOf(index)) + ); + }, []); + + // window is read at fire time, not a dependency, so scrolling cannot push the next wave out. + useEffect(() => { + if (!enabled || !hasPending) return; + + let rafId: number | null = null; + const timer = setTimeout(() => { + rafId = requestAnimationFrame(() => { + const current = latest.current; + const added = revealRange( + revealedRef.current, + current.lo, + current.hi, + current.batch, + current.keyOf + ); + if (added > 0) bumpVersion((v) => v + 1); + }); + }, interval); + + return () => { + clearTimeout(timer); + if (rafId !== null) cancelAnimationFrame(rafId); + }; + }, [enabled, interval, hasPending, version]); + + const reset = useCallback(() => { + revealedRef.current = new Set(); + bumpVersion((v) => v + 1); + }, []); + + return { isRevealed, pendingCount, reset }; +} diff --git a/src/useVirtualWindow.ts b/src/useVirtualWindow.ts new file mode 100644 index 0000000..3985770 --- /dev/null +++ b/src/useVirtualWindow.ts @@ -0,0 +1,754 @@ +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; +import { SizeCache } from "./sizeCache"; +import type { ItemKey } from "./sizeCache"; + +export type { ItemKey }; + +/** Where the item lands in the viewport. "auto" only scrolls if it has to. */ +export type ScrollAlign = "start" | "center" | "end" | "auto"; + +export interface ScrollToIndexOptions { + /** Default "start". */ + align?: ScrollAlign; + /** Default "auto", which scrolls instantly. */ + behavior?: ScrollBehavior; +} + +export interface ScrollToOffsetOptions { + /** Default "auto", which scrolls instantly. */ + behavior?: ScrollBehavior; +} + +export interface VirtualItem { + index: number; + /** getItemKey(index) when supplied, otherwise the index. */ + key: ItemKey; + /** Pixel offset of the top of the item within the sizer. */ + offset: number; + /** Measured size, or the estimate until the item has been measured. */ + size: number; +} + +export interface VirtualRange { + /** First rendered index. */ + start: number; + /** One past the last rendered index (exclusive). */ + end: number; + /** First index intersecting the viewport. */ + visibleStart: number; + /** One past the last index intersecting the viewport (exclusive). */ + visibleEnd: number; +} + +export interface UseVirtualWindowOptions { + /** Number of items in the list. */ + count: number; + /** + * Size in pixels used for an item until it has been measured. A value that + * is not positive and finite falls back to 1, which keeps the list windowed. + */ + estimateSize: number; + /** + * Extra items rendered above and below the viewport. Default 5. Clamped to a + * non-negative whole number. + */ + overscan?: number; + /** + * Stable identity per index. Measurements are stored by key, so a reorder of + * the data carries each measured size with its item. A change of function + * identity is read as a reorder and forces one O(count) offset rebuild, so + * memoize it on the data rather than passing a fresh arrow every render. + */ + getItemKey?: (index: number) => ItemKey; + /** + * Supply the scroll container from a ref you already own. An alternative to + * putting the returned scrollRef on the element. + */ + getScrollElement?: () => HTMLElement | null; + /** Scroll offset for the first render. Default 0. Read once. */ + initialScrollOffset?: number; + /** Index to open at. Wins over initialScrollOffset. Read once. */ + initialScrollIndex?: number; + /** Viewport size used until the container is measured. Default 400. Read once. */ + initialViewportSize?: number; + /** + * Pixels between the scroll container's content origin and item 0, for an + * in-flow header, caption or toolbar above the sizer. Default 0. + */ + scrollMargin?: number; + /** + * How an item element is measured. Default `el => el.offsetHeight`. Use + * `el => el.getBoundingClientRect().height` for fractional row heights, such + * as table rows with border collapsing. + */ + measureSize?: (el: HTMLElement) => number; + /** + * Called with the current scroll offset, at most once per animation frame. + * Programmatic scrolls and measurement corrections report through it too. It + * is not called when the container is first attached. + */ + onScroll?: (offset: number) => void; + /** Called whenever any of the four range bounds changes. */ + onRangeChange?: (range: VirtualRange) => void; +} + +export interface UseVirtualWindowResult { + /** Ref callback for the scroll container. */ + scrollRef: (el: HTMLElement | null) => void; + /** Ref callback for the item element at an index. Stable per index. */ + measureRef: (index: number) => (el: HTMLElement | null) => void; + /** The items to render, from start up to end. */ + virtualItems: VirtualItem[]; + /** First rendered index. */ + start: number; + /** One past the last rendered index (exclusive). */ + end: number; + /** First index intersecting the viewport. */ + visibleStart: number; + /** One past the last index intersecting the viewport (exclusive). */ + visibleEnd: number; + /** Size of all items together, for the sizer element. */ + totalSize: number; + /** Current scroll offset of the container. */ + scrollOffset: number; + /** Current size of the viewport. */ + viewportSize: number; + /** Pixel offset of the top of an item. */ + offsetOf(index: number): number; + /** Measured size of an item, or the estimate. */ + sizeOf(index: number): number; + /** Index of the item whose span contains a pixel offset. */ + indexAt(offset: number): number; + /** + * Scroll so the item is aligned in the viewport. Out of range indexes clamp + * to the list; NaN is ignored. + */ + scrollToIndex(index: number, options?: ScrollToIndexOptions): void; + /** Scroll to a pixel offset. NaN is ignored. */ + scrollToOffset(offset: number, options?: ScrollToOffsetOptions): void; + /** The scroll container, or null before it is attached. */ + getScrollElement(): HTMLElement | null; +} + +/** A scroll we issued and still have to keep on target as items are measured. */ +interface ScrollTarget { + index: number; + align: "start" | "center" | "end"; + behavior: ScrollBehavior; + /** Offset the container was sent to, as the container reported it back. */ + issuedOffset: number; + attempts: number; + /** Commits that moved nothing while the container sat on the target. */ + quietPasses: number; + /** False while the target is waiting for a container to be attached. */ + issued: boolean; +} + +/** Corrections give up after this many re-issues, so measurement cannot loop. */ +const MAX_CORRECTION_ATTEMPTS = 5; +/** Quiet commits before a target counts as settled. */ +const SETTLED_QUIET_PASSES = 2; +/** Quiet period that counts as the end of a smooth scroll. */ +const SMOOTH_SETTLE_MS = 150; + +const useIsomorphicLayoutEffect = + typeof window !== "undefined" ? useLayoutEffect : useEffect; + +const getScrollOffset = (el: HTMLElement): number => el.scrollTop; +const getViewportSize = (el: HTMLElement): number => el.clientHeight; +const defaultMeasure = (el: HTMLElement): number => el.offsetHeight; + +/** + * Headless windowing: which items to render, where to put them, and how to + * scroll to one. It renders nothing and owns no styles. + * + * Put `scrollRef` on a scroll container with a constrained height and + * `overflow: auto`, give the element inside it a height of `totalSize`, and + * position each `virtualItems` entry at its `offset`. Item elements take + * `measureRef(index)`, which measures them and keeps the offsets honest as + * they turn out taller or shorter than the estimate. + * + * The first render is derived only from `count`, `estimateSize`, `overscan`, + * `scrollMargin`, `getItemKey` and the `initial*` options, so server markup and + * the first client render agree. + */ +export function useVirtualWindow({ + count, + estimateSize: estimateSizeOption, + overscan: overscanOption = 5, + getItemKey, + getScrollElement: getScrollElementOption, + initialScrollOffset, + initialScrollIndex, + initialViewportSize, + scrollMargin = 0, + measureSize, + onScroll, + onRangeChange, +}: UseVirtualWindowOptions): UseVirtualWindowResult { + const estimateSize = + Number.isFinite(estimateSizeOption) && estimateSizeOption > 0 + ? estimateSizeOption + : 1; + const overscan = Number.isFinite(overscanOption) + ? Math.max(0, Math.floor(overscanOption)) + : 0; + + const cacheRef = useRef(null); + if (cacheRef.current === null) cacheRef.current = new SizeCache(estimateSize); + const cache = cacheRef.current; + cache.setDefaultSize(estimateSize); + cache.setCount(count); + cache.setKeyFn(getItemKey); + + const initialRef = useRef({ + initialScrollOffset, + initialScrollIndex, + initialViewportSize, + }); + + const [scrollOffset, setScrollOffset] = useState(() => + initialScrollIndex !== undefined && !Number.isNaN(initialScrollIndex) + ? Math.min(Math.max(0, initialScrollIndex), count) * estimateSize + + scrollMargin + : Number.isFinite(initialScrollOffset) + ? Math.max(0, initialScrollOffset as number) + : 0 + ); + const [viewportSize, setViewportSize] = useState( + () => initialViewportSize ?? 400 + ); + const [scrollEl, setScrollEl] = useState(null); + const [heightsVersion, bumpHeightsVersion] = useState(0); + + const latest = useRef({ + onScroll, + onRangeChange, + getItemKey, + getScrollElement: getScrollElementOption, + estimateSize, + overscan, + count, + scrollMargin, + measureSize, + }); + const scrollOffsetRef = useRef(scrollOffset); + const viewportSizeRef = useRef(viewportSize); + useIsomorphicLayoutEffect(() => { + latest.current = { + onScroll, + onRangeChange, + getItemKey, + getScrollElement: getScrollElementOption, + estimateSize, + overscan, + count, + scrollMargin, + measureSize, + }; + scrollOffsetRef.current = scrollOffset; + viewportSizeRef.current = viewportSize; + }); + + const scrollElRef = useRef(null); + const scrollRef = useCallback((el: HTMLElement | null) => { + scrollElRef.current = el; + setScrollEl(el); + }, []); + + useIsomorphicLayoutEffect(() => { + const get = latest.current.getScrollElement; + if (!get) return; + const el = get(); + if (el === scrollElRef.current) return; + scrollElRef.current = el; + setScrollEl(el); + }); + + const observerRef = useRef(null); + const observedChangeRef = useRef(false); + const elementToIndex = useRef(new Map()); + const elementToKey = useRef(new Map()); + const indexToElement = useRef(new Map()); + const refCallbacks = useRef( + new Map void>() + ); + + const readSize = useCallback( + (el: HTMLElement) => (latest.current.measureSize ?? defaultMeasure)(el), + [] + ); + + const getObserver = useCallback(() => { + if (observerRef.current) return observerRef.current; + if (typeof ResizeObserver === "undefined") return null; + observerRef.current = new ResizeObserver((entries) => { + const sizes = cacheRef.current; + if (!sizes) return; + let changed = false; + for (const entry of entries) { + const target = entry.target as HTMLElement; + const index = elementToIndex.current.get(target); + const key = elementToKey.current.get(target); + if (index === undefined || key === undefined) continue; + const size = readSize(target); + if (size > 0 && sizes.measureKey(key, index, size)) changed = true; + } + if (changed) { + observedChangeRef.current = true; + bumpHeightsVersion((v) => v + 1); + } + }); + return observerRef.current; + }, [readSize]); + + useEffect(() => { + // Re-observe after a StrictMode remount: the item refs attached before this ran. + const observer = getObserver(); + if (observer) { + for (const el of indexToElement.current.values()) observer.observe(el); + } + return () => { + observerRef.current?.disconnect(); + observerRef.current = null; + }; + }, [getObserver]); + + const measureRef = useCallback( + (index: number) => { + let cb = refCallbacks.current.get(index); + if (!cb) { + cb = (el: HTMLElement | null) => { + const prev = indexToElement.current.get(index); + if (el) { + const key = cacheRef.current?.keyOf(index) ?? index; + if (prev === el) { + elementToKey.current.set(el, key); + return; + } + if (prev) { + observerRef.current?.unobserve(prev); + elementToIndex.current.delete(prev); + elementToKey.current.delete(prev); + } + indexToElement.current.set(index, el); + elementToIndex.current.set(el, index); + elementToKey.current.set(el, key); + getObserver()?.observe(el); + } else if (prev) { + observerRef.current?.unobserve(prev); + elementToIndex.current.delete(prev); + elementToKey.current.delete(prev); + indexToElement.current.delete(index); + } + }; + refCallbacks.current.set(index, cb); + } + return cb; + }, + [getObserver] + ); + + const totalSize = cache.totalSize(); + let visibleStart = 0; + let visibleEnd = 0; + let start = 0; + let end = 0; + if (count > 0) { + const base = scrollOffset - scrollMargin; + visibleStart = cache.indexAt(base); + visibleEnd = cache.indexAt(base + Math.max(0, viewportSize - 1)) + 1; + start = Math.max(0, visibleStart - overscan); + end = Math.min(count, visibleEnd + overscan); + } + + const virtualItems: VirtualItem[] = []; + for (let index = start; index < end; index++) { + virtualItems.push({ + index, + key: cache.keyOf(index), + offset: cache.offsetOf(index), + size: cache.sizeOf(index), + }); + } + + const pendingRef = useRef(null); + const smoothTimerRef = useRef | null>(null); + + const clearSmoothTimer = useCallback(() => { + if (smoothTimerRef.current !== null) { + clearTimeout(smoothTimerRef.current); + smoothTimerRef.current = null; + } + }, []); + + const clearTarget = useCallback(() => { + pendingRef.current = null; + clearSmoothTimer(); + }, [clearSmoothTimer]); + + const maxScrollOf = useCallback((el: HTMLElement | null) => { + if (el) return Math.max(0, el.scrollHeight - el.clientHeight); + const sizes = cacheRef.current; + const total = sizes ? sizes.totalSize() : 0; + return Math.max( + 0, + total + latest.current.scrollMargin - viewportSizeRef.current + ); + }, []); + + const targetOffsetFor = useCallback( + (index: number, align: "start" | "center" | "end") => { + const sizes = cacheRef.current; + if (!sizes) return 0; + const viewport = viewportSizeRef.current; + const s = sizes.offsetOf(index) + latest.current.scrollMargin; + const size = sizes.sizeOf(index); + let target = s; + if (align === "center") target = s - (viewport - size) / 2; + else if (align === "end") target = s + size - viewport; + return Math.max(0, Math.min(target, maxScrollOf(scrollElRef.current))); + }, + [maxScrollOf] + ); + + /** Resolves "auto" against the current viewport. null means no scroll. */ + const resolveAlign = useCallback( + (index: number, align: ScrollAlign): "start" | "center" | "end" | null => { + if (align !== "auto") return align; + const sizes = cacheRef.current; + if (!sizes) return "start"; + const offset = scrollOffsetRef.current; + const viewport = viewportSizeRef.current; + const s = sizes.offsetOf(index) + latest.current.scrollMargin; + const size = sizes.sizeOf(index); + if (size > viewport) { + if (s <= offset && s + size >= offset + viewport) return null; + return s > offset ? "start" : "end"; + } + if (s >= offset && s + size <= offset + viewport) return null; + return s < offset ? "start" : "end"; + }, + [] + ); + + const startSmoothTimer = useCallback(() => { + clearSmoothTimer(); + smoothTimerRef.current = setTimeout(() => { + smoothTimerRef.current = null; + const pending = pendingRef.current; + const el = scrollElRef.current; + if (!pending || !el) return; + const newTarget = targetOffsetFor(pending.index, pending.align); + if (Math.abs(newTarget - pending.issuedOffset) > 1) { + el.scrollTop = newTarget; + const issued = getScrollOffset(el); + pending.issuedOffset = issued; + setScrollOffset(issued); + } + pending.behavior = "auto"; + pending.attempts = 1; + pending.quietPasses = 0; + }, SMOOTH_SETTLE_MS); + }, [clearSmoothTimer, targetOffsetFor]); + + const issueScroll = useCallback( + ( + index: number, + align: "start" | "center" | "end", + behavior: ScrollBehavior + ) => { + const el = scrollElRef.current; + const target = targetOffsetFor(index, align); + if (!el) { + pendingRef.current = { + index, + align, + behavior, + issuedOffset: target, + attempts: 0, + quietPasses: 0, + issued: false, + }; + return; + } + clearSmoothTimer(); + pendingRef.current = { + index, + align, + behavior, + issuedOffset: target, + attempts: 0, + quietPasses: 0, + issued: true, + }; + if (behavior === "smooth") { + el.scrollTo({ top: target, behavior: "smooth" }); + startSmoothTimer(); + return; + } + el.scrollTop = target; + const issued = getScrollOffset(el); + pendingRef.current.issuedOffset = issued; + setScrollOffset(issued); + }, + [clearSmoothTimer, startSmoothTimer, targetOffsetFor] + ); + + const scrollToIndex = useCallback( + (index: number, options?: ScrollToIndexOptions) => { + const total = latest.current.count; + if (total === 0) return; + if (Number.isNaN(index)) return; + const clamped = Math.min(Math.max(0, Math.floor(index)), total - 1); + const align = resolveAlign(clamped, options?.align ?? "start"); + if (align === null) return; + issueScroll(clamped, align, options?.behavior ?? "auto"); + }, + [issueScroll, resolveAlign] + ); + + const scrollToOffset = useCallback( + (offset: number, options?: ScrollToOffsetOptions) => { + if (Number.isNaN(offset)) return; + clearTarget(); + const el = scrollElRef.current; + if (!el) return; + const target = Math.max(0, Math.min(offset, maxScrollOf(el))); + if ((options?.behavior ?? "auto") === "smooth") { + el.scrollTo({ top: target, behavior: "smooth" }); + return; + } + el.scrollTop = target; + setScrollOffset(getScrollOffset(el)); + }, + [clearTarget, maxScrollOf] + ); + + /** + * Keeps an issued scroll on its item while the items around it are measured. + * Runs after every commit; `geometryChanged` says whether this commit moved + * anything, which is what tells a stale target from a settled one. + */ + const checkPendingTarget = useCallback( + (geometryChanged: boolean) => { + const pending = pendingRef.current; + const el = scrollElRef.current; + if (!pending || !el || !pending.issued) return; + if (pending.index >= latest.current.count) { + clearTarget(); + return; + } + if (pending.behavior === "smooth") return; + const landed = Math.abs(getScrollOffset(el) - pending.issuedOffset) <= 1; + if (!landed) return; + const newTarget = targetOffsetFor(pending.index, pending.align); + if (Math.abs(newTarget - pending.issuedOffset) <= 1) { + if (!geometryChanged) { + pending.quietPasses += 1; + if (pending.quietPasses >= SETTLED_QUIET_PASSES) clearTarget(); + } + return; + } + el.scrollTop = newTarget; + const issued = getScrollOffset(el); + pending.issuedOffset = issued; + setScrollOffset(issued); + pending.quietPasses = 0; + pending.attempts += 1; + if (pending.attempts >= MAX_CORRECTION_ATTEMPTS) clearTarget(); + }, + [clearTarget, targetOffsetFor] + ); + + const attachedOnceRef = useRef(false); + const lastAttachedElRef = useRef(null); + + useIsomorphicLayoutEffect(() => { + const el = scrollEl; + if (!el) return; + + if (lastAttachedElRef.current && lastAttachedElRef.current !== el) { + clearTarget(); + } + lastAttachedElRef.current = el; + + if (!attachedOnceRef.current) { + attachedOnceRef.current = true; + const initial = initialRef.current; + if (initial.initialScrollIndex !== undefined) { + scrollToIndex(initial.initialScrollIndex, { + align: "start", + behavior: "auto", + }); + } else if ( + initial.initialScrollOffset !== undefined && + initial.initialScrollOffset > 0 + ) { + el.scrollTop = initial.initialScrollOffset; + } + } + const pending = pendingRef.current; + if (pending && !pending.issued) { + issueScroll(pending.index, pending.align, pending.behavior); + } + + const size = getViewportSize(el); + if (size > 0) setViewportSize(size); + setScrollOffset(getScrollOffset(el)); + + let rafId: number | null = null; + + const handleFrame = () => { + rafId = null; + const offset = getScrollOffset(el); + const target = pendingRef.current; + if (target && target.issued) { + if (target.behavior === "smooth") { + startSmoothTimer(); + } else if (Math.abs(offset - target.issuedOffset) > 1) { + clearTarget(); + } + } + setScrollOffset(offset); + latest.current.onScroll?.(offset); + }; + + const handleScroll = () => { + if (rafId === null) rafId = requestAnimationFrame(handleFrame); + }; + + const handleUserInput = () => { + clearTarget(); + }; + + const handleViewportResize = () => { + setViewportSize(getViewportSize(el)); + }; + + el.addEventListener("scroll", handleScroll, { passive: true }); + el.addEventListener("wheel", handleUserInput, { passive: true }); + el.addEventListener("touchstart", handleUserInput, { passive: true }); + el.addEventListener("pointerdown", handleUserInput, { passive: true }); + el.addEventListener("keydown", handleUserInput, { passive: true }); + + let viewportObserver: ResizeObserver | null = null; + if (typeof ResizeObserver !== "undefined") { + viewportObserver = new ResizeObserver(handleViewportResize); + viewportObserver.observe(el); + } + + return () => { + el.removeEventListener("scroll", handleScroll); + el.removeEventListener("wheel", handleUserInput); + el.removeEventListener("touchstart", handleUserInput); + el.removeEventListener("pointerdown", handleUserInput); + el.removeEventListener("keydown", handleUserInput); + viewportObserver?.disconnect(); + if (rafId !== null) cancelAnimationFrame(rafId); + clearSmoothTimer(); + }; + }, [ + scrollEl, + clearSmoothTimer, + clearTarget, + issueScroll, + scrollToIndex, + startSmoothTimer, + ]); + + const lastViewportRef = useRef(viewportSize); + const suppressRangeReportRef = useRef(false); + + useIsomorphicLayoutEffect(() => { + const sizes = cacheRef.current; + if (!sizes) return; + let changed = false; + for (const [index, el] of indexToElement.current) { + const size = readSize(el); + if (size > 0 && sizes.measure(index, size)) changed = true; + } + if (changed) { + bumpHeightsVersion((v) => v + 1); + suppressRangeReportRef.current = true; + } + + const observedChange = observedChangeRef.current; + observedChangeRef.current = false; + const viewportChanged = lastViewportRef.current !== viewportSize; + lastViewportRef.current = viewportSize; + checkPendingTarget(changed || observedChange || viewportChanged); + + const callbacks = refCallbacks.current; + if (callbacks.size > 2 * (end - start) + 64) { + for (const index of callbacks.keys()) { + if (index < start || index >= end) callbacks.delete(index); + } + } + }); + + const lastReportedRef = useRef(null); + + useEffect(() => { + if (suppressRangeReportRef.current) { + suppressRangeReportRef.current = false; + return; + } + const last = lastReportedRef.current; + const range: VirtualRange = { start, end, visibleStart, visibleEnd }; + if (last === null) { + lastReportedRef.current = range; + if (end > start) latest.current.onRangeChange?.(range); + return; + } + if ( + last.start === range.start && + last.end === range.end && + last.visibleStart === range.visibleStart && + last.visibleEnd === range.visibleEnd + ) { + return; + } + lastReportedRef.current = range; + latest.current.onRangeChange?.(range); + }, [start, end, visibleStart, visibleEnd, heightsVersion]); + + const offsetOf = useCallback( + (index: number) => cacheRef.current?.offsetOf(index) ?? 0, + [] + ); + const sizeOf = useCallback( + (index: number) => cacheRef.current?.sizeOf(index) ?? 0, + [] + ); + const indexAt = useCallback( + (offset: number) => cacheRef.current?.indexAt(offset) ?? 0, + [] + ); + const getScrollElement = useCallback(() => scrollElRef.current, []); + + return { + scrollRef, + measureRef, + virtualItems, + start, + end, + visibleStart, + visibleEnd, + totalSize, + scrollOffset, + viewportSize, + offsetOf, + sizeOf, + indexAt, + scrollToIndex, + scrollToOffset, + getScrollElement, + }; +} diff --git a/test/heightCache.test.ts b/test/heightCache.test.ts deleted file mode 100644 index 289006c..0000000 --- a/test/heightCache.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { HeightCache } from "../src/heightCache"; - -describe("HeightCache", () => { - it("computes offsets and total from the default size", () => { - const cache = new HeightCache(40); - cache.setCount(10); - expect(cache.offsetOf(0)).toBe(0); - expect(cache.offsetOf(3)).toBe(120); - expect(cache.totalSize()).toBe(400); - }); - - it("clamps offsetOf outside the range", () => { - const cache = new HeightCache(40); - cache.setCount(5); - expect(cache.offsetOf(-2)).toBe(0); - expect(cache.offsetOf(99)).toBe(200); - }); - - it("incorporates measurements into offsets", () => { - const cache = new HeightCache(40); - cache.setCount(10); - expect(cache.totalSize()).toBe(400); - - expect(cache.measure(2, 100)).toBe(true); - expect(cache.offsetOf(2)).toBe(80); - expect(cache.offsetOf(3)).toBe(180); - expect(cache.totalSize()).toBe(460); - }); - - it("reports unchanged measurements as no-ops", () => { - const cache = new HeightCache(40); - cache.setCount(10); - cache.measure(2, 100); - expect(cache.measure(2, 100)).toBe(false); - expect(cache.measure(-1, 100)).toBe(false); - expect(cache.measure(10, 100)).toBe(false); - }); - - it("finds the item at an offset with boundary offsets belonging to the next item", () => { - const cache = new HeightCache(40); - cache.setCount(100); - expect(cache.indexAt(-10)).toBe(0); - expect(cache.indexAt(0)).toBe(0); - expect(cache.indexAt(39)).toBe(0); - expect(cache.indexAt(40)).toBe(1); - expect(cache.indexAt(3999)).toBe(99); - expect(cache.indexAt(999999)).toBe(99); - }); - - it("hit tests correctly with mixed heights", () => { - const cache = new HeightCache(40); - cache.setCount(5); - cache.measure(0, 10); - cache.measure(1, 200); - // Layout: [0..10) [10..210) [210..250) [250..290) [290..330) - expect(cache.indexAt(5)).toBe(0); - expect(cache.indexAt(10)).toBe(1); - expect(cache.indexAt(209)).toBe(1); - expect(cache.indexAt(210)).toBe(2); - expect(cache.totalSize()).toBe(330); - }); - - it("handles count changes in both directions", () => { - const cache = new HeightCache(40); - cache.setCount(10); - cache.measure(9, 100); - expect(cache.totalSize()).toBe(460); - - cache.setCount(4); - expect(cache.totalSize()).toBe(160); - - cache.setCount(12); - // The measurement for index 9 persists across the shrink and regrow. - expect(cache.totalSize()).toBe(40 * 11 + 100); - }); - - it("invalidates everything when the default size changes", () => { - const cache = new HeightCache(40); - cache.setCount(10); - cache.measure(0, 100); - expect(cache.totalSize()).toBe(460); - - cache.setDefaultSize(50); - expect(cache.totalSize()).toBe(100 + 9 * 50); - expect(cache.offsetOf(2)).toBe(150); - }); - - it("handles an empty list", () => { - const cache = new HeightCache(40); - expect(cache.totalSize()).toBe(0); - expect(cache.indexAt(100)).toBe(0); - expect(cache.offsetOf(0)).toBe(0); - }); -}); diff --git a/tsconfig.build.json b/tsconfig.build.json index c8a2806..4f83fe2 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -4,8 +4,6 @@ "noEmit": false, "declaration": true, "emitDeclarationOnly": true, - "declarationDir": "dist/types", - "outDir": "dist", "types": [] }, "include": ["src"] diff --git a/vite.config.ts b/vite.config.ts index 5dbc994..44965c2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,6 +1,18 @@ import { defineConfig } from "vitest/config"; +import dts from "vite-plugin-dts"; export default defineConfig({ + plugins: [ + dts({ + tsconfigPath: "./tsconfig.build.json", + // One bundled declaration file, so nothing ships an extensionless + // relative import that node16 resolution cannot follow. + bundleTypes: true, + // The require condition needs its own declaration file, otherwise + // node16 reads the ESM declarations as CJS and reports a masquerade. + outDirs: ["dist", { dir: "dist", moduleFormat: "cjs" }], + }), + ], build: { target: "es2020", sourcemap: true, From 1bdb1bc22f4561c12acfc050889eb6b64445cc15 Mon Sep 17 00:00:00 2001 From: dev-intj <42313770+sudo-ezekiel@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:35:12 +0300 Subject: [PATCH 2/4] test: cover the 3.1.0 surface and every fix in it 179 tests across 18 files. New suites for the size cache (including a property test against a brute-force prefix sum), the headless hook and its edge cases, the viewport reveal mode, server rendering, end detection, the component's scroll and feature surface, and the five natural shapes a custom outerElement or innerElement can take, which are checked by tsc as well as at runtime. test/regressions310.test.tsx holds one failing-before-the-fix case for each bug fixed in this release. test/setup.ts guards the scrollTo stub, since the SSR suites run in the node environment where there is no Element to patch. --- test/componentFeatures.test.tsx | 549 +++++++++++++++++++ test/componentScroll.test.tsx | 193 +++++++ test/endReached.test.tsx | 145 +++++ test/regressions310.test.tsx | 441 ++++++++++++++++ test/renderWaveOptions.test.tsx | 113 ++++ test/revealMode.test.tsx | 186 +++++++ test/setup.ts | 30 +- test/sizeCache.test.ts | 165 ++++++ test/sizeCacheProperties.test.ts | 300 +++++++++++ test/ssr.test.tsx | 111 ++++ test/useViewportReveal.test.tsx | 282 ++++++++++ test/useViewportRevealEdges.test.tsx | 289 ++++++++++ test/useVirtualWindow.test.tsx | 760 +++++++++++++++++++++++++++ test/useVirtualWindowEdges.test.tsx | 520 ++++++++++++++++++ test/virtualBehaviours.test.tsx | 451 ++++++++++++++++ test/wrapperElements.test.tsx | 451 ++++++++++++++++ 16 files changed, 4972 insertions(+), 14 deletions(-) create mode 100644 test/componentFeatures.test.tsx create mode 100644 test/componentScroll.test.tsx create mode 100644 test/endReached.test.tsx create mode 100644 test/regressions310.test.tsx create mode 100644 test/renderWaveOptions.test.tsx create mode 100644 test/revealMode.test.tsx create mode 100644 test/sizeCache.test.ts create mode 100644 test/sizeCacheProperties.test.ts create mode 100644 test/ssr.test.tsx create mode 100644 test/useViewportReveal.test.tsx create mode 100644 test/useViewportRevealEdges.test.tsx create mode 100644 test/useVirtualWindow.test.tsx create mode 100644 test/useVirtualWindowEdges.test.tsx create mode 100644 test/virtualBehaviours.test.tsx create mode 100644 test/wrapperElements.test.tsx diff --git a/test/componentFeatures.test.tsx b/test/componentFeatures.test.tsx new file mode 100644 index 0000000..0dd413c --- /dev/null +++ b/test/componentFeatures.test.tsx @@ -0,0 +1,549 @@ +import { act, render, screen } from "@testing-library/react"; +import { createRef, type Ref } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { renderToString } from "react-dom/server"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import type { + VirtualRenderWaveHandle, + VirtualRenderWaveProps, +} from "../src/types"; +import { MockResizeObserver } from "./setup"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. Copied from +// VirtualRenderWave.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const keyedRows = (n: number) => + Array.from({ length: n }, (_, i) => ({ id: i, label: `Item ${i}` })); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +/** Interval 50 plus the frame the wave is committed on. */ +const wave = () => { + act(() => { + vi.advanceTimersByTime(100); + }); +}; + +const shown = (index: number) => screen.queryByText(`Item ${index}`) !== null; +const skeleton = (index: number) => + screen.queryByText(`Skeleton ${index}`) !== null; + +const rowObserverOf = (el: Element) => + MockResizeObserver.instances.find((ro) => ro.observed.has(el)); + +const stubHeight = (el: Element, value: number) => { + Object.defineProperty(el, "offsetHeight", { configurable: true, value }); +}; + +type ListProps = Partial> & { + ref?: Ref; +}; + +const list = (props: ListProps = {}) => ( +
{item}
} + renderSkeleton={(i) =>
Skeleton {i}
} + {...props} + /> +); + +describe("VirtualRenderWave, viewport reveal edge cases", () => { + it("keeps a row's revealed key revealed after a reorder, without re-staggering", () => { + const rows = keyedRows(20); + const { rerender } = render( + item.id} + renderItem={(item) =>
{item.label}
} + renderSkeleton={(i) =>
Skeleton {i}
} + /> + ); + + // First batch of the window, ids 0..4. + for (let i = 0; i < 5; i++) expect(shown(i)).toBe(true); + for (let i = 5; i < 20; i++) expect(skeleton(i)).toBe(true); + + rerender( + item.id} + renderItem={(item) =>
{item.label}
} + renderSkeleton={(i) =>
Skeleton {i}
} + /> + ); + + // Ids 0..4 are still revealed, now sitting at indexes 19..15. No + // re-stagger happens: this holds without advancing a single wave. + for (let id = 0; id <= 4; id++) expect(shown(id)).toBe(true); + for (let index = 0; index <= 14; index++) + expect(skeleton(index)).toBe(true); + for (let index = 15; index <= 19; index++) { + expect(shown(19 - index)).toBe(true); + } + }); + + it("never reveals rows before startIndex, and reveals from startIndex in batches", () => { + const { container } = render( + list({ + items: items(30), + revealMode: "viewport", + startIndex: 5, + overscan: 5, + }) + ); + const outer = container.firstElementChild as HTMLElement; + void outer; + + for (let i = 0; i < 5; i++) expect(skeleton(i)).toBe(true); + expect(shown(5)).toBe(true); + expect(shown(9)).toBe(true); + expect(shown(10)).toBe(false); + + wave(); + wave(); + wave(); + wave(); + + // The rows before startIndex never reveal, no matter how many waves run. + for (let i = 0; i < 5; i++) expect(skeleton(i)).toBe(true); + // The window [5, 15) has fully revealed by now. + for (let i = 5; i < 15; i++) expect(shown(i)).toBe(true); + }); + + it("shows exactly batchSize revealed items and the rest skeletons on the very first client render", () => { + const { container } = render( +
{item}
} + renderSkeleton={(i) =>
Skeleton {i}
} + /> + ); + + const revealedCount = (container.innerHTML.match(/data-kind="item"/g) ?? []) + .length; + const skeletonCount = ( + container.innerHTML.match(/data-kind="skeleton"/g) ?? [] + ).length; + + expect(revealedCount).toBe(5); + expect(skeletonCount).toBe(10); + }); + + it("marks only revealed rows with the fade transition in viewport mode", () => { + const { container } = render( + list({ + items: items(30), + revealMode: "viewport", + overscan: 5, + batchSize: 5, + transition: true, + }) + ); + + const rows = Array.from(container.querySelectorAll('[role="listitem"]')); + expect(rows.length).toBeGreaterThan(0); + + const revealedRows = rows.filter((row) => + row.textContent?.startsWith("Item") + ); + const skeletonRows = rows.filter((row) => + row.textContent?.startsWith("Skeleton") + ); + expect(revealedRows.length).toBeGreaterThan(0); + expect(skeletonRows.length).toBeGreaterThan(0); + + for (const row of revealedRows) { + expect((row as HTMLElement).style.animation).toContain("rrw-fade-in"); + } + for (const row of skeletonRows) { + expect((row as HTMLElement).style.animation).toBe(""); + } + }); + + it("lists no revealed indexes right after a jump to a part of the list nobody has seen, then the first batch after a wave", () => { + const ref = createRef(); + const { container } = render( + list({ + items: items(1000), + ref, + revealMode: "viewport", + overscan: 5, + batchSize: 5, + }) + ); + const outer = container.firstElementChild as HTMLElement; + + scrollTo(outer, 4000); + expect(ref.current?.getVisibleIndexes()).toEqual([]); + + wave(); + expect(ref.current?.getVisibleIndexes()).toEqual([95, 96, 97, 98, 99]); + }); +}); + +describe("VirtualRenderWave, onRangeChange", () => { + it("fires on mount, on scroll, and when a shrinking list changes the range, with half-open bounds matching the rendered rows", () => { + const onRangeChange = vi.fn(); + const { container, rerender } = render( + list({ items: items(1000), onRangeChange, batchSize: 1000 }) + ); + const outer = container.firstElementChild as HTMLElement; + + expect(onRangeChange).toHaveBeenCalledTimes(1); + let last = onRangeChange.mock.calls[onRangeChange.mock.calls.length - 1][0]; + expect(last).toEqual({ + start: 0, + end: 15, + visibleStart: 0, + visibleEnd: 10, + }); + let posinsets = Array.from( + container.querySelectorAll('[role="listitem"]') + ).map((el) => Number(el.getAttribute("aria-posinset"))); + expect(Math.min(...posinsets)).toBe(last.start + 1); + expect(Math.max(...posinsets)).toBe(last.end); + + scrollTo(outer, 4000); + expect(onRangeChange).toHaveBeenCalledTimes(2); + last = onRangeChange.mock.calls[onRangeChange.mock.calls.length - 1][0]; + expect(last).toEqual({ + start: 95, + end: 115, + visibleStart: 100, + visibleEnd: 110, + }); + posinsets = Array.from(container.querySelectorAll('[role="listitem"]')).map( + (el) => Number(el.getAttribute("aria-posinset")) + ); + expect(Math.min(...posinsets)).toBe(last.start + 1); + expect(Math.max(...posinsets)).toBe(last.end); + + const callsBeforeShrink = onRangeChange.mock.calls.length; + rerender(list({ items: items(50), onRangeChange, batchSize: 1000 })); + expect(onRangeChange.mock.calls.length).toBeGreaterThan(callsBeforeShrink); + last = onRangeChange.mock.calls[onRangeChange.mock.calls.length - 1][0]; + expect(last.end).toBeLessThanOrEqual(50); + expect(last.end).toBeGreaterThan(last.start); + }); +}); + +describe("VirtualRenderWave, dynamic heights and scroll targeting", () => { + it("corrects a scrollTop opened at initialScrollIndex once an earlier row measures taller", () => { + const { container, rerender } = render( + list({ + items: items(1000), + initialScrollIndex: 50, + overscan: 40, + batchSize: 1000, + }) + ); + const outer = container.firstElementChild as HTMLElement; + expect(outer.scrollTop).toBe(2000); + + const row10 = container.querySelector( + '[aria-posinset="11"]' + ) as HTMLElement; + expect(row10).toBeTruthy(); + stubHeight(row10, 100); + const observer = rowObserverOf(row10); + act(() => { + observer?.trigger([row10]); + }); + + // The row observer's report alone does not commit; force the pass that + // reads it by re-rendering, exactly as the underlying hook's own test + // does for the same correction. + act(() => { + rerender( + list({ + items: items(1000), + initialScrollIndex: 50, + overscan: 40, + batchSize: 1000, + }) + ); + }); + + expect(outer.scrollTop).toBe(2060); + }); + + it("handles a center align, a no-op auto align on a visible row, and an offset scroll that survives a smooth scroll's settle window", () => { + const ref = createRef(); + const { container } = render( + list({ items: items(1000), ref, batchSize: 1000 }) + ); + const outer = container.firstElementChild as HTMLElement; + + act(() => { + ref.current?.scrollTo(50, { align: "center", behavior: "auto" }); + }); + expect(outer.scrollTop).toBe(1820); + + // Item 50 (offset 2000, size 40) is already fully inside the viewport + // [1820, 2220), so an "auto" align has nothing to do. + act(() => { + ref.current?.scrollTo(50, { align: "auto" }); + }); + expect(outer.scrollTop).toBe(1820); + + act(() => { + ref.current?.scrollTo(10); + }); + expect(outer.scrollTop).toBe(400); + + act(() => { + ref.current?.scrollToOffset(123); + }); + expect(outer.scrollTop).toBe(123); + + act(() => { + vi.advanceTimersByTime(300); + }); + expect(outer.scrollTop).toBe(123); + }); + + it("opens at initialScrollIndex over an initial scrollToIndex, then honors later changes to scrollToIndex", () => { + const { container, rerender } = render( + list({ + items: items(1000), + initialScrollIndex: 50, + scrollToIndex: 10, + batchSize: 1000, + }) + ); + const outer = container.firstElementChild as HTMLElement; + expect(outer.scrollTop).toBe(2000); + + act(() => { + rerender( + list({ + items: items(1000), + initialScrollIndex: 50, + scrollToIndex: 80, + batchSize: 1000, + }) + ); + }); + expect(outer.scrollTop).toBe(3200); + }); + + it("carries a measured size to its item's new position after a keyed reorder", () => { + const rows = keyedRows(5); + const { rerender } = render( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + + const rowA = screen + .getByText("Item 0") + .closest('[role="listitem"]') as HTMLElement; + stubHeight(rowA, 100); + const observer = rowObserverOf(rowA); + act(() => { + observer?.trigger([rowA]); + }); + + // Reorder: b, c, a, d, e. a's 100px size now belongs at its new index 2, + // so the row after it (d, at index 3) sits at 40 + 40 + 100 = 180px. + const reordered = [rows[1], rows[2], rows[0], rows[3], rows[4]]; + rerender( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + + const rowD = screen + .getByText("Item 3") + .closest('[role="listitem"]') as HTMLElement; + expect(rowD.style.top).toBe("180px"); + }); + + it("keeps a measured size across a rerender that changes only the identity of an inline getItemKey", () => { + const rows = keyedRows(5); + const { rerender } = render( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + + const row0 = screen + .getByText("Item 0") + .closest('[role="listitem"]') as HTMLElement; + stubHeight(row0, 100); + const observer = rowObserverOf(row0); + act(() => { + observer?.trigger([row0]); + }); + + const row1Before = screen + .getByText("Item 1") + .closest('[role="listitem"]') as HTMLElement; + expect(row1Before.style.top).toBe("100px"); + + // Same items array, but a brand new inline arrow for getItemKey. + rerender( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + + const row1After = screen + .getByText("Item 1") + .closest('[role="listitem"]') as HTMLElement; + expect(row1After.style.top).toBe("100px"); + }); +}); + +describe("VirtualRenderWave, viewport reveal hydration", () => { + it("hydrates in viewport mode without logging a hydration mismatch", () => { + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const element = ( + index} + renderItem={(item) =>
{item}
} + renderSkeleton={(i) =>
Skeleton {i}
} + /> + ); + const markup = renderToString(element); + const container = document.createElement("div"); + container.innerHTML = markup; + document.body.appendChild(container); + + let root: ReturnType | undefined; + act(() => { + root = hydrateRoot(container, element); + }); + + const hydrationErrors = errorSpy.mock.calls.filter((call) => { + const message = String(call[0]); + return ( + message.includes("Hydration failed") || + message.includes("did not match") + ); + }); + expect(hydrationErrors).toEqual([]); + + act(() => { + root?.unmount(); + }); + container.remove(); + } finally { + errorSpy.mockRestore(); + } + }); +}); diff --git a/test/componentScroll.test.tsx b/test/componentScroll.test.tsx new file mode 100644 index 0000000..3fa2de8 --- /dev/null +++ b/test/componentScroll.test.tsx @@ -0,0 +1,193 @@ +import { act, render, screen } from "@testing-library/react"; +import { createRef, type ReactElement, type Ref } from "react"; +import { renderToString } from "react-dom/server"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import type { + VirtualRenderWaveHandle, + VirtualRenderWaveProps, +} from "../src/types"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. Copied from +// VirtualRenderWave.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +/** + * Markup of the very first render, before any effect has run. React 18 warns + * about useLayoutEffect whenever renderToString runs in jsdom, which is noise + * here rather than a finding, so it is swallowed. + */ +const firstRenderMarkup = (element: ReactElement) => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + return renderToString(element); + } finally { + errors.mockRestore(); + } +}; + +type ListProps = Partial> & { + ref?: Ref; +}; + +const list = (props: ListProps = {}) => ( +
{item}
} + {...props} + /> +); + +describe("VirtualRenderWave scroll options", () => { + it("opens at initialScrollOffset, from the very first render", () => { + // The window is derived from the offset during render, so the server + // markup and the first paint already show it: no jump after mount. + const markup = firstRenderMarkup(list({ initialScrollOffset: 2000 })); + expect(markup).toContain("Item 50"); + expect(markup).not.toContain(">Item 0<"); + + const { container } = render(list({ initialScrollOffset: 2000 })); + const outer = container.firstElementChild as HTMLElement; + expect(outer.scrollTop).toBe(2000); + expect(screen.getByText("Item 50")).toBeTruthy(); + expect(screen.queryByText("Item 0")).toBeNull(); + }); + + it("opens at initialScrollIndex, from the very first render", () => { + const markup = firstRenderMarkup(list({ initialScrollIndex: 50 })); + expect(markup).toContain("Item 50"); + expect(markup).not.toContain(">Item 0<"); + + const { container } = render(list({ initialScrollIndex: 50 })); + const outer = container.firstElementChild as HTMLElement; + expect(outer.scrollTop).toBe(2000); + expect(screen.queryByText("Item 0")).toBeNull(); + }); + + it("renders the target window on the first render of a controlled scrollToIndex", () => { + const markup = firstRenderMarkup(list({ scrollToIndex: 50 })); + expect(markup).toContain("Item 50"); + expect(markup).not.toContain(">Item 0<"); + + const { container } = render(list({ scrollToIndex: 50 })); + const outer = container.firstElementChild as HTMLElement; + expect(outer.scrollTop).toBe(2000); + }); + + it("reports the rendered and visible range through onRangeChange", () => { + const onRangeChange = vi.fn(); + const { container } = render(list({ onRangeChange })); + const outer = container.firstElementChild as HTMLElement; + + expect(onRangeChange).toHaveBeenCalledTimes(1); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 0, + end: 15, + visibleStart: 0, + visibleEnd: 10, + }); + + scrollTo(outer, 4000); + expect(onRangeChange).toHaveBeenCalledTimes(2); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 95, + end: 115, + visibleStart: 100, + visibleEnd: 110, + }); + }); + + it("takes an alignment or a behavior string on handle.scrollTo", () => { + const ref = createRef(); + const { container } = render(list({ ref })); + const outer = container.firstElementChild as HTMLElement; + + act(() => { + ref.current?.scrollTo(50, { align: "end", behavior: "auto" }); + }); + expect(outer.scrollTop).toBe(1640); + + act(() => { + ref.current?.scrollTo(50, "auto"); + }); + expect(outer.scrollTop).toBe(2000); + + act(() => { + ref.current?.scrollTo(0, "auto"); + }); + expect(outer.scrollTop).toBe(0); + + // The default is align "start" with a smooth scroll; the jsdom scrollTo + // stub applies it instantly. + act(() => { + ref.current?.scrollTo(50); + }); + expect(outer.scrollTop).toBe(2000); + }); +}); diff --git a/test/endReached.test.tsx b/test/endReached.test.tsx new file mode 100644 index 0000000..3ccbf8a --- /dev/null +++ b/test/endReached.test.tsx @@ -0,0 +1,145 @@ +import { act, render } from "@testing-library/react"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +const flush = () => { + act(() => { + vi.advanceTimersByTime(20); + }); +}; + +const props = (count: number, onEndReached: () => void) => ({ + items: items(count), + itemHeight: 40, + containerHeight: 400, + batchSize: 100, + onEndReached, + renderItem: (item: string) =>
{item}
, +}); + +describe("onEndReached", () => { + it("fires on mount when the content is shorter than the viewport", () => { + const onEndReached = vi.fn(); + // 5 rows of 40px never fill a 400px viewport, so no scroll event is ever + // dispatched to report the end. + render(); + flush(); + expect(onEndReached).toHaveBeenCalledTimes(1); + }); + + it("fires again when a page arrives that still leaves the list short", () => { + const onEndReached = vi.fn(); + const { rerender } = render( + + ); + flush(); + expect(onEndReached).toHaveBeenCalledTimes(1); + + rerender(); + flush(); + expect(onEndReached).toHaveBeenCalledTimes(2); + }); + + it("does not fire again when the item count is unchanged", () => { + const onEndReached = vi.fn(); + const { rerender } = render( + + ); + flush(); + expect(onEndReached).toHaveBeenCalledTimes(1); + + rerender(); + flush(); + expect(onEndReached).toHaveBeenCalledTimes(1); + }); + + it("does not fire on mount when the content overflows the viewport", () => { + const onEndReached = vi.fn(); + render(); + flush(); + expect(onEndReached).not.toHaveBeenCalled(); + }); + + it("honours endReachedThreshold", () => { + const onEndReached = vi.fn(); + const { container } = render( + + ); + const outer = container.firstElementChild as HTMLElement; + + // 3400 + 400 is 100px short of the 3900px trigger point. + scrollTo(outer, 3400); + expect(onEndReached).not.toHaveBeenCalled(); + + scrollTo(outer, 3550); + expect(onEndReached).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/regressions310.test.tsx b/test/regressions310.test.tsx new file mode 100644 index 0000000..a461098 --- /dev/null +++ b/test/regressions310.test.tsx @@ -0,0 +1,441 @@ +import { act, fireEvent, render } from "@testing-library/react"; +import { StrictMode, forwardRef } from "react"; +import { renderToString } from "react-dom/server"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import { useVirtualWindow } from "../src/useVirtualWindow"; +import type { + UseVirtualWindowOptions, + UseVirtualWindowResult, +} from "../src/useVirtualWindow"; +import type { WrapperProps } from "../src/types"; +import { MockResizeObserver } from "./setup"; + +// jsdom performs no layout, so heights come from inline styles. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +type HookRef = { current: UseVirtualWindowResult | null }; + +interface HarnessProps extends Omit { + count: number; + height?: number; + hookRef?: HookRef; +} + +function rows(v: UseVirtualWindowResult) { + return v.virtualItems.map((it) => ( +
+ Item {it.index} +
+ )); +} + +function Harness({ height = 400, hookRef, ...options }: HarnessProps) { + const v = useVirtualWindow(options); + if (hookRef) hookRef.current = v; + return ( +
+
{rows(v)}
+
+ ); +} + +const stubHeight = (el: Element, value: number) => { + Object.defineProperty(el, "offsetHeight", { configurable: true, value }); +}; + +const rowObserver = () => + MockResizeObserver.instances.find((ro) => + Array.from(ro.observed).some((el) => el.getAttribute("role") === "listitem") + ); + +describe("react-render-wave 3.1.0 regression tests", () => { + describe("a wrapper that swallows the ref", () => { + const RefLosingSection = forwardRef( + function RefLosingSection({ children, ...rest }, _ref) { + return
{children}
; + } + ); + + const REF_LOST_MESSAGE = + "react-render-wave: outerElement did not attach the ref it received, so " + + "the list cannot scroll or measure. On React 18 wrap the component in " + + "forwardRef and pass the ref to your DOM node."; + + it("reports a ref-swallowing outerElement once even under StrictMode", () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + render( + +
{item}
} + /> +
+ ); + + const ours = errors.mock.calls.filter((call) => + String(call[0]).includes("outerElement did not attach the ref") + ); + expect(ours).toHaveLength(1); + expect(ours[0][0]).toBe(REF_LOST_MESSAGE); + } finally { + errors.mockRestore(); + } + }); + }); + + it("initialScrollIndex's first render already includes scrollMargin in its window", () => { + const onRangeChange = vi.fn(); + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + // The very first render (what renderToString would emit, and what paints + // before the client-only attach effect corrects it) should already window + // around index 100, not 80. + expect(hookRef.current?.start).toBe(95); + expect(hookRef.current?.end).toBe(115); + expect(hookRef.current?.visibleStart).toBe(100); + expect(hookRef.current?.visibleEnd).toBe(110); + expect(hookRef.current?.scrollOffset).toBe(4600); + expect(scroller.scrollTop).toBe(4600); + expect(onRangeChange).toHaveBeenCalledTimes(1); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 95, + end: 115, + visibleStart: 100, + visibleEnd: 110, + }); + }); + + it("scrollToIndex near the end of the list lands on the target item", () => { + const hookRef: HookRef = { current: null }; + const props = { + count: 100, + estimateSize: 50, + overscan: 5, + measureSize: () => 100, + hookRef, + }; + const { container, rerender } = render(); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(99, { align: "start" })); + act(() => { + rerender(); + }); + act(() => { + rerender(); + }); + + // Item 99 (100px tall, 100 rows measured at 100px = totalSize 10000) + // must be inside the [scrollTop, scrollTop+400) viewport, not stopped + // short of it. + const totalSize = hookRef.current?.totalSize ?? 0; + const offsetOf99 = hookRef.current?.offsetOf(99) ?? 0; + const sizeOf99 = hookRef.current?.sizeOf(99) ?? 0; + expect(scroller.scrollTop + 400).toBeGreaterThanOrEqual( + offsetOf99 + sizeOf99 + ); + expect(hookRef.current?.visibleEnd).toBe(100); + expect(scroller.scrollTop).toBe(totalSize - 400); + }); + + it("align auto settles once on an item taller than the viewport", () => { + const hookRef: HookRef = { current: null }; + const props = { + count: 20, + estimateSize: 50, + overscan: 2, + measureSize: (el: HTMLElement) => + el.getAttribute("data-index") === "3" ? 800 : 0, + hookRef, + }; + const { container } = render(); + const scroller = container.firstElementChild as HTMLElement; + + // Let the commit pass measure row 3 as 800px tall. + expect(hookRef.current?.sizeOf(3)).toBe(800); + expect(hookRef.current?.offsetOf(3)).toBe(150); + + act(() => hookRef.current?.scrollToIndex(3, { align: "auto" })); + const firstStop = scroller.scrollTop; + expect(firstStop).toBe(150); + + // A second identical call must be a no-op: the item already fills the + // viewport, so "auto" should not oscillate. + act(() => hookRef.current?.scrollToIndex(3, { align: "auto" })); + expect(scroller.scrollTop).toBe(firstStop); + }); + + it("keyboard navigation leaves a focused input's own key handling alone", () => { + const { container } = render( + } + /> + ); + const outer = container.firstElementChild as HTMLElement; + scrollTo(outer, 400); + expect(outer.scrollTop).toBe(400); + + const input = container.querySelector("input") as HTMLInputElement; + expect(input).toBeTruthy(); + input.focus(); + + const notPrevented = fireEvent.keyDown(input, { key: "Home" }); + expect(notPrevented).toBe(true); + // The list must not have hijacked the key: scroll position is unchanged. + expect(outer.scrollTop).toBe(400); + + // The container itself keeps working as before. + const stillPrevented = fireEvent.keyDown(outer, { key: "Home" }); + expect(stillPrevented).toBe(false); + expect(outer.scrollTop).toBe(0); + }); + + it("the injected fade-in keyframes are scoped to prefers-reduced-motion: no-preference", () => { + render( +
{item}
} + /> + ); + + const style = document.head.querySelector("style[data-react-render-wave]"); + expect(style).toBeTruthy(); + expect(style?.textContent).toContain("prefers-reduced-motion"); + expect(style?.textContent).toContain("@keyframes rrw-fade-in"); + }); + + it("a zero estimateSize does not disable virtualization", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + + const rendered = container.querySelectorAll('[role="listitem"]').length; + // With a sane estimate the window renders a couple dozen rows at most. + // A zero estimate must not make every row mount. + expect(rendered).toBeLessThan(1000); + }); + + it("a negative overscan does not collapse the range to empty", () => { + const hookRef: HookRef = { current: null }; + render( + + ); + + expect(hookRef.current?.end).toBeGreaterThanOrEqual( + hookRef.current?.start ?? 0 + ); + expect(hookRef.current?.virtualItems.length ?? 0).toBeGreaterThan(0); + }); + + it("scrollToIndex(NaN) leaves the current scroll position alone", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(30)); + expect(scroller.scrollTop).toBe(1200); + + act(() => hookRef.current?.scrollToIndex(Number.NaN)); + + expect(scroller.scrollTop).toBe(1200); + }); + + // ---- D1/D2: a non-finite or negative initialScrollOffset must not seed a + // non-finite or negative first-render scrollOffset. renderToString is used + // rather than @testing-library/react's render, because the mount effect + // that attaches the scroll listener also reads the DOM's own scrollTop + // back into state; on the very next commit that overwrites the seeded + // value with 0 regardless of whether the seed itself was clamped, hiding + // the bug renderToString's effect-free first render still exposes (the + // same first render server markup would emit, per C3 above). + + it("a NaN initialScrollOffset renders the same first window as no initial offset at all, and scrollOffset is 0 not NaN", () => { + const withNaNRef: HookRef = { current: null }; + renderToString( + + ); + + const withoutRef: HookRef = { current: null }; + renderToString( + + ); + + // scrollOffset must land on the finite fallback, not carry NaN through. + expect(withNaNRef.current?.scrollOffset).toBe(0); + expect(Number.isNaN(withNaNRef.current?.scrollOffset)).toBe(false); + + // The first window (rows from index 0) must match the no-offset case. + expect(withNaNRef.current?.start).toBe(withoutRef.current?.start); + expect(withNaNRef.current?.end).toBe(withoutRef.current?.end); + expect(withNaNRef.current?.visibleStart).toBe(0); + expect(withNaNRef.current?.visibleStart).toBe( + withoutRef.current?.visibleStart + ); + }); + + it("a negative initialScrollOffset clamps scrollOffset to 0 on the first render", () => { + const hookRef: HookRef = { current: null }; + renderToString( + + ); + + expect(hookRef.current?.scrollOffset).toBe(0); + expect(hookRef.current?.start).toBe(0); + expect(hookRef.current?.visibleStart).toBe(0); + }); + + // ---- C2 (coverage): StrictMode remount must not orphan the ResizeObserver + + it("a StrictMode remount keeps every attached row under live observation", () => { + const hookRef: HookRef = { current: null }; + render( + + + + ); + + const observer = rowObserver(); + expect(observer).toBeDefined(); + + // Every row element currently in the DOM must be observed by the live + // instance, not just the one StrictMode's simulated first mount created + // and then disconnected. + const rowEls = Array.from(document.querySelectorAll('[role="listitem"]')); + expect(rowEls.length).toBeGreaterThan(0); + for (const el of rowEls) { + expect(observer?.observed.has(el)).toBe(true); + } + + // And the observer actually delivers: triggering a size change on a row + // measures it, with no rerender in between to hide a broken hookup. + stubHeight(rowEls[0] as HTMLElement, 123); + act(() => { + observer?.trigger([rowEls[0] as HTMLElement]); + }); + expect(hookRef.current?.sizeOf(0)).toBe(123); + }); +}); diff --git a/test/renderWaveOptions.test.tsx b/test/renderWaveOptions.test.tsx new file mode 100644 index 0000000..12a6f06 --- /dev/null +++ b/test/renderWaveOptions.test.tsx @@ -0,0 +1,113 @@ +import { act, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { RenderWave } from "../src/RenderWave"; + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const advanceWave = (ms = 100) => { + act(() => { + vi.advanceTimersByTime(ms); + }); +}; + +describe("RenderWave options (regression net for the windowing refactor)", () => { + it("pauses the reveal while disabled and resumes once enabled again", () => { + const list = Array.from({ length: 60 }, (_, i) => `Item ${i}`); + const { rerender } = render( +
{item}
} + /> + ); + + expect(screen.getAllByText(/^Item /)).toHaveLength(20); + advanceWave(200); + expect(screen.getAllByText(/^Item /)).toHaveLength(20); + + rerender( +
{item}
} + /> + ); + advanceWave(); + expect(screen.getAllByText(/^Item /)).toHaveLength(40); + }); + + it("reveals from startIndex in batches", () => { + const list = Array.from({ length: 10 }, (_, i) => `Item ${i}`); + render( +
{item}
} + /> + ); + + expect(screen.getByText("Item 4")).toBeTruthy(); + expect(screen.getByText("Item 5")).toBeTruthy(); + expect(screen.queryByText("Item 6")).toBeNull(); + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getAllByText(/^Item /)).toHaveLength(2); + + advanceWave(); + + expect(screen.getByText("Item 6")).toBeTruthy(); + expect(screen.getByText("Item 7")).toBeTruthy(); + expect(screen.queryByText("Item 8")).toBeNull(); + expect(screen.getAllByText(/^Item /)).toHaveLength(4); + }); + + it("never calls renderItem with an out-of-range item when items shrink mid-reveal", () => { + const big = Array.from({ length: 60 }, (_, i) => `Item ${i}`); + const renderItem = vi.fn((item: string, i: number) => ( +
{item}
+ )); + const { rerender } = render( + + ); + advanceWave(); + renderItem.mockClear(); + + const small = Array.from({ length: 10 }, (_, i) => `Item ${i}`); + rerender( + + ); + + expect(renderItem.mock.calls.length).toBeGreaterThan(0); + for (const call of renderItem.mock.calls) { + expect(call[0]).toBeDefined(); + } + }); +}); diff --git a/test/revealMode.test.tsx b/test/revealMode.test.tsx new file mode 100644 index 0000000..f9fff9f --- /dev/null +++ b/test/revealMode.test.tsx @@ -0,0 +1,186 @@ +import { act, render, screen } from "@testing-library/react"; +import { createRef, type Ref } from "react"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import type { + VirtualRenderWaveHandle, + VirtualRenderWaveProps, +} from "../src/types"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. Copied from +// VirtualRenderWave.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +/** Interval 50 plus the frame the wave is committed on. */ +const wave = () => { + act(() => { + vi.advanceTimersByTime(100); + }); +}; + +const shown = (index: number) => screen.queryByText(`Item ${index}`) !== null; +const skeleton = (index: number) => + screen.queryByText(`Skeleton ${index}`) !== null; + +type ListProps = Partial> & { + ref?: Ref; +}; + +const list = (props: ListProps = {}) => ( +
{item}
} + renderSkeleton={(i) =>
Skeleton {i}
} + {...props} + /> +); + +describe("revealMode", () => { + it("reveals the rendered window in batches and never re-hides a row", () => { + const ref = createRef(); + const { container } = render(list({ revealMode: "viewport", ref })); + const outer = container.firstElementChild as HTMLElement; + + // The first batch of the window is revealed during the first render. + expect(shown(4)).toBe(true); + expect(shown(5)).toBe(false); + expect(skeleton(5)).toBe(true); + expect(skeleton(14)).toBe(true); + + wave(); + expect(shown(9)).toBe(true); + expect(shown(10)).toBe(false); + + // A jump to a part of the list nobody has seen: the new window starts as + // skeletons and is revealed by the waves that follow. + scrollTo(outer, 4000); + expect(shown(95)).toBe(false); + expect(shown(114)).toBe(false); + expect(skeleton(95)).toBe(true); + expect(skeleton(114)).toBe(true); + + wave(); + expect(shown(95)).toBe(true); + expect(shown(99)).toBe(true); + expect(shown(100)).toBe(false); + + // Back to the top: every row revealed on the way out is still revealed, + // so nothing the reader has already seen re-staggers. The rows that were + // never reached are picked up by the next wave. + scrollTo(outer, 0); + for (let i = 0; i < 10; i++) expect(shown(i)).toBe(true); + expect(shown(10)).toBe(false); + expect(ref.current?.getVisibleIndexes()).toEqual([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + ]); + + wave(); + for (let i = 0; i < 15; i++) expect(shown(i)).toBe(true); + expect(ref.current?.getVisibleIndexes()).toEqual( + Array.from({ length: 15 }, (_, i) => i) + ); + }); + + it("lists only the revealed rows of the window in getVisibleIndexes", () => { + const ref = createRef(); + render(list({ revealMode: "viewport", ref })); + + expect(ref.current?.getVisibleIndexes()).toEqual([0, 1, 2, 3, 4]); + + wave(); + expect(ref.current?.getVisibleIndexes()).toEqual([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + ]); + }); + + it("counts from startIndex regardless of the scroll position by default", () => { + const ref = createRef(); + const { container } = render(list({ ref })); + const outer = container.firstElementChild as HTMLElement; + + expect(shown(4)).toBe(true); + expect(shown(5)).toBe(false); + + // The window moves, but the wave is still counting from the start of the + // list, so every row here is a skeleton. + scrollTo(outer, 4000); + expect(skeleton(95)).toBe(true); + expect(skeleton(114)).toBe(true); + expect(ref.current?.getVisibleIndexes()).toEqual([]); + + wave(); + expect(skeleton(95)).toBe(true); + + scrollTo(outer, 0); + expect(shown(0)).toBe(true); + expect(shown(9)).toBe(true); + expect(shown(10)).toBe(false); + }); +}); diff --git a/test/setup.ts b/test/setup.ts index 3fa272a..e91b4b3 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -53,17 +53,19 @@ afterEach(() => { MockResizeObserver.instances = []; }); -// jsdom does not implement scrollTo. The stub applies the offset and fires a -// scroll event, mirroring what a real browser does for instant scrolls. -Element.prototype.scrollTo = function scrollTo( - this: Element, - options?: ScrollToOptions | number, - y?: number -) { - const top = - typeof options === "object" && options !== null - ? options.top ?? this.scrollTop - : y ?? 0; - this.scrollTop = top; - this.dispatchEvent(new Event("scroll")); -} as Element["scrollTo"]; +// jsdom has no scrollTo. This stub applies the offset and fires a scroll event. +// The node environment used by the SSR suites has no Element at all, hence the guard. +if (typeof Element !== "undefined") { + Element.prototype.scrollTo = function scrollTo( + this: Element, + options?: ScrollToOptions | number, + y?: number + ) { + const top = + typeof options === "object" && options !== null + ? options.top ?? this.scrollTop + : y ?? 0; + this.scrollTop = top; + this.dispatchEvent(new Event("scroll")); + } as Element["scrollTo"]; +} diff --git a/test/sizeCache.test.ts b/test/sizeCache.test.ts new file mode 100644 index 0000000..ef3b179 --- /dev/null +++ b/test/sizeCache.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from "vitest"; +import { SizeCache } from "../src/sizeCache"; + +describe("SizeCache", () => { + it("computes offsets and total from the default size", () => { + const cache = new SizeCache(40); + cache.setCount(10); + expect(cache.offsetOf(0)).toBe(0); + expect(cache.offsetOf(3)).toBe(120); + expect(cache.totalSize()).toBe(400); + }); + + it("clamps offsetOf outside the range", () => { + const cache = new SizeCache(40); + cache.setCount(5); + expect(cache.offsetOf(-2)).toBe(0); + expect(cache.offsetOf(99)).toBe(200); + }); + + it("incorporates measurements into offsets", () => { + const cache = new SizeCache(40); + cache.setCount(10); + expect(cache.totalSize()).toBe(400); + + expect(cache.measure(2, 100)).toBe(true); + expect(cache.offsetOf(2)).toBe(80); + expect(cache.offsetOf(3)).toBe(180); + expect(cache.totalSize()).toBe(460); + }); + + it("reports unchanged measurements as no-ops", () => { + const cache = new SizeCache(40); + cache.setCount(10); + cache.measure(2, 100); + expect(cache.measure(2, 100)).toBe(false); + expect(cache.measure(-1, 100)).toBe(false); + expect(cache.measure(10, 100)).toBe(false); + }); + + it("finds the item at an offset with boundary offsets belonging to the next item", () => { + const cache = new SizeCache(40); + cache.setCount(100); + expect(cache.indexAt(-10)).toBe(0); + expect(cache.indexAt(0)).toBe(0); + expect(cache.indexAt(39)).toBe(0); + expect(cache.indexAt(40)).toBe(1); + expect(cache.indexAt(3999)).toBe(99); + expect(cache.indexAt(999999)).toBe(99); + }); + + it("hit tests correctly with mixed sizes", () => { + const cache = new SizeCache(40); + cache.setCount(5); + cache.measure(0, 10); + cache.measure(1, 200); + // Layout: [0..10) [10..210) [210..250) [250..290) [290..330) + expect(cache.indexAt(5)).toBe(0); + expect(cache.indexAt(10)).toBe(1); + expect(cache.indexAt(209)).toBe(1); + expect(cache.indexAt(210)).toBe(2); + expect(cache.totalSize()).toBe(330); + }); + + it("handles count changes in both directions", () => { + const cache = new SizeCache(40); + cache.setCount(10); + cache.measure(9, 100); + expect(cache.totalSize()).toBe(460); + + cache.setCount(4); + expect(cache.totalSize()).toBe(160); + + cache.setCount(12); + // The measurement for index 9 persists across the shrink and regrow. + expect(cache.totalSize()).toBe(40 * 11 + 100); + }); + + it("invalidates everything when the default size changes", () => { + const cache = new SizeCache(40); + cache.setCount(10); + cache.measure(0, 100); + expect(cache.totalSize()).toBe(460); + + cache.setDefaultSize(50); + expect(cache.totalSize()).toBe(100 + 9 * 50); + expect(cache.offsetOf(2)).toBe(150); + }); + + it("handles an empty list", () => { + const cache = new SizeCache(40); + expect(cache.totalSize()).toBe(0); + expect(cache.indexAt(100)).toBe(0); + expect(cache.offsetOf(0)).toBe(0); + }); + + it("carries keyed sizes along when the data is reordered", () => { + const cache = new SizeCache(40); + cache.setCount(3); + const first = ["a", "b", "c"]; + cache.setKeyFn((i) => first[i]); + expect(cache.keyOf(0)).toBe("a"); + expect(cache.measure(0, 100)).toBe(true); + expect(cache.totalSize()).toBe(180); + expect(cache.offsetOf(1)).toBe(100); + + const swapped = ["b", "a", "c"]; + cache.setKeyFn((i) => swapped[i]); + expect(cache.sizeOf(0)).toBe(40); + expect(cache.sizeOf(1)).toBe(100); + expect(cache.offsetOf(1)).toBe(40); + expect(cache.offsetOf(2)).toBe(140); + expect(cache.totalSize()).toBe(180); + }); + + it("drops measurements when the keying mode toggles", () => { + const cache = new SizeCache(40); + cache.setCount(3); + cache.measure(0, 100); + expect(cache.totalSize()).toBe(180); + + // Index keys and item keys share one map, so they never mix. + cache.setKeyFn((i) => ["a", "b", "c"][i]); + expect(cache.sizeOf(0)).toBe(40); + expect(cache.totalSize()).toBe(120); + + cache.measure(0, 100); + expect(cache.totalSize()).toBe(180); + cache.setKeyFn(undefined); + expect(cache.totalSize()).toBe(120); + }); + + it("keeps sizes when the key function identity changes but the mapping does not", () => { + const cache = new SizeCache(40); + cache.setCount(3); + const keys = ["a", "b", "c"]; + cache.setKeyFn((i) => keys[i]); + cache.measure(1, 90); + expect(cache.totalSize()).toBe(170); + + cache.setKeyFn((i) => keys[i]); + expect(cache.sizeOf(1)).toBe(90); + expect(cache.offsetOf(2)).toBe(130); + expect(cache.totalSize()).toBe(170); + }); + + it("records a measurement under a key snapshot taken before a move", () => { + const cache = new SizeCache(40); + cache.setCount(3); + let order = ["a", "b", "c"]; + cache.setKeyFn((i) => order[i]); + expect(cache.measureKey("a", 0, 100)).toBe(true); + expect(cache.measureKey("a", 0, 100)).toBe(false); + expect(cache.sizeOf(0)).toBe(100); + + order = ["b", "c", "a"]; + cache.setKeyFn((i) => order[i]); + expect(cache.sizeOf(2)).toBe(100); + + // A measurement in flight across the move still lands on its own item. + expect(cache.measureKey("a", 2, 120)).toBe(true); + expect(cache.sizeOf(2)).toBe(120); + expect(cache.totalSize()).toBe(200); + expect(cache.measureKey("a", 3, 130)).toBe(false); + }); +}); diff --git a/test/sizeCacheProperties.test.ts b/test/sizeCacheProperties.test.ts new file mode 100644 index 0000000..f37215f --- /dev/null +++ b/test/sizeCacheProperties.test.ts @@ -0,0 +1,300 @@ +import { describe, expect, it } from "vitest"; +import { SizeCache } from "../src/sizeCache"; + +// A small deterministic seeded PRNG (mulberry32), so failures reproduce. +function mulberry32(seed: number): () => number { + let state = seed | 0; + return () => { + state = (state + 0x6d2b79f5) | 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function randInt(rng: () => number, min: number, max: number): number { + return min + Math.floor(rng() * (max - min + 1)); +} + +function shuffle(rng: () => number, arr: T[]): T[] { + const copy = arr.slice(); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + [copy[i], copy[j]] = [copy[j], copy[i]]; + } + return copy; +} + +/** Brute force prefix sums (length count + 1, offsets[0] = 0) for a sizes array. */ +function bruteOffsets(sizes: number[]): number[] { + const offsets = [0]; + for (let i = 0; i < sizes.length; i++) offsets.push(offsets[i] + sizes[i]); + return offsets; +} + +/** + * The last index in [0, count - 1] whose offset <= x, following the same + * boundary rules as SizeCache#indexAt. + */ +function bruteIndexAt(offsets: number[], count: number, x: number): number { + if (count === 0) return 0; + if (x <= 0) return 0; + let best = 0; + for (let i = 0; i < count; i++) { + if (offsets[i] <= x) best = i; + else break; + } + return Math.min(best, count - 1); +} + +describe("SizeCache properties", () => { + it("matches a brute force prefix sum and hit test across 200 random scenarios", () => { + const rng = mulberry32(1); + for (let scenario = 0; scenario < 200; scenario++) { + const count = randInt(rng, 0, 300); + const defaultSize = randInt(rng, 1, 100); + const cache = new SizeCache(defaultSize); + cache.setCount(count); + + const sizes = new Array(count).fill(defaultSize); + const order = shuffle( + rng, + Array.from({ length: count }, (_, i) => i) + ); + const measureCount = randInt(rng, 0, count); + for (let k = 0; k < measureCount; k++) { + const index = order[k]; + const size = randInt(rng, 1, 200); + sizes[index] = size; + cache.measure(index, size); + } + + const offsets = bruteOffsets(sizes); + for (let i = 0; i <= count; i++) { + expect(cache.offsetOf(i)).toBe(offsets[i]); + } + expect(cache.totalSize()).toBe(cache.offsetOf(count)); + expect(cache.totalSize()).toBe(offsets[count]); + + const total = offsets[count]; + for (let q = 0; q < 50; q++) { + const x = randInt(rng, -10, total + 10); + expect(cache.indexAt(x)).toBe(bruteIndexAt(offsets, count, x)); + } + } + }); + + it("gives the same answers whether measurements are interleaved with queries or not", () => { + const rng = mulberry32(2); + for (let scenario = 0; scenario < 100; scenario++) { + const count = randInt(rng, 1, 100); + const defaultSize = randInt(rng, 1, 80); + const cache = new SizeCache(defaultSize); + cache.setCount(count); + + const finalSizes = new Array(count).fill(defaultSize); + + const applyRandomMeasurements = () => { + const batch = randInt(rng, 0, count); + for (let k = 0; k < batch; k++) { + const index = randInt(rng, 0, count - 1); + const size = randInt(rng, 1, 150); + finalSizes[index] = size; + cache.measure(index, size); + } + }; + + applyRandomMeasurements(); + // Interleave some queries that force a partial rebuild. + for (let q = 0; q < 5; q++) { + cache.offsetOf(randInt(rng, 0, count)); + cache.indexAt(randInt(rng, 0, defaultSize * count)); + } + applyRandomMeasurements(); + for (let q = 0; q < 5; q++) { + cache.offsetOf(randInt(rng, 0, count)); + } + + const fresh = new SizeCache(defaultSize); + fresh.setCount(count); + for (let i = 0; i < count; i++) fresh.measure(i, finalSizes[i]); + + for (let i = 0; i <= count; i++) { + expect(cache.offsetOf(i)).toBe(fresh.offsetOf(i)); + } + expect(cache.totalSize()).toBe(fresh.totalSize()); + + const total = fresh.totalSize(); + for (let q = 0; q < 20; q++) { + const x = randInt(rng, -10, total + 10); + expect(cache.indexAt(x)).toBe(fresh.indexAt(x)); + } + } + }); + + it("drops offsets beyond a shrunk count and restores measured sizes on regrow", () => { + const rng = mulberry32(3); + for (let scenario = 0; scenario < 30; scenario++) { + const defaultSize = randInt(rng, 1, 60); + const cache = new SizeCache(defaultSize); + let count = 0; + const measured = new Map(); + + const bruteTotal = () => { + let total = 0; + for (let i = 0; i < count; i++) total += measured.get(i) ?? defaultSize; + return total; + }; + + const steps = randInt(rng, 5, 15); + for (let s = 0; s < steps; s++) { + if (rng() < 0.4) { + count = randInt(rng, 0, 50); + cache.setCount(count); + } else if (count > 0) { + const index = randInt(rng, 0, count - 1); + const size = randInt(rng, 1, 200); + measured.set(index, size); + cache.measure(index, size); + } + expect(cache.totalSize()).toBe(bruteTotal()); + expect(cache.offsetOf(count)).toBe(bruteTotal()); + } + } + }); + + it("keeps a measurement made before a shrink and restores it after a regrow", () => { + const cache = new SizeCache(40); + cache.setCount(10); + cache.measure(7, 300); + expect(cache.totalSize()).toBe(9 * 40 + 300); + + cache.setCount(3); // index 7 no longer exists + expect(cache.totalSize()).toBe(3 * 40); + + cache.setCount(8); // index 7 exists again, with its old measurement + expect(cache.totalSize()).toBe(7 * 40 + 300); + }); + + it("gives a keyed cache the same offsets as a fresh cache fed the permuted sizes directly", () => { + const rng = mulberry32(4); + for (let scenario = 0; scenario < 50; scenario++) { + const n = randInt(rng, 1, 40); + const defaultSize = randInt(rng, 1, 50); + const keys = Array.from({ length: n }, (_, i) => `k${i}`); + const sizeByKey = new Map(); + for (const key of keys) sizeByKey.set(key, randInt(rng, 1, 200)); + + const order1 = shuffle(rng, keys); + const cache = new SizeCache(defaultSize); + cache.setCount(n); + cache.setKeyFn((i) => order1[i]); + for (let i = 0; i < n; i++) { + cache.measure(i, sizeByKey.get(order1[i])!); + } + + const order2 = shuffle(rng, keys); + cache.setKeyFn((i) => order2[i]); + + const fresh = new SizeCache(defaultSize); + fresh.setCount(n); + const permutedSizes = order2.map((key) => sizeByKey.get(key)!); + for (let i = 0; i < n; i++) fresh.measure(i, permutedSizes[i]); + + for (let i = 0; i <= n; i++) { + expect(cache.offsetOf(i)).toBe(fresh.offsetOf(i)); + } + expect(cache.totalSize()).toBe(fresh.totalSize()); + } + }); + + it("clears measurements on a keyed to unkeyed mode toggle, returning offsets to multiples of the default size", () => { + const rng = mulberry32(5); + for (let scenario = 0; scenario < 30; scenario++) { + const count = randInt(rng, 1, 40); + const defaultSize = randInt(rng, 1, 50); + const cache = new SizeCache(defaultSize); + cache.setCount(count); + + // Measure a random subset while unkeyed. + for (let i = 0; i < count; i++) { + if (rng() < 0.5) cache.measure(i, randInt(rng, 1, 150)); + } + + // Switching to keyed mode drops the unkeyed measurements. + cache.setKeyFn((i) => `k${i}`); + expect(cache.totalSize()).toBe(count * defaultSize); + + // Measure a random subset while keyed. + for (let i = 0; i < count; i++) { + if (rng() < 0.5) cache.measure(i, randInt(rng, 1, 150)); + } + + // Switching back to unkeyed drops the keyed measurements too. + cache.setKeyFn(undefined); + expect(cache.totalSize()).toBe(count * defaultSize); + for (let i = 0; i < count; i++) { + expect(cache.offsetOf(i)).toBe(i * defaultSize); + } + } + }); + + it("changes only the contribution of unmeasured items when the default size changes", () => { + const rng = mulberry32(6); + for (let scenario = 0; scenario < 30; scenario++) { + const count = randInt(rng, 1, 60); + const oldDefault = randInt(rng, 1, 50); + const cache = new SizeCache(oldDefault); + cache.setCount(count); + + const measured = new Map(); + for (let i = 0; i < count; i++) { + if (rng() < 0.4) { + const size = randInt(rng, 1, 200); + measured.set(i, size); + cache.measure(i, size); + } + } + + const newDefault = randInt(rng, 1, 50); + cache.setDefaultSize(newDefault); + + const expectedSizes = Array.from( + { length: count }, + (_, i) => measured.get(i) ?? newDefault + ); + const expectedOffsets = bruteOffsets(expectedSizes); + for (let i = 0; i <= count; i++) { + expect(cache.offsetOf(i)).toBe(expectedOffsets[i]); + } + } + }); + + it("returns true from measure only when the value actually changes", () => { + const cache = new SizeCache(40); + cache.setCount(5); + expect(cache.measure(2, 100)).toBe(true); + expect(cache.measure(2, 100)).toBe(false); + expect(cache.measure(2, 101)).toBe(true); + expect(cache.measure(2, 101)).toBe(false); + }); + + it("returns false from measureKey for an index outside the current count and stores nothing", () => { + const cache = new SizeCache(40); + cache.setCount(3); + + expect(cache.measureKey("ghost", -1, 999)).toBe(false); + expect(cache.measureKey("ghost", 5, 999)).toBe(false); + + // Nothing was stored under "ghost": once an index maps onto that key, + // its size is still the default rather than the rejected value. + cache.setKeyFn((i) => (i === 0 ? "ghost" : `other${i}`)); + expect(cache.sizeOf(0)).toBe(40); + + // Growing the count to include index 5 does not surface the rejected + // measurement either. + cache.setCount(6); + cache.setKeyFn((i) => (i === 5 ? "ghost" : `other${i}`)); + expect(cache.sizeOf(5)).toBe(40); + }); +}); diff --git a/test/ssr.test.tsx b/test/ssr.test.tsx new file mode 100644 index 0000000..7ff30e9 --- /dev/null +++ b/test/ssr.test.tsx @@ -0,0 +1,111 @@ +// @vitest-environment node +import { renderToString } from "react-dom/server"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { RenderWave } from "../src/RenderWave"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; + +// This whole file runs in the node test environment: window, document and +// Element are all undefined here, which is exactly the branch the library +// takes for real server rendering (it swaps useLayoutEffect for useEffect by +// checking typeof window). + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +let errorSpy: ReturnType; + +beforeEach(() => { + errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); +}); + +afterEach(() => { + errorSpy.mockRestore(); +}); + +describe("server rendering", () => { + it("RenderWave emits exactly the first batch and is deterministic across calls", () => { + const element = ( + ( + + {item} + + )} + /> + ); + + const first = renderToString(element); + const second = renderToString(element); + + const count = (first.match(/data-item="\d+"/g) ?? []).length; + expect(count).toBe(20); + expect(second).toBe(first); + }); + + it("VirtualRenderWave emits the visible window with the right total height and aria attributes, deterministically", () => { + const element = ( +
{item}
} + /> + ); + + const first = renderToString(element); + const second = renderToString(element); + + expect(first).toContain('role="list"'); + expect(first).toContain("height:40000px"); + + const listitems = first.match(/role="listitem"/g) ?? []; + expect(listitems).toHaveLength(15); + + const setsizes = first.match(/aria-setsize="1000"/g) ?? []; + expect(setsizes).toHaveLength(15); + + expect(second).toBe(first); + }); + + it("logs nothing through console.error while rendering either component on the server", () => { + renderToString( + {item}} + /> + ); + renderToString( +
{item}
} + /> + ); + + expect(errorSpy).not.toHaveBeenCalled(); + }); + + it("VirtualRenderWave with renderSkeleton splits the first window between revealed items and skeletons", () => { + const markup = renderToString( +
{item}
} + renderSkeleton={(i) =>
Skeleton {i}
} + /> + ); + + const revealedCount = (markup.match(/data-kind="item"/g) ?? []).length; + const skeletonCount = (markup.match(/data-kind="skeleton"/g) ?? []).length; + + expect(revealedCount).toBe(5); + expect(skeletonCount).toBe(10); + }); +}); diff --git a/test/useViewportReveal.test.tsx b/test/useViewportReveal.test.tsx new file mode 100644 index 0000000..12ad5b1 --- /dev/null +++ b/test/useViewportReveal.test.tsx @@ -0,0 +1,282 @@ +import { act, renderHook } from "@testing-library/react"; +import { StrictMode, type ReactNode } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + useViewportReveal, + type UseViewportRevealOptions, +} from "../src/useViewportReveal"; + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +/** Advances far enough for exactly one wave (interval 50 plus one frame). */ +const advanceWave = (ms = 100) => { + act(() => { + vi.advanceTimersByTime(ms); + }); +}; + +/** Indexes of [lo, hi) that the hook reports as revealed. */ +const revealedIn = ( + isRevealed: (index: number) => boolean, + lo: number, + hi: number +) => { + const out: number[] = []; + for (let i = lo; i < hi; i++) if (isRevealed(i)) out.push(i); + return out; +}; + +const range = (lo: number, hi: number) => + Array.from({ length: hi - lo }, (_, i) => lo + i); + +describe("useViewportReveal", () => { + it("reveals the first batch of the window during the first render", () => { + const { result } = renderHook(() => + useViewportReveal({ count: 1000, start: 0, end: 15, batchSize: 5 }) + ); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + expect(result.current.pendingCount).toBe(10); + }); + + it("reveals one batch per wave until the window is full", () => { + const { result } = renderHook(() => + useViewportReveal({ + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }) + ); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 10)); + expect(result.current.pendingCount).toBe(5); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 15)); + expect(result.current.pendingCount).toBe(0); + + // Nothing left to reveal in this window, so nothing stays armed. + expect(vi.getTimerCount()).toBe(0); + }); + + it("keeps rows revealed when the window moves and picks up the new ones", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }, + } + ); + advanceWave(); + advanceWave(); + expect(result.current.pendingCount).toBe(0); + + rerender({ count: 1000, start: 100, end: 115, batchSize: 5, interval: 50 }); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 15)); + expect(result.current.pendingCount).toBe(15); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 100, 115)).toEqual( + range(100, 105) + ); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 15)); + }); + + it("does not restart the pending wave when the window moves", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }, + } + ); + + advanceWave(30); + rerender({ count: 1000, start: 100, end: 115, batchSize: 5, interval: 50 }); + expect(result.current.isRevealed(100)).toBe(false); + + // 70ms in total: past the wave armed on the first render, well short of + // the 80ms a wave re-armed by the move would have taken. + advanceWave(40); + expect(revealedIn(result.current.isRevealed, 100, 115)).toEqual( + range(100, 105) + ); + }); + + it("tracks revealed rows by key when getItemKey is given", () => { + const order = ["a", "b", "c", "d", "e", "f"]; + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 6, + start: 0, + end: 6, + batchSize: 2, + getItemKey: (index: number) => order[index], + }, + } + ); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1]); + + // The list is reversed: "a" and "b" now sit at the end of it. + const reversed = [...order].reverse(); + rerender({ + count: 6, + start: 0, + end: 6, + batchSize: 2, + getItemKey: (index: number) => reversed[index], + }); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([4, 5]); + expect(result.current.pendingCount).toBe(4); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1, 4, 5]); + }); + + it("never reveals rows below startIndex", () => { + const { result } = renderHook(() => + useViewportReveal({ + count: 100, + start: 0, + end: 15, + batchSize: 5, + startIndex: 5, + }) + ); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(5, 10)); + expect(result.current.pendingCount).toBe(5); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(5, 15)); + expect(result.current.pendingCount).toBe(0); + }); + + it("pauses while enabled is false and resumes without losing state", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + enabled: false, + }, + } + ); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + advanceWave(); + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + expect(vi.getTimerCount()).toBe(0); + + rerender({ count: 1000, start: 0, end: 15, batchSize: 5, enabled: true }); + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 10)); + }); + + it("re-primes the first batch after reset", () => { + const { result } = renderHook(() => + useViewportReveal({ count: 1000, start: 0, end: 15, batchSize: 5 }) + ); + advanceWave(); + advanceWave(); + expect(result.current.pendingCount).toBe(0); + + act(() => { + result.current.reset(); + }); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + expect(result.current.pendingCount).toBe(10); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 10)); + }); + + it("primes the first batch when the data arrives after the first render", () => { + // The list renders empty while its data is in flight. Priming only on the + // first render would prime nothing, and the rows that do arrive would sit + // blank for a whole interval. + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { initialProps: { count: 0, start: 0, end: 0, batchSize: 5 } } + ); + expect(result.current.pendingCount).toBe(0); + + rerender({ count: 100, start: 0, end: 15, batchSize: 5 }); + + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + expect(result.current.pendingCount).toBe(10); + }); + + it("reveals a window shorter than one batch in full on the first render", () => { + const { result } = renderHook(() => + useViewportReveal({ count: 3, start: 0, end: 3, batchSize: 5 }) + ); + expect(revealedIn(result.current.isRevealed, 0, 3)).toEqual([0, 1, 2]); + expect(result.current.pendingCount).toBe(0); + expect(vi.getTimerCount()).toBe(0); + }); + + it("schedules nothing for an empty list", () => { + const { result } = renderHook(() => + useViewportReveal({ count: 0, start: 0, end: 0 }) + ); + expect(result.current.pendingCount).toBe(0); + expect(result.current.isRevealed(0)).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it("reveals one batch, not two, under StrictMode", () => { + const { result } = renderHook( + () => useViewportReveal({ count: 1000, start: 0, end: 15, batchSize: 5 }), + { + wrapper: ({ children }: { children: ReactNode }) => ( + {children} + ), + } + ); + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + expect(result.current.pendingCount).toBe(10); + }); + + it("keeps isRevealed and reset referentially stable", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { initialProps: { count: 1000, start: 0, end: 15, batchSize: 5 } } + ); + const { isRevealed, reset } = result.current; + + rerender({ count: 1000, start: 10, end: 25, batchSize: 5 }); + advanceWave(); + expect(result.current.isRevealed).toBe(isRevealed); + expect(result.current.reset).toBe(reset); + }); +}); diff --git a/test/useViewportRevealEdges.test.tsx b/test/useViewportRevealEdges.test.tsx new file mode 100644 index 0000000..09485bd --- /dev/null +++ b/test/useViewportRevealEdges.test.tsx @@ -0,0 +1,289 @@ +import { act, renderHook } from "@testing-library/react"; +import { StrictMode } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + useViewportReveal, + type UseViewportRevealOptions, +} from "../src/useViewportReveal"; + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +/** Advances far enough for exactly one wave (interval 50 plus one frame). */ +const advanceWave = (ms = 100) => { + act(() => { + vi.advanceTimersByTime(ms); + }); +}; + +/** Indexes of [lo, hi) that the hook reports as revealed. */ +const revealedIn = ( + isRevealed: (index: number) => boolean, + lo: number, + hi: number +) => { + const out: number[] = []; + for (let i = lo; i < hi; i++) if (isRevealed(i)) out.push(i); + return out; +}; + +const range = (lo: number, hi: number) => + Array.from({ length: hi - lo }, (_, i) => lo + i); + +describe("useViewportReveal edge cases", () => { + it("reveals only rows inside a window that shrank before the wave fired", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }, + } + ); + // First render primes 0..4 synchronously. + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 5)); + + // The window shrinks to [0, 8) before the wave has had a chance to fire. + rerender({ count: 1000, start: 0, end: 8, batchSize: 5, interval: 50 }); + expect(result.current.pendingCount).toBe(3); + + advanceWave(); + + // Only rows inside the shrunk window (5, 6, 7) are picked up: nothing + // beyond index 8 is ever touched. + expect(revealedIn(result.current.isRevealed, 0, 15)).toEqual(range(0, 8)); + expect(result.current.pendingCount).toBe(0); + }); + + it("floors a fractional batchSize and clamps a zero or negative one to 1 per wave", () => { + const zero = renderHook(() => + useViewportReveal({ count: 100, start: 0, end: 50, batchSize: 0 }) + ); + expect(revealedIn(zero.result.current.isRevealed, 0, 50)).toEqual([0]); + + const negative = renderHook(() => + useViewportReveal({ count: 100, start: 0, end: 50, batchSize: -3 }) + ); + expect(revealedIn(negative.result.current.isRevealed, 0, 50)).toEqual([0]); + + const fractional = renderHook(() => + useViewportReveal({ count: 100, start: 0, end: 50, batchSize: 2.9 }) + ); + expect(revealedIn(fractional.result.current.isRevealed, 0, 50)).toEqual([ + 0, 1, + ]); + }); + + it("re-arms with the new interval when interval changes mid-wave", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }, + } + ); + expect(result.current.pendingCount).toBe(10); + + // 30ms into a 50ms wave, the interval changes: the pending timer is torn + // down and a fresh 200ms one takes its place. + advanceWave(30); + rerender({ count: 1000, start: 0, end: 15, batchSize: 5, interval: 200 }); + expect(result.current.pendingCount).toBe(10); + + // Well short of the new 200ms interval: nothing revealed yet. + advanceWave(150); + expect(result.current.pendingCount).toBe(10); + + // Past 200ms plus a frame from the rerender: the wave has now fired. + advanceWave(80); + expect(result.current.pendingCount).toBe(5); + }); + + it("clears revealed state and re-primes synchronously when getItemKey toggles to undefined and back", () => { + const order = ["a", "b", "c", "d", "e", "f"]; + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 6, + start: 0, + end: 6, + batchSize: 2, + getItemKey: (index: number) => order[index], + } as UseViewportRevealOptions, + } + ); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1]); + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1, 2, 3]); + + // Switch to index-based tracking: the keyed set is discarded and the + // first batch is re-primed against plain indexes. + rerender({ count: 6, start: 0, end: 6, batchSize: 2 }); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1]); + expect(result.current.pendingCount).toBe(4); + + // Switching back to keyed tracking discards the index-based set too. + rerender({ + count: 6, + start: 0, + end: 6, + batchSize: 2, + getItemKey: (index: number) => order[index], + }); + expect(revealedIn(result.current.isRevealed, 0, 6)).toEqual([0, 1]); + expect(result.current.pendingCount).toBe(4); + }); + + it("keeps previously revealed indexes visible once count shrinks below them, and reports zero pending when hi <= lo", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { initialProps: { count: 100, start: 0, end: 5, batchSize: 5 } } + ); + expect(revealedIn(result.current.isRevealed, 0, 5)).toEqual(range(0, 5)); + + // count shrinks to 3, but index 4 was already marked revealed. The + // documented behaviour is that isRevealed reports whatever the set says, + // regardless of count. + rerender({ count: 3, start: 0, end: 5, batchSize: 5 }); + expect(result.current.isRevealed(4)).toBe(true); + + // A window where start sits past the (count-clamped) end has hi <= lo: + // nothing is pending by definition. + rerender({ count: 3, start: 5, end: 15, batchSize: 5 }); + expect(result.current.pendingCount).toBe(0); + }); + + it("reveals the first batch once, waves add exactly batchSize, and reset re-primes exactly one batch under StrictMode", () => { + const { result } = renderHook( + () => + useViewportReveal({ + count: 1000, + start: 0, + end: 20, + batchSize: 4, + interval: 50, + }), + { + wrapper: ({ children }) => {children}, + } + ); + expect(revealedIn(result.current.isRevealed, 0, 20)).toEqual(range(0, 4)); + expect(result.current.pendingCount).toBe(16); + + advanceWave(); + expect(revealedIn(result.current.isRevealed, 0, 20)).toEqual(range(0, 8)); + expect(result.current.pendingCount).toBe(12); + + act(() => { + result.current.reset(); + }); + expect(revealedIn(result.current.isRevealed, 0, 20)).toEqual(range(0, 4)); + expect(result.current.pendingCount).toBe(16); + }); + + it("primes the first batch synchronously and schedules no timer when enabled is false at mount", () => { + const { result } = renderHook(() => + useViewportReveal({ + count: 500, + start: 0, + end: 30, + batchSize: 7, + enabled: false, + }) + ); + expect(revealedIn(result.current.isRevealed, 0, 30)).toEqual(range(0, 7)); + expect(result.current.pendingCount).toBe(23); + expect(vi.getTimerCount()).toBe(0); + }); + + it("keeps rows revealed when the window moves away and back, and counts only never-revealed rows as pending", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { + initialProps: { + count: 1000, + start: 0, + end: 15, + batchSize: 5, + interval: 50, + }, + } + ); + advanceWave(); + advanceWave(); + expect(result.current.pendingCount).toBe(0); + + rerender({ count: 1000, start: 100, end: 115, batchSize: 5, interval: 50 }); + advanceWave(); + expect(revealedIn(result.current.isRevealed, 100, 115)).toEqual( + range(100, 105) + ); + + // Move to a window overlapping both the fully revealed [0, 15) and the + // partially revealed [100, 105): pendingCount counts only what neither + // wave has touched yet. + rerender({ count: 1000, start: 5, end: 105, batchSize: 5, interval: 50 }); + const revealedInWindow = revealedIn( + result.current.isRevealed, + 5, + 105 + ).length; + expect(revealedInWindow).toBe(10 + 5); // [5, 15) and [100, 105) + expect(result.current.pendingCount).toBe(100 - revealedInWindow); + }); + + it("reveals batchSize rows per wave and drains pendingCount accordingly across a very large window", () => { + const { result } = renderHook(() => + useViewportReveal({ + count: 10000, + start: 0, + end: 5000, + batchSize: 20, + interval: 50, + }) + ); + expect(result.current.pendingCount).toBe(4980); + + advanceWave(); + expect(result.current.pendingCount).toBe(4960); + expect(revealedIn(result.current.isRevealed, 0, 40)).toEqual(range(0, 40)); + + advanceWave(); + expect(result.current.pendingCount).toBe(4940); + }); + + it("reveals the first batch synchronously the moment count goes from 0 to non-zero", () => { + const { result, rerender } = renderHook( + (props: UseViewportRevealOptions) => useViewportReveal(props), + { initialProps: { count: 0, start: 0, end: 0, batchSize: 8 } } + ); + expect(result.current.pendingCount).toBe(0); + expect(revealedIn(result.current.isRevealed, 0, 10)).toEqual([]); + + rerender({ count: 250, start: 0, end: 30, batchSize: 8 }); + expect(revealedIn(result.current.isRevealed, 0, 30)).toEqual(range(0, 8)); + expect(result.current.pendingCount).toBe(22); + }); +}); diff --git a/test/useVirtualWindow.test.tsx b/test/useVirtualWindow.test.tsx new file mode 100644 index 0000000..6a17d26 --- /dev/null +++ b/test/useVirtualWindow.test.tsx @@ -0,0 +1,760 @@ +import { act, fireEvent, render } from "@testing-library/react"; +import { StrictMode, useCallback, useRef } from "react"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { useVirtualWindow } from "../src/useVirtualWindow"; +import type { + UseVirtualWindowOptions, + UseVirtualWindowResult, +} from "../src/useVirtualWindow"; +import { MockResizeObserver } from "./setup"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// hook sees a realistic viewport and content size. Copied from +// VirtualRenderWave.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +type HookRef = { current: UseVirtualWindowResult | null }; + +interface HarnessProps extends Omit { + count: number; + /** Height of the scroll container, in pixels. */ + height?: number; + hookRef?: HookRef; + /** Remounts the scroll container when it changes. */ + outerKey?: string; + onRenderResult?: (result: UseVirtualWindowResult) => void; +} + +function rows(v: UseVirtualWindowResult) { + return v.virtualItems.map((it) => ( +
+ Item {it.index} +
+ )); +} + +function Harness({ + height = 400, + hookRef, + outerKey, + onRenderResult, + ...options +}: HarnessProps) { + const v = useVirtualWindow(options); + if (hookRef) hookRef.current = v; + onRenderResult?.(v); + return ( +
+
{rows(v)}
+
+ ); +} + +/** Same list, but the container is handed over through getScrollElement. */ +function GetterHarness({ height = 400, hookRef, ...options }: HarnessProps) { + const elRef = useRef(null); + const getScrollElement = useCallback(() => elRef.current, []); + const v = useVirtualWindow({ ...options, getScrollElement }); + if (hookRef) hookRef.current = v; + return ( +
+
{rows(v)}
+
+ ); +} + +const renderedIndexes = (container: HTMLElement) => + Array.from(container.querySelectorAll('[role="listitem"]')).map((el) => + Number(el.getAttribute("data-index")) + ); + +const range = (from: number, to: number) => + Array.from({ length: to - from }, (_, i) => from + i); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +const rowObserver = () => + MockResizeObserver.instances.find((ro) => + Array.from(ro.observed).some((el) => el.getAttribute("role") === "listitem") + ); + +const stubHeight = (el: Element, value: number) => { + Object.defineProperty(el, "offsetHeight", { configurable: true, value }); +}; + +const rowAt = (container: HTMLElement, index: number) => + container.querySelector(`[data-index="${index}"]`) as HTMLElement; + +describe("useVirtualWindow", () => { + it("renders the visible window plus overscan and moves it on scroll", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(renderedIndexes(container)).toEqual(range(0, 15)); + expect(hookRef.current?.totalSize).toBe(40000); + expect(hookRef.current?.visibleStart).toBe(0); + expect(hookRef.current?.visibleEnd).toBe(10); + + scrollTo(scroller, 4000); + + expect(renderedIndexes(container)).toEqual(range(95, 115)); + expect(hookRef.current?.visibleStart).toBe(100); + expect(hookRef.current?.visibleEnd).toBe(110); + }); + + it("takes the container from the getScrollElement option", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(hookRef.current?.getScrollElement()).toBe(scroller); + expect(renderedIndexes(container)).toEqual(range(0, 15)); + + scrollTo(scroller, 4000); + expect(renderedIndexes(container)).toEqual(range(95, 115)); + }); + + it("carries a measured size to the item's new index after a reorder", () => { + const hookRef: HookRef = { current: null }; + const first = ["a", "b", "c"]; + const { container, rerender } = render( + first[i]} + hookRef={hookRef} + /> + ); + + stubHeight(rowAt(container, 0), 100); + const observer = rowObserver(); + expect(observer).toBeDefined(); + act(() => { + observer?.trigger([rowAt(container, 0)]); + }); + + expect(hookRef.current?.sizeOf(0)).toBe(100); + expect(hookRef.current?.totalSize).toBe(180); + + const reversed = ["c", "b", "a"]; + rerender( + reversed[i]} + hookRef={hookRef} + /> + ); + + expect(hookRef.current?.sizeOf(0)).toBe(40); + expect(hookRef.current?.sizeOf(2)).toBe(100); + expect(hookRef.current?.offsetOf(2)).toBe(80); + expect(hookRef.current?.totalSize).toBe(180); + }); + + it("measures with the measureSize option on both paths", () => { + let firstSize = 70; + const measureSize = vi.fn((el: HTMLElement) => + el.getAttribute("data-index") === "0" ? firstSize : 0 + ); + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + + // The commit pass. + expect(measureSize).toHaveBeenCalled(); + expect(hookRef.current?.sizeOf(0)).toBe(70); + expect(hookRef.current?.totalSize).toBe(70 + 99 * 40); + expect(rowAt(container, 1).style.top).toBe("70px"); + + // The observer pass. + firstSize = 120; + act(() => { + rowObserver()?.trigger([rowAt(container, 0)]); + }); + expect(hookRef.current?.sizeOf(0)).toBe(120); + expect(hookRef.current?.totalSize).toBe(120 + 99 * 40); + }); + + it("opens at initialScrollOffset on the first render", () => { + const onRangeChange = vi.fn(); + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(renderedIndexes(container)).toEqual(range(45, 65)); + expect(hookRef.current?.scrollOffset).toBe(2000); + expect(scroller.scrollTop).toBe(2000); + expect(onRangeChange).toHaveBeenCalledWith({ + start: 45, + end: 65, + visibleStart: 50, + visibleEnd: 60, + }); + }); + + it("opens at initialScrollIndex and corrects it once items are measured", () => { + const hookRef: HookRef = { current: null }; + const props = { + count: 1000, + estimateSize: 40, + overscan: 40, + initialScrollIndex: 50, + hookRef, + }; + const { container, rerender } = render(); + const scroller = container.firstElementChild as HTMLElement; + + expect(scroller.scrollTop).toBe(2000); + expect(hookRef.current?.visibleStart).toBe(50); + + // An item above the target turns out 60px taller than the estimate. + stubHeight(rowAt(container, 10), 100); + act(() => { + rerender(); + }); + + expect(hookRef.current?.offsetOf(50)).toBe(2060); + expect(scroller.scrollTop).toBe(2060); + expect(hookRef.current?.scrollOffset).toBe(2060); + }); + + it("corrects initialScrollIndex under StrictMode too", () => { + // StrictMode runs the attach effect's cleanup and body again on mount in + // development. The correction target has to survive that, or the list + // settles 60px above the item it was opened at. + const hookRef: HookRef = { current: null }; + const props = { + count: 1000, + estimateSize: 40, + overscan: 40, + initialScrollIndex: 50, + hookRef, + }; + const { container, rerender } = render( + + + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(scroller.scrollTop).toBe(2000); + + stubHeight(rowAt(container, 10), 100); + act(() => { + rerender( + + + + ); + }); + + expect(hookRef.current?.offsetOf(50)).toBe(2060); + expect(scroller.scrollTop).toBe(2060); + }); + + it("aligns scrollToIndex to the start, centre, end or only when needed", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50)); + expect(scroller.scrollTop).toBe(2000); + + act(() => hookRef.current?.scrollToIndex(50, { align: "center" })); + expect(scroller.scrollTop).toBe(2000 - (400 - 40) / 2); + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + expect(scroller.scrollTop).toBe(2000 + 40 - 400); + + // Back to the top, where index 3 is already fully visible. + act(() => hookRef.current?.scrollToOffset(0)); + act(() => hookRef.current?.scrollToIndex(3, { align: "auto" })); + expect(scroller.scrollTop).toBe(0); + + // Below the viewport: aligned to the end. + act(() => hookRef.current?.scrollToIndex(20, { align: "auto" })); + expect(scroller.scrollTop).toBe(800 + 40 - 400); + + // Above the viewport: aligned to the start. + act(() => hookRef.current?.scrollToOffset(2000)); + act(() => hookRef.current?.scrollToIndex(10, { align: "auto" })); + expect(scroller.scrollTop).toBe(400); + }); + + it("gives up correcting a target after five attempts", () => { + // The target row reports a new size on every pass, so the offset it has + // to be aligned to never stops moving. + let grown = 40; + let growths = 0; + const measureSize = (el: HTMLElement) => { + if (el.getAttribute("data-index") !== "50") return 0; + if (growths < 8) { + growths += 1; + grown += 20; + } + return grown; + }; + const hookRef: HookRef = { current: null }; + const props = { + count: 1000, + estimateSize: 40, + overscan: 0, + measureSize, + hookRef, + }; + const { container, rerender } = render(); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + + // Five corrections, at sizes 60 through 140, then the target is dropped + // even though the row keeps growing to 200. + expect(grown).toBe(200); + expect(scroller.scrollTop).toBe(2000 + 140 - 400); + expect(hookRef.current?.sizeOf(50)).toBe(200); + + // Nothing is chasing the row any more: it keeps growing on its own. + growths = 0; + act(() => { + rerender(); + }); + expect(hookRef.current?.sizeOf(50)).toBe(360); + expect(scroller.scrollTop).toBe(2000 + 140 - 400); + }); + + it("reports scroll offsets once per frame and not on attach", () => { + const onScroll = vi.fn(); + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + expect(onScroll).not.toHaveBeenCalled(); + + scrollTo(scroller, 1234); + expect(onScroll).toHaveBeenCalledTimes(1); + expect(onScroll).toHaveBeenLastCalledWith(1234); + + // Several events inside one frame report once, with the final offset. + act(() => { + scroller.scrollTop = 1500; + scroller.dispatchEvent(new Event("scroll")); + scroller.scrollTop = 1600; + scroller.dispatchEvent(new Event("scroll")); + vi.advanceTimersByTime(20); + }); + expect(onScroll).toHaveBeenCalledTimes(2); + expect(onScroll).toHaveBeenLastCalledWith(1600); + }); + + it("finishes a smooth target once the scrolling goes quiet", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { behavior: "smooth" })); + act(() => { + vi.advanceTimersByTime(20); + }); + expect(scroller.scrollTop).toBe(2000); + expect(hookRef.current?.scrollOffset).toBe(2000); + + // An item above the target grows while the animation is still running. + // Re-issuing now would fight the animation, so nothing moves yet. + stubHeight(rowAt(container, 45), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 45)]); + }); + expect(scroller.scrollTop).toBe(2000); + + act(() => { + vi.advanceTimersByTime(200); + }); + expect(scroller.scrollTop).toBe(2060); + expect(hookRef.current?.scrollOffset).toBe(2060); + }); + + it("cancels a pending target when scrollToOffset is called", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + expect(scroller.scrollTop).toBe(1640); + + // The same position, but no longer tied to an item. + act(() => hookRef.current?.scrollToOffset(1640)); + + stubHeight(rowAt(container, 45), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 45)]); + }); + + expect(hookRef.current?.offsetOf(50)).toBe(2060); + expect(scroller.scrollTop).toBe(1640); + }); + + it("drops a pending target when the user scrolls away", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + expect(scroller.scrollTop).toBe(1640); + + // A scroll that lands nowhere near the issued offset is the user. + scrollTo(scroller, 1000); + + stubHeight(rowAt(container, 30), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 30)]); + }); + + // The item moved down by 60px, and the list did not chase it. + expect(hookRef.current?.offsetOf(50)).toBe(2060); + expect(scroller.scrollTop).toBe(1000); + }); + + it("drops a pending target on wheel input over the container", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + expect(scroller.scrollTop).toBe(1640); + + fireEvent.wheel(scroller); + + stubHeight(rowAt(container, 45), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 45)]); + }); + + // Without the wheel the target would have been re-issued at 1700. + expect(hookRef.current?.offsetOf(50)).toBe(2060); + expect(scroller.scrollTop).toBe(1640); + }); + + describe("onRangeChange", () => { + it("reports on mount, on a move, and not on a no-op rerender", () => { + const onRangeChange = vi.fn(); + const props = { + count: 1000, + estimateSize: 40, + overscan: 5, + onRangeChange, + }; + const { container, rerender } = render(); + const scroller = container.firstElementChild as HTMLElement; + + expect(onRangeChange).toHaveBeenCalledTimes(1); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 0, + end: 15, + visibleStart: 0, + visibleEnd: 10, + }); + + rerender(); + expect(onRangeChange).toHaveBeenCalledTimes(1); + + scrollTo(scroller, 4000); + expect(onRangeChange).toHaveBeenCalledTimes(2); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 95, + end: 115, + visibleStart: 100, + visibleEnd: 110, + }); + }); + + it("reports once on mount when the rows measure taller than the estimate", () => { + // Nothing delivers a ResizeObserver entry: the rows are measured by the + // commit pass, which suppresses the report of the range it measured. The + // settled range still has to be announced, and exactly once. + const offsetHeight = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + "offsetHeight" + ); + Object.defineProperty(HTMLElement.prototype, "offsetHeight", { + configurable: true, + get(this: HTMLElement) { + return this.getAttribute("role") === "listitem" ? 90 : 0; + }, + }); + + try { + const onRangeChange = vi.fn(); + render( + + ); + + // 90px rows: four of them fit in 400px, indexAt(399) is 4. + expect(onRangeChange).toHaveBeenCalledTimes(1); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 0, + end: 10, + visibleStart: 0, + visibleEnd: 5, + }); + } finally { + if (offsetHeight) { + Object.defineProperty( + HTMLElement.prototype, + "offsetHeight", + offsetHeight + ); + } else { + Reflect.deleteProperty(HTMLElement.prototype, "offsetHeight"); + } + } + }); + + it("reports on mount when measuring leaves the range where it was", () => { + // The rows measure exactly the estimate. The commit pass still records + // the sizes and suppresses its report, and the re-render that follows + // lands on the same four bounds, so nothing but the heights version + // tells this effect it has a report still owed. + const offsetHeight = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + "offsetHeight" + ); + Object.defineProperty(HTMLElement.prototype, "offsetHeight", { + configurable: true, + get(this: HTMLElement) { + return this.getAttribute("role") === "listitem" ? 40 : 0; + }, + }); + + try { + const onRangeChange = vi.fn(); + render( + + ); + + expect(onRangeChange).toHaveBeenCalledTimes(1); + expect(onRangeChange).toHaveBeenLastCalledWith({ + start: 0, + end: 15, + visibleStart: 0, + visibleEnd: 10, + }); + } finally { + if (offsetHeight) { + Object.defineProperty( + HTMLElement.prototype, + "offsetHeight", + offsetHeight + ); + } else { + Reflect.deleteProperty(HTMLElement.prototype, "offsetHeight"); + } + } + }); + + it("stays quiet on mount for an empty list", () => { + const onRangeChange = vi.fn(); + render( + + ); + expect(onRangeChange).not.toHaveBeenCalled(); + }); + + it("reports once on mount under StrictMode", () => { + const onRangeChange = vi.fn(); + render( + + + + ); + expect(onRangeChange).toHaveBeenCalledTimes(1); + }); + }); + + it("offsets the window and scroll targets by scrollMargin", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(hookRef.current?.visibleStart).toBe(0); + expect(hookRef.current?.start).toBe(0); + + scrollTo(scroller, 500); + expect(hookRef.current?.visibleStart).toBe(10); + + act(() => hookRef.current?.scrollToIndex(50)); + expect(scroller.scrollTop).toBe(2100); + }); + + it("keeps every returned function stable across rerenders", () => { + const hookRef: HookRef = { current: null }; + const props = { count: 100, estimateSize: 40, hookRef }; + const { rerender } = render(); + const before = hookRef.current!; + + rerender(); + const after = hookRef.current!; + + expect(after).not.toBe(before); + expect(after.scrollRef).toBe(before.scrollRef); + expect(after.measureRef).toBe(before.measureRef); + expect(after.scrollToIndex).toBe(before.scrollToIndex); + expect(after.scrollToOffset).toBe(before.scrollToOffset); + expect(after.offsetOf).toBe(before.offsetOf); + expect(after.sizeOf).toBe(before.sizeOf); + expect(after.indexAt).toBe(before.indexAt); + expect(after.getScrollElement).toBe(before.getScrollElement); + expect(after.measureRef(3)).toBe(before.measureRef(3)); + }); + + it("moves its listeners when the container element is swapped", () => { + const hookRef: HookRef = { current: null }; + const props = { count: 1000, estimateSize: 40, overscan: 5, hookRef }; + const { container, rerender } = render(); + const oldScroller = container.firstElementChild as HTMLElement; + + scrollTo(oldScroller, 4000); + expect(renderedIndexes(container)).toEqual(range(95, 115)); + + rerender(); + const newScroller = container.firstElementChild as HTMLElement; + expect(newScroller).not.toBe(oldScroller); + expect(hookRef.current?.getScrollElement()).toBe(newScroller); + // The new container starts at the top, and the window follows it. + expect(renderedIndexes(container)).toEqual(range(0, 15)); + + scrollTo(newScroller, 4000); + expect(renderedIndexes(container)).toEqual(range(95, 115)); + + scrollTo(oldScroller, 0); + expect(renderedIndexes(container)).toEqual(range(95, 115)); + }); +}); diff --git a/test/useVirtualWindowEdges.test.tsx b/test/useVirtualWindowEdges.test.tsx new file mode 100644 index 0000000..1ecbc2a --- /dev/null +++ b/test/useVirtualWindowEdges.test.tsx @@ -0,0 +1,520 @@ +import { act, render } from "@testing-library/react"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { useVirtualWindow } from "../src/useVirtualWindow"; +import type { + UseVirtualWindowOptions, + UseVirtualWindowResult, +} from "../src/useVirtualWindow"; +import { MockResizeObserver } from "./setup"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// hook sees a realistic viewport and content size. Copied from +// useVirtualWindow.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +type HookRef = { current: UseVirtualWindowResult | null }; + +interface HarnessProps extends Omit { + count: number; + /** Height of the scroll container, in pixels. */ + height?: number; + hookRef?: HookRef; + /** Remounts the scroll container when it changes. */ + outerKey?: string; + /** Skips rendering the scroll container entirely while false. */ + attach?: boolean; +} + +function rows(v: UseVirtualWindowResult) { + return v.virtualItems.map((it) => ( +
+ Item {it.index} +
+ )); +} + +function Harness({ + height = 400, + hookRef, + outerKey, + attach = true, + ...options +}: HarnessProps) { + const v = useVirtualWindow(options); + if (hookRef) hookRef.current = v; + if (!attach) return
; + return ( +
+
{rows(v)}
+
+ ); +} + +const renderedIndexes = (container: HTMLElement) => + Array.from(container.querySelectorAll('[role="listitem"]')).map((el) => + Number(el.getAttribute("data-index")) + ); + +const range = (from: number, to: number) => + Array.from({ length: to - from }, (_, i) => from + i); + +const rowObserver = () => + MockResizeObserver.instances.find((ro) => + Array.from(ro.observed).some((el) => el.getAttribute("role") === "listitem") + ); + +const stubHeight = (el: Element, value: number) => { + Object.defineProperty(el, "offsetHeight", { configurable: true, value }); +}; + +const rowAt = (container: HTMLElement, index: number) => + container.querySelector(`[data-index="${index}"]`) as HTMLElement; + +describe("useVirtualWindow edges", () => { + it("stores a scrollToIndex issued before attach and applies it once the container arrives", () => { + const hookRef: HookRef = { current: null }; + const { container, rerender } = render( + + ); + + act(() => hookRef.current?.scrollToIndex(50)); + + rerender( + + ); + const scroller = container.firstElementChild as HTMLElement; + + expect(scroller.scrollTop).toBe(2000); + }); + + it("reports onRangeChange for count 1000 -> 0, stays quiet at 0, then reports again for 0 -> 100", () => { + const shrinkSpy = vi.fn(); + const { rerender: rerenderShrink } = render( + + ); + shrinkSpy.mockClear(); + rerenderShrink( + + ); + expect(shrinkSpy).toHaveBeenCalledWith({ + start: 0, + end: 0, + visibleStart: 0, + visibleEnd: 0, + }); + + const growSpy = vi.fn(); + const { rerender: rerenderGrow } = render( + + ); + expect(growSpy).not.toHaveBeenCalled(); + rerenderGrow( + + ); + expect(growSpy).toHaveBeenCalledWith({ + start: 0, + end: 15, + visibleStart: 0, + visibleEnd: 10, + }); + }); + + it("drops a pending target when the count shrinks below its index, so a later measurement does not chase it", () => { + const hookRef: HookRef = { current: null }; + const { container, rerender } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(900)); + expect(scroller.scrollTop).toBe(36000); + + rerender( + + ); + + // Row 95 is inside the rendered window for the shrunk list. + stubHeight(rowAt(container, 95), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 95)]); + }); + + expect(scroller.scrollTop).toBe(36000); + expect(hookRef.current?.scrollOffset).toBe(36000); + }); + + it("clears a pending target and moves its listeners when the container element is swapped", () => { + const hookRef: HookRef = { current: null }; + const { container, rerender } = render( + + ); + const oldScroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(500)); + expect(oldScroller.scrollTop).toBe(20000); + + rerender( + + ); + const newScroller = container.firstElementChild as HTMLElement; + expect(newScroller).not.toBe(oldScroller); + expect(renderedIndexes(container)).toEqual(range(0, 15)); + + act(() => { + oldScroller.scrollTop = 9999; + oldScroller.dispatchEvent(new Event("scroll")); + vi.advanceTimersByTime(20); + }); + + expect(renderedIndexes(container)).toEqual(range(0, 15)); + expect(hookRef.current?.scrollOffset).toBe(0); + }); + + it("aligns scrollToIndex to center and end with a scrollMargin offset", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { align: "center" })); + expect(scroller.scrollTop).toBe(1920); + + act(() => hookRef.current?.scrollToIndex(50, { align: "end" })); + expect(scroller.scrollTop).toBe(1740); + }); + + it("accumulates fractional measured sizes exactly through both the layout pass and the observer path", () => { + const offsetHeight = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + "offsetHeight" + ); + Object.defineProperty(HTMLElement.prototype, "offsetHeight", { + configurable: true, + get(this: HTMLElement) { + return this.getAttribute("role") === "listitem" ? 40.5 : 0; + }, + }); + + try { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + + // Layout pass: rows 0..9 all measured at 40.5 on mount. + expect(hookRef.current?.offsetOf(10)).toBe(405); + + // Observer path: row 0 reports a different fractional size. + stubHeight(rowAt(container, 0), 50.25); + act(() => { + rowObserver()?.trigger([rowAt(container, 0)]); + }); + + expect(hookRef.current?.sizeOf(0)).toBe(50.25); + expect(hookRef.current?.offsetOf(10)).toBe(414.75); + } finally { + if (offsetHeight) { + Object.defineProperty( + HTMLElement.prototype, + "offsetHeight", + offsetHeight + ); + } else { + Reflect.deleteProperty(HTMLElement.prototype, "offsetHeight"); + } + } + }); + + it("renders exactly the visible rows with overscan 0, and a 0 viewport renders one row plus overscan without throwing", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + expect(renderedIndexes(container)).toEqual(range(0, 10)); + + const zeroHookRef: HookRef = { current: null }; + expect(() => + render( + + ) + ).not.toThrow(); + expect(zeroHookRef.current?.viewportSize).toBe(0); + }); + + it("cancels a smooth scroll correction on a user wheel event, so a later measurement does not move it", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + + act(() => hookRef.current?.scrollToIndex(50, { behavior: "smooth" })); + act(() => { + vi.advanceTimersByTime(20); + }); + expect(scroller.scrollTop).toBe(2000); + + scroller.dispatchEvent(new Event("wheel")); + + act(() => { + vi.advanceTimersByTime(200); + }); + + stubHeight(rowAt(container, 45), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 45)]); + }); + + expect(scroller.scrollTop).toBe(2000); + }); + + it("carries measured sizes by key and drops exactly the removed item's size when a reorder removes an item along with a count change", () => { + const before = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; + const hookRef: HookRef = { current: null }; + const { container, rerender } = render( + before[i]} + hookRef={hookRef} + /> + ); + + stubHeight(rowAt(container, 0), 100); + stubHeight(rowAt(container, 4), 70); + const observer = rowObserver(); + act(() => { + observer?.trigger([rowAt(container, 0), rowAt(container, 4)]); + }); + + expect(hookRef.current?.totalSize).toBe(490); + + const after = ["b", "c", "d", "e", "f", "g", "h", "i", "j"]; + rerender( + after[i]} + hookRef={hookRef} + /> + ); + + expect(hookRef.current?.sizeOf(3)).toBe(70); // "e" carried its measured size + expect(hookRef.current?.totalSize).toBe(390); + }); + + it("keeps every measured size when getItemKey changes identity but keeps the same mapping", () => { + const keys = Array.from({ length: 20 }, (_, i) => `k${i}`); + const keyFnA = (i: number) => keys[i]; + const hookRef: HookRef = { current: null }; + const { container, rerender } = render( + + ); + + stubHeight(rowAt(container, 0), 100); + act(() => { + rowObserver()?.trigger([rowAt(container, 0)]); + }); + expect(hookRef.current?.offsetOf(1)).toBe(100); + + const keyFnB = (i: number) => keys[i]; + rerender( + + ); + + expect(hookRef.current?.sizeOf(0)).toBe(100); + expect(hookRef.current?.offsetOf(1)).toBe(100); + }); + + it("gives every virtualItems entry a key, offset and size consistent with offsetOf/sizeOf", () => { + const hookRef: HookRef = { current: null }; + render( + `item-${i}`} + hookRef={hookRef} + /> + ); + + const result = hookRef.current!; + expect(result.virtualItems.length).toBe(result.end - result.start); + for (const item of result.virtualItems) { + expect(item.key).toBe(`item-${item.index}`); + expect(item.offset).toBe(result.offsetOf(item.index)); + expect(item.size).toBe(result.sizeOf(item.index)); + } + }); + + it("resolves indexAt boundaries correctly through the hook once rows have mixed measured sizes", () => { + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + + stubHeight(rowAt(container, 0), 100); + stubHeight(rowAt(container, 1), 50); + stubHeight(rowAt(container, 2), 25); + act(() => { + rowObserver()?.trigger([ + rowAt(container, 0), + rowAt(container, 1), + rowAt(container, 2), + ]); + }); + + expect(hookRef.current?.indexAt(99)).toBe(0); + expect(hookRef.current?.indexAt(100)).toBe(1); + expect(hookRef.current?.indexAt(149)).toBe(1); + expect(hookRef.current?.indexAt(150)).toBe(2); + expect(hookRef.current?.indexAt(175)).toBe(3); + }); + + it("does not call onScroll on attach or for a programmatic instant scroll, since jsdom never fires a scroll event from a scrollTop write", () => { + const onScroll = vi.fn(); + const hookRef: HookRef = { current: null }; + const { container } = render( + + ); + const scroller = container.firstElementChild as HTMLElement; + expect(onScroll).not.toHaveBeenCalled(); + + act(() => hookRef.current?.scrollToIndex(50)); + expect(scroller.scrollTop).toBe(2000); + expect(onScroll).not.toHaveBeenCalled(); + + // A real scroll event still reports once per animation frame. + act(() => { + scroller.dispatchEvent(new Event("scroll")); + vi.advanceTimersByTime(20); + }); + expect(onScroll).toHaveBeenCalledTimes(1); + expect(onScroll).toHaveBeenLastCalledWith(2000); + }); +}); diff --git a/test/virtualBehaviours.test.tsx b/test/virtualBehaviours.test.tsx new file mode 100644 index 0000000..e2ba132 --- /dev/null +++ b/test/virtualBehaviours.test.tsx @@ -0,0 +1,451 @@ +import { act, render, screen, within } from "@testing-library/react"; +import { createRef } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { renderToString } from "react-dom/server"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import type { VirtualRenderWaveHandle } from "../src/types"; +import { MockResizeObserver } from "./setup"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. Copied from +// VirtualRenderWave.test.tsx so this file can run standalone. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +describe("VirtualRenderWave behaviours (regression net for the windowing refactor)", () => { + it("injects a single shared keyframes style and marks only revealed rows with the fade animation", () => { + const list = items(5); + const { container: c1 } = render( +
{item}
} + /> + ); + const { container: c2 } = render( +
{item}
} + /> + ); + + expect( + document.head.querySelectorAll("style[data-react-render-wave]") + ).toHaveLength(1); + + const revealedRows = [ + ...c1.querySelectorAll('[role="listitem"]'), + ...c2.querySelectorAll('[role="listitem"]'), + ]; + expect(revealedRows.length).toBeGreaterThan(0); + for (const row of revealedRows) { + expect((row as HTMLElement).style.animation).toContain("rrw-fade-in"); + } + + const { container: c3 } = render( +
Skeleton {i}
} + renderItem={(item) =>
{item}
} + /> + ); + const skeletonRows = Array.from( + c3.querySelectorAll('[role="listitem"]') + ).filter((row) => row.textContent?.startsWith("Skeleton")); + expect(skeletonRows.length).toBeGreaterThan(0); + for (const row of skeletonRows) { + expect((row as HTMLElement).style.animation).toBe(""); + } + }); + + it("keeps the same DOM node for a row across a reorder when getItemKey is stable", () => { + type Row = { id: number; label: string }; + const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({ + id: i, + label: `Item ${i}`, + })); + + const { rerender } = render( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + const original = screen.getByText("Item 3").closest('[role="listitem"]'); + expect(original).toBeTruthy(); + + rerender( + item.id} + renderItem={(item) =>
{item.label}
} + /> + ); + const afterReorder = screen + .getByText("Item 3") + .closest('[role="listitem"]'); + expect(afterReorder).toBe(original); + expect((afterReorder as HTMLElement).style.top).toBe("320px"); + }); + + it("renders skeletons before startIndex and starts the visible window at startIndex", () => { + const ref = createRef(); + render( +
Skeleton {i}
} + renderItem={(item) =>
{item}
} + /> + ); + + for (let i = 0; i < 5; i++) { + expect(screen.getByText(`Skeleton ${i}`)).toBeTruthy(); + } + expect(screen.getByText("Item 5")).toBeTruthy(); + expect(screen.queryByText("Skeleton 5")).toBeNull(); + + const visible = ref.current?.getVisibleIndexes(); + expect(visible?.[0]).toBe(5); + }); + + it("recomputes offsets and total height when itemHeight changes", () => { + const { container, rerender } = render( +
{item}
} + /> + ); + const inner = () => container.querySelector('[role="list"]') as HTMLElement; + const second = () => + container.querySelector('[aria-posinset="2"]') as HTMLElement; + expect(inner().style.height).toBe("40000px"); + expect(second().style.top).toBe("40px"); + + rerender( +
{item}
} + /> + ); + expect(inner().style.height).toBe("80000px"); + expect(second().style.top).toBe("80px"); + }); + + it("grows the rendered window when the viewport is resized", () => { + const { container } = render( +
{item}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + expect(screen.getAllByRole("listitem")).toHaveLength(15); + + const viewportObserver = MockResizeObserver.instances.find((ro) => + ro.observed.has(outer) + ); + expect(viewportObserver).toBeDefined(); + + act(() => { + outer.style.height = "800px"; + viewportObserver?.trigger([outer]); + }); + + // 20 rows fit in 800px, plus 5 overscan below. + expect(screen.getAllByRole("listitem")).toHaveLength(25); + }); + + it("passes className and style through to the outer element, sizing the viewport from style.height", () => { + render( +
{item}
} + /> + ); + const count200 = screen.getAllByRole("listitem").length; + expect(count200).toBe(10); + + const { container } = render( +
{item}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + expect(outer.className).toBe("my-list"); + expect(outer.style.background).toBe("red"); + expect(outer.style.overflowY).toBe("auto"); + expect(outer.style.position).toBe("relative"); + + const count300 = within(container).getAllByRole("listitem").length; + expect(count300).toBeGreaterThan(count200); + }); + + it("renders exactly the fitting rows when overscan is 0", () => { + render( +
{item}
} + /> + ); + expect(screen.getAllByRole("listitem")).toHaveLength(10); + }); + + it("clamps scrollToIndex past the end to the bottom of the list", () => { + const { container } = render( +
{item}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + // 4000px of content in a 400px viewport: the last scroll position is + // 3600. The windowing hook clamps to it up front, where the pre-hook + // component wrote the raw 4000 offset and left the clamping to the + // browser (jsdom does not clamp, so the old expectation was 4000). + expect(outer.scrollTop).toBe(3600); + }); + + it("supports groupByKey as a function alongside a sticky header", () => { + const rows = Array.from({ length: 60 }, (_, i) => ({ label: `Row ${i}` })); + const { container } = render( + (index < 30 ? "A" : "B")} + renderStickyHeader={(group) =>
Group {group}
} + renderItem={(row) =>
{row.label}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + + expect(screen.getByText("Group A")).toBeTruthy(); + + scrollTo(outer, 31 * 40); + expect(screen.getByText("Group B")).toBeTruthy(); + expect(screen.queryByText("Group A")).toBeNull(); + }); + + it("renders no sticky header unless both groupByKey and renderStickyHeader are provided", () => { + const rows = Array.from({ length: 10 }, (_, i) => ({ + label: `Row ${i}`, + group: "A", + })); + + const { container: c1 } = render( +
Group {group}
} + renderItem={(row) =>
{row.label}
} + /> + ); + expect(within(c1).queryByText(/^Group /)).toBeNull(); + + const { container: c2 } = render( +
{row.label}
} + /> + ); + expect(within(c2).queryByText(/^Group /)).toBeNull(); + }); + + it("handles items shrinking below the current scroll position without crashing", () => { + const { container, rerender } = render( +
{item}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + scrollTo(outer, 4000); + + expect(() => + rerender( +
{item}
} + /> + ) + ).not.toThrow(); + + expect(screen.queryByText(/Item undefined/)).toBeNull(); + expect(screen.queryByText("undefined")).toBeNull(); + + const inner = container.querySelector('[role="list"]') as HTMLElement; + expect(inner.style.height).toBe("2000px"); + expect( + container.querySelectorAll('[role="listitem"]').length + ).toBeLessThanOrEqual(50); + }); + + it("hydrates without logging a hydration mismatch warning", () => { + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const element = ( + index} + renderItem={(item) =>
{item}
} + /> + ); + const markup = renderToString(element); + const container = document.createElement("div"); + container.innerHTML = markup; + document.body.appendChild(container); + + let root: ReturnType | undefined; + act(() => { + root = hydrateRoot(container, element); + }); + + // React 18 also logs an unrelated useLayoutEffect warning while + // renderToString runs in jsdom, so asserting "not called at all" would + // be wrong; filter for calls that actually mention hydration. That + // warning has to be named to be excluded: its own text says the effect + // "will lead to a mismatch between the initial, non-hydrated UI and the + // intended UI", which matches on "hydrat" as well. + const hydrationWarnings = errorSpy.mock.calls.filter( + (call) => + String(call[0]).toLowerCase().includes("hydrat") && + !String(call[0]).includes( + "useLayoutEffect does nothing on the server" + ) + ); + expect(hydrationWarnings).toEqual([]); + + act(() => { + root?.unmount(); + }); + container.remove(); + } finally { + errorSpy.mockRestore(); + } + }); +}); diff --git a/test/wrapperElements.test.tsx b/test/wrapperElements.test.tsx new file mode 100644 index 0000000..69d0974 --- /dev/null +++ b/test/wrapperElements.test.tsx @@ -0,0 +1,451 @@ +import { act, render, screen } from "@testing-library/react"; +import { createRef, forwardRef, version as reactVersion } from "react"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { VirtualRenderWave } from "../src/VirtualRenderWave"; +import type { + VirtualRenderWaveHandle, + WrapperComponent, + WrapperProps, +} from "../src/types"; + +// jsdom performs no layout. Heights are derived from inline styles so the +// component sees a realistic viewport and content size. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, "clientHeight", { + configurable: true, + get(this: HTMLElement) { + const px = parseFloat(this.style?.height ?? ""); + return Number.isFinite(px) ? px : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get(this: HTMLElement) { + let max = 0; + for (const child of Array.from(this.children)) { + const px = parseFloat((child as HTMLElement).style?.height ?? ""); + if (Number.isFinite(px)) max = Math.max(max, px); + } + if (max > 0) return max; + const own = parseFloat(this.style?.height ?? ""); + return Number.isFinite(own) ? own : 0; + }, + }); +}); + +afterAll(() => { + Reflect.deleteProperty(HTMLElement.prototype, "clientHeight"); + Reflect.deleteProperty(HTMLElement.prototype, "scrollHeight"); +}); + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + ], + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const items = (n: number) => Array.from({ length: n }, (_, i) => `Item ${i}`); + +const scrollTo = (el: HTMLElement, top: number) => { + act(() => { + el.scrollTop = top; + el.dispatchEvent(new Event("scroll")); + // Flush the animation frame that commits the new scroll position. + vi.advanceTimersByTime(20); + }); +}; + +// React 18 strips `ref` from the props of a plain function component, so only +// the forwardRef form works there. +const onReact19 = Number.parseInt(reactVersion, 10) >= 19 ? it : it.skip; +const onReact18 = Number.parseInt(reactVersion, 10) >= 19 ? it.skip : it; + +const ForwardedSection = forwardRef( + function ForwardedSection({ children, ...rest }, ref) { + return ( +
+ {children} +
+ ); + } +); + +function PlainSection({ children, ...rest }: WrapperProps) { + return ( +
+ {children} +
+ ); +} + +// Takes the ref and drops it on the floor, the way a wrapper that forgets to +// attach it does. +const RefLosingSection = forwardRef( + function RefLosingSection({ children, ...rest }, _ref) { + return
{children}
; + } +); + +const REF_LOST_MESSAGE = + "react-render-wave: outerElement did not attach the ref it received, so " + + "the list cannot scroll or measure. On React 18 wrap the component in " + + "forwardRef and pass the ref to your DOM node."; + +// Five natural shapes for a custom outerElement/innerElement, each typed as a +// WrapperComponent so that tsc covers them as well as the runtime assertions. + +// Shape 1: forwardRef rendering a
. +const ForwardRefSection: WrapperComponent = forwardRef< + HTMLElement, + WrapperProps +>(function ForwardRefSection({ children, ...rest }, ref) { + return ( +
+ {children} +
+ ); +}); + +// Shape 2: forwardRef rendering a +//
. Before the fix, WrapperProps.ref was typed narrower than +// a forwardRef render function's own ref parameter, so this did not compile. +const ForwardRefDiv: WrapperComponent = forwardRef< + HTMLDivElement, + WrapperProps +>(function ForwardRefDiv({ children, ...rest }, ref) { + return ( +
+ {children} +
+ ); +}); + +// Shape 3: FC putting the ref straight on the node as a prop, +// the React 19 ref-as-prop style. Before the fix, WrapperProps.ref did not +// exist as a plain prop a function component could read, so this did not +// compile. +const RefAsPropDiv: WrapperComponent = function RefAsPropDiv( + props: WrapperProps +) { + const { children, ref, ...rest } = props; + return ( +
+ {children} +
+ ); +}; + +// Shape 4: FC whose body reads props.ref?.current, the pattern +// a 3.0.0 consumer may have written against the old, narrower ref type. +// Before the fix, `.current` did not compile on WrapperProps.ref. +const ReadsRefCurrentDiv: WrapperComponent = function ReadsRefCurrentDiv( + props: WrapperProps +) { + const { children, ref, ...rest } = props; + const alreadyMounted = Boolean(ref?.current); + return ( +
+ {children} +
+ ); +}; + +// Shape 5: a plain arrow function component. It destructures `ref` off the +// props but never attaches it anywhere, the way a caller who has not read +// the ref-forwarding note would write it. (Spreading the rest of the props, +// ref included, would forward it on React 19 through the JSX spread the way +// the FC fixture above does; this fixture drops it on purpose so the shape +// is deterministic across both React versions.) +const ArrowDiv: WrapperComponent = (props: WrapperProps) => { + const { children, ref: _ref, ...rest } = props; + return ( +
+ {children} +
+ ); +}; + +describe("VirtualRenderWave wrapper elements", () => { + it("renders string tags and still scrolls", () => { + const { container } = render( +
{item}
} + /> + ); + const outer = container.firstElementChild as HTMLElement; + expect(outer.tagName).toBe("SECTION"); + expect(container.querySelector('[role="list"]')?.tagName).toBe("UL"); + expect(screen.getAllByRole("listitem")).toHaveLength(15); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + }); + + it("attaches the ref of a forwardRef outerElement", () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(outer.tagName).toBe("SECTION"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + }); + + onReact19("attaches the ref of a plain function outerElement", () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.getByText("Item 100")).toBeTruthy(); + }); + + it("reports an outerElement that swallows the ref, once", () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + render( +
{item}
} + /> + ); + + // React itself may warn about the dropped ref as well, so match on ours. + const ours = errors.mock.calls.filter((call) => + String(call[0]).includes("outerElement did not attach the ref") + ); + expect(ours).toHaveLength(1); + expect(ours[0][0]).toBe(REF_LOST_MESSAGE); + // Rows still render; only scrolling and measuring are lost. + expect(screen.getAllByRole("listitem")).toHaveLength(15); + } finally { + errors.mockRestore(); + } + }); +}); + +describe("WrapperProps ref shapes", () => { + it("shape 1: forwardRef rendering a
scrolls and measures", () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(outer.tagName).toBe("SECTION"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + }); + + it("shape 2: forwardRef rendering a
scrolls and measures", () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(outer.tagName).toBe("DIV"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + }); + + onReact19( + "shape 3: FC putting the ref on the node as a prop scrolls and measures (React 19 only)", + () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + } + ); + + onReact18( + "shape 3 on React 18: props.ref never arrives, so the ref-loss warning fires and rows still render", + () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const handle = createRef(); + render( +
{item}
} + /> + ); + expect(handle.current?.getScrollElement()).toBeNull(); + const ours = errors.mock.calls.filter((call) => + String(call[0]).includes("outerElement did not attach the ref") + ); + expect(ours).toHaveLength(1); + expect(screen.getAllByRole("listitem")).toHaveLength(15); + } finally { + errors.mockRestore(); + } + } + ); + + onReact19( + "shape 4: FC reading props.ref?.current scrolls and measures (React 19 only)", + () => { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(handle.current?.getScrollElement()).toBe(outer); + + scrollTo(outer, 4000); + + expect(screen.queryByText("Item 0")).toBeNull(); + expect(screen.getByText("Item 100")).toBeTruthy(); + } + ); + + it("shape 5: a plain arrow function component never forwards the ref, so scrolling and measuring are lost", () => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const handle = createRef(); + render( +
{item}
} + /> + ); + const outer = screen.getByTestId("outer"); + expect(outer.tagName).toBe("DIV"); + expect(handle.current?.getScrollElement()).toBeNull(); + const ours = errors.mock.calls.filter((call) => + String(call[0]).includes("outerElement did not attach the ref") + ); + expect(ours).toHaveLength(1); + // Rows still render; only scrolling and measuring are lost. + expect(screen.getAllByRole("listitem")).toHaveLength(15); + } finally { + errors.mockRestore(); + } + }); +}); From 5491776252b40e293bd176de3257ff54b940b78d Mon Sep 17 00:00:00 2001 From: dev-intj <42313770+sudo-ezekiel@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:35:17 +0300 Subject: [PATCH 3/4] ci: run typecheck, tests, build and the package checks on React 18 and 19 Node 20 and 22 against the pinned React 19 devDependencies, plus a job that reinstalls React 18 and runs typecheck and tests against it. That job earns its keep: a WrapperComponent return type that compiles under @types/react 19 fails under 18, and no React 19 check would have caught it. --- .github/workflows/ci.yml | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a345672 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,46 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [20, 22] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm test + - run: npm run build + - run: npm run check:pkg + + # The devDependencies pin React 19, so the matrix above never exercises React 18. + react-18: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + - run: npm ci + - name: Install React 18 without touching the lockfile + run: npm install --no-save --ignore-scripts react@18 react-dom@18 @types/react@18 @types/react-dom@18 + - name: Print the installed React version + run: node -p "require('react/package.json').version" + - run: npm run typecheck + - run: npm test From 3760c3f94aa2ecfd234065a34559966aece16077 Mon Sep 17 00:00:00 2001 From: dev-intj <42313770+sudo-ezekiel@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:35:23 +0300 Subject: [PATCH 4/4] docs: document 3.1.0 in the README and the changelog The README gains a useVirtualWindow section with a worked example, full option and result tables, the four new component props, and a note on wrapping a custom outerElement in forwardRef for React 18. The changelog entry for 3.0.0 said 2026-07-28. Both the git tag and the npm publish record say 2026-08-22. --- CHANGELOG.md | 42 +++++++++++- README.md | 184 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 203 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60a2a85..1293917 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,46 @@ # Changelog -## 3.0.0 (2026-07-28) +## 3.1.0 (unreleased) + +The windowing engine is now a public hook, `useVirtualWindow`, and `VirtualRenderWave` is built on it. The component API grows by four props and one option object; the one type change that can break a compile is listed under Changed. + +### Added + +- `useVirtualWindow`, a headless windowing hook: given a count and an estimated size it returns the items to render with their offsets, a ref for the scroll container, a per-item ref that measures rows and corrects the offsets below them, `totalSize` for the sizer, and `scrollToIndex`/`scrollToOffset`. It renders nothing and owns no styles, so it fits a table, a grid or a scroller you already have. Options include `scrollMargin` for an in-flow header above the sizer and `measureSize` for fractional row heights. The first render depends only on the count, the estimate, overscan, `scrollMargin`, `getItemKey` and the `initial*` options, so server markup and the first client render agree. +- Exported types for the hook: `UseVirtualWindowOptions`, `UseVirtualWindowResult`, `VirtualItem`, `VirtualRange`, `ScrollAlign`, `ScrollToIndexOptions`, `ScrollToOffsetOptions`, `ItemKey`; and for the component: `RevealMode`, `WrapperComponent`. +- `VirtualRenderWave`: `revealMode`. `"sequential"` (the default) is the 3.0 behaviour and counts forward from `startIndex` regardless of scroll position. `"viewport"` reveals the rows inside the rendered window in batches and never re-hides a revealed row, so a small `batchSize` still fills the screen on a long list instead of needing `batchSize={items.length}`. +- `VirtualRenderWave`: `initialScrollOffset` and `initialScrollIndex`, both read once. The first paint and the server markup already show that window rather than jumping to it after mount. `initialScrollIndex` wins over `initialScrollOffset`, and over a controlled `scrollToIndex` at mount, and is corrected once the rows above it are measured. +- `VirtualRenderWave`: `onRangeChange`, called after commit whenever the rendered or visible range changes. The payload is a `VirtualRange`; `end` and `visibleEnd` are exclusive. +- Handle: `scrollTo(index, options)` accepts `{ align, behavior }` as well as the old behavior string. `align` is `"start"` (default), `"center"`, `"end"` or `"auto"`, which only scrolls when the item is not already fully visible. +- A GitHub Actions workflow (CI) that runs typecheck, tests, build and the package checks on Node 20 and 22, plus a job that reinstalls React 18 and runs typecheck and tests against it, since the devDependencies pin React 19. +- `npm run check:pkg`, which runs publint and arethetypeswrong against the packed tarball. `prepublishOnly` runs it. +- Test suite: 179 tests across 18 files, including regression tests for every fix below. + +### Fixed + +- React 18: a custom `outerElement` or `innerElement` written as a `forwardRef` component could not attach its ref, so the list could not scroll or measure. Rendering and types now support it, and a dev-only `console.error` names the wrapper when one swallows the ref instead of failing silently. +- Package types did not resolve under Node16/NodeNext module resolution from either CJS or ESM. The `exports` map now carries a `types` entry per condition and the build emits both `.d.ts` and `.d.cts`; publint and arethetypeswrong are clean across all four resolution modes. +- `onEndReached` never fired when the content was shorter than the viewport, so a short first page could not trigger the next one. It now runs after any commit that changes the geometry. +- `scrollTo`/`scrollToIndex` near the end of a list whose rows measure taller than the estimate stopped short of the target and never re-aimed. Programmatic scrolls now stay on target while the rows they mount are measured. +- With a non-zero `scrollMargin`, the first render and the server markup opened at the wrong window when `initialScrollIndex` was set. +- `align: "auto"` on an item taller than the viewport could never treat it as already visible, so repeated calls oscillated between two positions. +- `scrollToIndex(NaN)` and `scrollToOffset(NaN)` reset the scroll position to the top instead of being ignored. A non-finite `initialScrollOffset` did the same on the first render. +- Degenerate options broke windowing entirely: an `itemHeight`/`estimateSize` of 0, NaN or Infinity mounted every row in the list, and a negative or NaN `overscan` rendered nothing. The estimate now falls back to 1 and overscan is clamped to a non-negative whole number. +- With `keyboardNavigation`, the arrows, Home, End and the page keys were taken from any focused control inside a row (an input, a select, a contentEditable region). They now only scroll the list when the keydown starts on the scroll container itself. +- The fade-in for revealed rows ignored `prefers-reduced-motion`. The injected keyframes are scoped to `prefers-reduced-motion: no-preference`, so a preference flipped at runtime is picked up without a listener. +- The dev-only warning about a ref-swallowing wrapper fired twice under StrictMode. +- The height cache was replaced by a keyed size cache, so a measured row keeps its height across a reorder when `getItemKey` is set. + +### Changed + +- `WrapperProps.ref` is optional and typed `RefObject` (it was a required `RefObject`), and `WrapperComponent` may return `ReactNode | Promise`. This is the one source-breaking type change in the release: code that read `props.ref.current` needs `props.ref?.current`. It is also what makes a custom wrapper compile at all in most shapes. Before, only a `forwardRef` component typed for `HTMLElement` passed `tsc`; a `forwardRef` typed for `HTMLDivElement`, a plain `FC` attaching the ref itself, an `FC` reading `props.ref?.current`, and under `@types/react` 19 anything typed `FC` were all rejected. All five compile now. +- Handle: `scrollTo` takes `(index, options?)` where `options` is a `ScrollBehavior` string or `{ align, behavior }`. The string form still works. `behavior` still defaults to `"smooth"` on the handle. +- `getItemKey` returns the named type `ItemKey` (`string | number`). No behaviour change. +- `outerElement` and `innerElement` accept `WrapperComponent`. On React 19 the ref arrives as a prop; on React 18 the component must be wrapped in `forwardRef` and attach the forwarded ref. +- `engines.node` is `>=18`. +- Bundle size: the ESM build gzips to about 7 kB (3.0.0: about 3.7 kB). The growth is the windowing hook. + +## 3.0.0 (2026-08-22) Ground-up rewrite of the internals. The component API stays close to v2; the sections below are the full list of what changed. diff --git a/README.md b/README.md index c7b1692..bb9e115 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ # React Render Wave [![npm version](https://img.shields.io/npm/v/react-render-wave)](https://www.npmjs.com/package/react-render-wave) +[![CI](https://github.com/sudo-ezekiel/react-render-wave/actions/workflows/ci.yml/badge.svg)](https://github.com/sudo-ezekiel/react-render-wave/actions/workflows/ci.yml) [![license](https://img.shields.io/npm/l/react-render-wave)](https://github.com/sudo-ezekiel/react-render-wave/blob/main/LICENSE) Progressive wave rendering and lightweight virtual scrolling for React lists. @@ -13,7 +14,7 @@ immediately and the rest streams in while the page stays responsive. For long lists, `VirtualRenderWave` adds windowing on top: only the rows in view, plus overscan, exist in the DOM. -No dependencies, about 3.7 kB gzipped, ESM and CJS with TypeScript types. +No dependencies, about 7 kB gzipped, ESM and CJS with TypeScript types. **Docs, recipes and runnable examples: [renderwave.sudo-ezekiel.com](https://renderwave.sudo-ezekiel.com)** @@ -27,19 +28,25 @@ React 18 or 19 is a peer dependency. ## What you get -Three exports, in increasing order of how much they do for you. +Four exports, in increasing order of how much they do for you. + +`useVirtualWindow` is the windowing engine with no opinion about markup. It +tells you which items to render, where to place them and how tall the sizer +has to be, measures rows as they mount, and scrolls to an index. Use it when +the markup is yours: a table, a grid, a scroller you already have. `useRenderWave` is the reveal on its own. It tells you how many items to show right now and nothing else, so you keep full control of the markup. -`RenderWave` wraps the hook in a component. Everything mounts eventually, -nothing is windowed away. Reach for it when the cost is the components -themselves rather than the number of rows: a grid of charts, a page of cards -that each do layout work. +`RenderWave` wraps the reveal hook in a component. Everything mounts +eventually, nothing is windowed away. Reach for it when the cost is the +components themselves rather than the number of rows: a grid of charts, a page +of cards that each do layout work. -`VirtualRenderWave` adds windowing. Row offsets come from a prefix-sum cache -with binary search, so the scroll math holds up past 100,000 rows. Heights can -be uniform or measured per row. This is the one you want for a long list. +`VirtualRenderWave` puts the two hooks together and adds the list chrome. Row +offsets come from a prefix-sum cache with binary search, so the scroll math +holds up past 100,000 rows. Heights can be uniform or measured per row. This is +the one you want for a long list. Beyond that: dynamic row heights measured with a ResizeObserver and cached across unmounts, skeleton placeholders, sticky group headers, keyboard @@ -88,7 +95,14 @@ length](https://renderwave.sudo-ezekiel.com/recipes/batch-size/) on a virtualized list, and [why `getItemKey` matters](https://renderwave.sudo-ezekiel.com/recipes/stable-keys/) as soon as the list can sort or filter. -## The hook +If you would rather keep a small `batchSize`, set `revealMode="viewport"`. The +wave then reveals the rows inside the rendered window instead of counting +forward from the top, and a revealed row stays revealed, so the screen fills +after a few batches no matter where the user has scrolled. + +## The hooks + +### `useRenderWave` ```tsx import { useRenderWave } from "react-render-wave"; @@ -116,6 +130,60 @@ It returns `count`, `indexes`, `isComplete` and `reset`. The hook clamps when `items` shrinks, resumes when it grows, and never yields an index past the end of the list, so `items[i]` is always defined. +### `useVirtualWindow` + +The hook renders nothing and owns no styles. You give it a count and an +estimated row size; it gives you a ref for the scroll container, a ref per +item for measurement, and the items to render with their offsets. + +```tsx +import { useCallback } from "react"; +import { useVirtualWindow } from "react-render-wave"; + +function Feed({ posts }: { posts: Post[] }) { + const getItemKey = useCallback((i: number) => posts[i].id, [posts]); + const { scrollRef, measureRef, virtualItems, totalSize } = useVirtualWindow({ + count: posts.length, + estimateSize: 80, + getItemKey, + }); + + return ( +
+
+ {virtualItems.map((item) => ( +
+ +
+ ))} +
+
+ ); +} +``` + +Three parts have to line up. The scroll container needs a constrained height +and `overflow: auto`, and takes `scrollRef` (or hand the hook an element you +already own through `getScrollElement`). The element inside it is the sizer; +give it `position: relative` and a height of `totalSize` so the scrollbar +reflects the whole list. Each item is positioned absolutely at `item.offset` +and takes `measureRef(item.index)`, which watches the element with a +ResizeObserver and corrects the offsets below it when it turns out taller or +shorter than the estimate. Skip `measureRef` when every row is the same +height. + +Memoize `getItemKey` on the data. Measurements are stored by key, so a reorder +carries each measured height with its item, but a new function identity is +read as a reorder and costs one rebuild of the offsets. + +The first render is derived only from `count`, `estimateSize`, `overscan`, +`scrollMargin`, `getItemKey` and the `initial*` options, so server markup and +the first client render agree. + ## API ### `useRenderWave(options)` @@ -131,6 +199,42 @@ of the list, so `items[i]` is always defined. Returns `{ count, indexes, isComplete, reset }`. +### `useVirtualWindow(options)` + +| Option | Default | Description | +| --- | --- | --- | +| `count` | required | Number of items in the list. | +| `estimateSize` | required | Size in pixels used for an item until it is measured. A value that is not positive and finite falls back to `1`. | +| `overscan` | `5` | Extra items rendered above and below the viewport. Clamped to a non-negative whole number. | +| `getItemKey` | item index | `(index) => string \| number`. Measurements are stored by key, so a reorder keeps each item's measured size. Memoize it on the data. | +| `getScrollElement` | – | Supply the scroll container from a ref you already own instead of using `scrollRef`. | +| `initialScrollOffset` | `0` | Scroll offset for the first render. Read once. | +| `initialScrollIndex` | – | Index to open at. Wins over `initialScrollOffset`. Read once. | +| `initialViewportSize` | `400` | Viewport size used until the container is measured. Read once. | +| `scrollMargin` | `0` | Pixels between the container's content origin and item 0, for an in-flow header or toolbar above the sizer. | +| `measureSize` | `el => el.offsetHeight` | How an item element is measured. Use `el => el.getBoundingClientRect().height` for fractional heights, such as table rows with collapsed borders. | +| `onScroll` | – | Called with the current scroll offset, at most once per animation frame. Programmatic scrolls and measurement corrections report through it too. | +| `onRangeChange` | – | Called whenever any of the four range bounds changes. | + +Returns a `UseVirtualWindowResult`: + +| Field | Description | +| --- | --- | +| `scrollRef` | Ref callback for the scroll container. | +| `measureRef(index)` | Ref callback for the item element at `index`. Stable per index. | +| `virtualItems` | The items to render: `{ index, key, offset, size }[]`. `size` is the measured size, or the estimate until measured. | +| `start`, `end` | Rendered range. `end` is exclusive. | +| `visibleStart`, `visibleEnd` | Indexes intersecting the viewport. `visibleEnd` is exclusive. | +| `totalSize` | Size of all items together, for the sizer element. | +| `scrollOffset` | Current scroll offset of the container. | +| `viewportSize` | Current size of the viewport. | +| `offsetOf(index)` | Pixel offset of the top of an item. | +| `sizeOf(index)` | Measured size of an item, or the estimate. | +| `indexAt(offset)` | Index of the item whose span contains a pixel offset. | +| `scrollToIndex(index, options?)` | Scroll so the item is aligned in the viewport. `options` is `{ align?, behavior? }`; `align` is `"start"` (default), `"center"`, `"end"` or `"auto"`, which only scrolls if the item is not already fully visible. `behavior` defaults to `"auto"`. Out of range indexes clamp to the list; `NaN` is ignored. | +| `scrollToOffset(offset, options?)` | Scroll to a pixel offset. `options` is `{ behavior? }`. `NaN` is ignored. | +| `getScrollElement()` | The scroll container, or `null` before it is attached. | + ### `` | Prop | Default | Description | @@ -155,30 +259,60 @@ Returns `{ count, indexes, isComplete, reset }`. | `interval` | `50` | Delay in milliseconds between waves. | | `overscan` | `5` | Extra rows rendered above and below the viewport. | | `startIndex` | `0` | Index of the first item to reveal. | +| `revealMode` | `"sequential"` | Which rows the wave reveals. `"sequential"` counts forward from `startIndex` regardless of the scroll position. `"viewport"` reveals the rows inside the rendered window in batches and never re-hides a revealed row, so a small `batchSize` still fills the screen on a long list. | | `renderSkeleton` | – | Rendered in place of items the wave has not reached yet. | -| `getItemKey` | item index | Stable key per item. | +| `getItemKey` | item index | `(item, index) => ItemKey`, where `ItemKey` is `string \| number`. Stable key per item. | | `scrollToIndex` | – | Scrolls to the index whenever the value changes. | -| `outerElement` | – | Tag name or component for the scroll container. | -| `innerElement` | – | Tag name or component for the inner sizer. | -| `transition` | `false` | Fade newly revealed items in. | +| `initialScrollOffset` | – | Pixel offset for the first render, read once. The first paint and the server markup already show that window. | +| `initialScrollIndex` | – | Index to open at, read once. Wins over `initialScrollOffset`, and over a controlled `scrollToIndex` at mount. Corrected once the rows above it are measured. | +| `outerElement` | `"div"` | Tag name or `WrapperComponent` for the scroll container. See the note below. | +| `innerElement` | `"div"` | Tag name or `WrapperComponent` for the inner sizer. See the note below. | +| `transition` | `false` | Fade newly revealed items in. The fade is skipped when the user prefers reduced motion. | | `snapToBatch` | `false` | Align to the nearest batch boundary after scrolling stops. Assumes fixed heights. | -| `onEndReached` | – | Called once each time the user reaches the end of the scroll area. | +| `onEndReached` | – | Called once each time the user reaches the end of the scroll area, including when the content is shorter than the viewport. | | `endReachedThreshold` | `10` | Distance in pixels from the bottom that counts as the end. | | `onScroll` | – | Called with the current `scrollTop`, at most once per animation frame. | -| `keyboardNavigation` | `false` | Enable ArrowUp/ArrowDown, PageUp/PageDown, Home and End. | +| `onRangeChange` | – | Called after commit whenever the rendered or visible range changes, with `{ start, end, visibleStart, visibleEnd }`. `end` and `visibleEnd` are exclusive. | +| `keyboardNavigation` | `false` | Enable ArrowUp/ArrowDown, PageUp/PageDown, Home and End. Keys are only taken when the scroll container itself has focus, so an input or select inside a row keeps its own key handling. | | `renderStickyHeader` | – | Renders a sticky header for the group of the topmost visible item. | | `groupByKey` | – | Property name or function that yields an item's group label. | | `className`, `style` | – | Passed to the scroll container. | | `ariaLabel` | – | Accessible label for the scroll container. | +A custom `outerElement` or `innerElement` receives `WrapperProps` and must +spread every prop onto the DOM node it renders, `ref` included, because the +list scrolls and measures through that ref. On React 19 the ref arrives as an +ordinary prop. On React 18 a plain function component never receives it, so +wrap the component in `forwardRef` and attach the forwarded ref to the node. +A wrapper that drops the ref leaves the list unable to scroll or measure; the +only sign is a `console.error` in development naming the wrapper. + +```tsx +import { forwardRef } from "react"; +import type { WrapperProps } from "react-render-wave"; + +const Scroller = forwardRef(function Scroller( + { children, ...rest }, + ref +) { + return ( +
+ {children} +
+ ); +}); + +; +``` + ### Imperative handle Attach a ref to `VirtualRenderWave` to get a `VirtualRenderWaveHandle`: | Method | Description | | --- | --- | -| `scrollTo(index, behavior?)` | Scroll so the item at `index` sits at the top of the viewport. | -| `scrollToOffset(px, behavior?)` | Scroll to a pixel offset. | +| `scrollTo(index, options?)` | Scroll to the item at `index`. `options` is a `ScrollBehavior` string or `{ align?, behavior? }`. `align` is `"start"` (default), `"center"`, `"end"` or `"auto"`, which only scrolls if the item is not already fully visible. `behavior` defaults to `"smooth"`. | +| `scrollToOffset(px, behavior?)` | Scroll to a pixel offset. `behavior` defaults to `"smooth"`. | | `getVisibleIndexes()` | Indexes currently rendered and revealed. | | `getScrollElement()` | The scrollable outer element, or `null` before mount. | @@ -197,7 +331,8 @@ npm run demo ## Roadmap - Horizontal virtualization -- Table layout with expandable rows +- Table layout with expandable rows. `useVirtualWindow` gets you most of the + way to a virtualized table today; the built-in layout is still to come. ## Contributing @@ -205,12 +340,17 @@ Contributions are welcome. ```bash npm install -npm test # vitest -npm run demo # local playground -npm run build # dist (ESM + CJS + types) +npm test # vitest +npm run demo # local playground +npm run build # dist (ESM + CJS + types) npm run typecheck +npm run check:pkg # publint + arethetypeswrong against the packed tarball ``` +CI runs the same checks on Node 20 and 22, and a separate job reinstalls +React 18 and runs the typecheck and tests against it, so a change that only +works on React 19 fails there. + ## Acknowledgements Thanks to [@sequencemedia](https://github.com/sequencemedia) for helping squash