@vielzeug/scroll 1.1.6 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/dist/_alignment.cjs +2 -0
- package/dist/_alignment.cjs.map +1 -0
- package/dist/_alignment.d.ts +3 -0
- package/dist/_alignment.d.ts.map +1 -0
- package/dist/_alignment.js +2 -0
- package/dist/_alignment.js.map +1 -0
- package/dist/_validation.cjs +2 -0
- package/dist/_validation.cjs.map +1 -0
- package/dist/_validation.d.ts +8 -0
- package/dist/_validation.d.ts.map +1 -0
- package/dist/_validation.js +2 -0
- package/dist/_validation.js.map +1 -0
- package/dist/dom-virtual-list.cjs +1 -1
- package/dist/dom-virtual-list.cjs.map +1 -1
- package/dist/dom-virtual-list.d.ts.map +1 -1
- package/dist/dom-virtual-list.js +1 -1
- package/dist/dom-virtual-list.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/grid-virtualizer.cjs +1 -1
- package/dist/grid-virtualizer.cjs.map +1 -1
- package/dist/grid-virtualizer.d.ts +3 -4
- package/dist/grid-virtualizer.d.ts.map +1 -1
- package/dist/grid-virtualizer.js +1 -1
- package/dist/grid-virtualizer.js.map +1 -1
- package/dist/grouped-virtualizer.cjs +1 -1
- package/dist/grouped-virtualizer.cjs.map +1 -1
- package/dist/grouped-virtualizer.d.ts +9 -14
- package/dist/grouped-virtualizer.d.ts.map +1 -1
- package/dist/grouped-virtualizer.js +1 -1
- package/dist/grouped-virtualizer.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/reactive.cjs +1 -1
- package/dist/reactive.cjs.map +1 -1
- package/dist/reactive.d.ts +2 -5
- package/dist/reactive.d.ts.map +1 -1
- package/dist/reactive.js +1 -1
- package/dist/reactive.js.map +1 -1
- package/dist/scroll.cjs +1 -1
- package/dist/scroll.cjs.map +1 -1
- package/dist/scroll.iife.js +1 -1
- package/dist/scroll.iife.js.map +1 -1
- package/dist/scroll.js +1 -1
- package/dist/scroll.js.map +1 -1
- package/dist/virtualizer.cjs +1 -1
- package/dist/virtualizer.cjs.map +1 -1
- package/dist/virtualizer.d.ts +9 -17
- package/dist/virtualizer.d.ts.map +1 -1
- package/dist/virtualizer.js +1 -1
- package/dist/virtualizer.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @vielzeug/scroll
|
|
2
2
|
|
|
3
|
-
> Lightweight, framework-agnostic virtual list engine with variable heights, sticky headers, grid support, and
|
|
3
|
+
> Lightweight, framework-agnostic virtual list engine with variable heights, sticky headers, grid support, and optional reactive integration.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@vielzeug/scroll) [](https://opensource.org/licenses/MIT)
|
|
6
6
|
|
|
@@ -40,7 +40,7 @@ const virt = createVirtualizer(scrollEl, {
|
|
|
40
40
|
estimateSize: 36,
|
|
41
41
|
onChange: ({ items, totalSize }) => {
|
|
42
42
|
listEl.style.height = `${totalSize}px`;
|
|
43
|
-
listEl.
|
|
43
|
+
listEl.replaceChildren();
|
|
44
44
|
|
|
45
45
|
for (const item of items) {
|
|
46
46
|
const row = document.createElement('div');
|
|
@@ -64,6 +64,11 @@ import { createDomVirtualList } from '@vielzeug/scroll';
|
|
|
64
64
|
|
|
65
65
|
type Option = { label: string; value: string };
|
|
66
66
|
|
|
67
|
+
const dropdownEl = document.querySelector<HTMLElement>('.dropdown')!;
|
|
68
|
+
const listEl = document.querySelector<HTMLElement>('.list')!;
|
|
69
|
+
const options: Option[] = [{ label: 'Ada Lovelace', value: 'ada' }];
|
|
70
|
+
const focusedIndex = 0;
|
|
71
|
+
|
|
67
72
|
const domList = createDomVirtualList<Option>({
|
|
68
73
|
estimateSize: 36,
|
|
69
74
|
getItemKey: (_, opt) => opt.value,
|
|
@@ -91,6 +96,9 @@ domList.dispose();
|
|
|
91
96
|
```ts
|
|
92
97
|
import { createVirtualScroller } from '@vielzeug/scroll';
|
|
93
98
|
|
|
99
|
+
type Option = { label: string; value: string };
|
|
100
|
+
|
|
101
|
+
const options: Option[] = [{ label: 'Ada Lovelace', value: 'ada' }];
|
|
94
102
|
const list = createVirtualScroller<Option>(document.getElementById('root')!, {
|
|
95
103
|
estimateSize: 36,
|
|
96
104
|
render: ({ items, listEl, recycle }) => {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_alignment.cjs","names":[],"sources":["../src/_alignment.ts"],"sourcesContent":["export type ScrollAlignment = 'auto' | 'center' | 'end' | 'start';\n\nexport function alignOffset(\n itemStart: number,\n itemEnd: number,\n itemSize: number,\n currentOffset: number,\n viewportSize: number,\n align: ScrollAlignment,\n): number | null {\n if (align === 'start') return itemStart;\n\n if (align === 'end') return itemEnd - viewportSize;\n\n if (align === 'center') return itemStart - (viewportSize - itemSize) / 2;\n\n if (itemStart >= currentOffset && itemEnd <= currentOffset + viewportSize) return null;\n\n return itemStart < currentOffset ? itemStart : itemEnd - viewportSize;\n}\n"],"mappings":"AAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACe,CASf,OARI,IAAU,QAAgB,EAE1B,IAAU,MAAc,EAAU,EAElC,IAAU,SAAiB,GAAa,EAAe,GAAY,EAEnE,GAAa,GAAiB,GAAW,EAAgB,EAAqB,KAE3E,EAAY,EAAgB,EAAY,EAAU,CAC3D"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export type ScrollAlignment = 'auto' | 'center' | 'end' | 'start';
|
|
2
|
+
export declare function alignOffset(itemStart: number, itemEnd: number, itemSize: number, currentOffset: number, viewportSize: number, align: ScrollAlignment): number | null;
|
|
3
|
+
//# sourceMappingURL=_alignment.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_alignment.d.ts","sourceRoot":"","sources":["../src/_alignment.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,QAAQ,GAAG,KAAK,GAAG,OAAO,CAAC;AAElE,wBAAgB,WAAW,CACzB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,eAAe,GACrB,MAAM,GAAG,IAAI,CAUf"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_alignment.js","names":[],"sources":["../src/_alignment.ts"],"sourcesContent":["export type ScrollAlignment = 'auto' | 'center' | 'end' | 'start';\n\nexport function alignOffset(\n itemStart: number,\n itemEnd: number,\n itemSize: number,\n currentOffset: number,\n viewportSize: number,\n align: ScrollAlignment,\n): number | null {\n if (align === 'start') return itemStart;\n\n if (align === 'end') return itemEnd - viewportSize;\n\n if (align === 'center') return itemStart - (viewportSize - itemSize) / 2;\n\n if (itemStart >= currentOffset && itemEnd <= currentOffset + viewportSize) return null;\n\n return itemStart < currentOffset ? itemStart : itemEnd - viewportSize;\n}\n"],"mappings":"AAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACe,CASf,OARI,IAAU,QAAgB,EAE1B,IAAU,MAAc,EAAU,EAElC,IAAU,SAAiB,GAAa,EAAe,GAAY,EAEnE,GAAa,GAAiB,GAAW,EAAgB,EAAqB,KAE3E,EAAY,EAAgB,EAAY,EAAU,CAC3D"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs");function t(t,n){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e.ScrollConfigurationError(`${n} must be a finite non-negative integer.`);return t}function n(t,n){if(!Number.isFinite(t)||t<0)throw new e.ScrollConfigurationError(`${n} must be a finite non-negative number.`);return t}function r(t,n){if(!Number.isFinite(t)||t<=0||t>1e7)throw new e.ScrollConfigurationError(`${n} must be a finite positive number no greater than 10000000.`);return t}function i(n,r=`overscan`){if(typeof n==`number`){t(n,r);return}if(typeof n!=`object`||!n||Array.isArray(n))throw new e.ScrollConfigurationError(`${r} must be a finite non-negative integer or an overscan object.`);n.start!==void 0&&t(n.start,`${r}.start`),n.end!==void 0&&t(n.end,`${r}.end`)}exports.requireNonNegativeInteger=t,exports.requireNonNegativeNumber=n,exports.requirePositiveNumber=r,exports.validateOverscan=i;
|
|
2
|
+
//# sourceMappingURL=_validation.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_validation.cjs","names":[],"sources":["../src/_validation.ts"],"sourcesContent":["import { ScrollConfigurationError } from './errors';\n\nexport function requireNonNegativeInteger(value: number, name: string): number {\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative integer.`);\n }\n\n return value;\n}\n\nexport function requireNonNegativeNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value < 0) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative number.`);\n }\n\n return value;\n}\n\nexport function requirePositiveNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0 || value > 1e7) {\n throw new ScrollConfigurationError(`${name} must be a finite positive number no greater than 10000000.`);\n }\n\n return value;\n}\n\nexport function validateOverscan(overscan: number | { end?: number; start?: number }, name = 'overscan'): void {\n if (typeof overscan === 'number') {\n requireNonNegativeInteger(overscan, name);\n\n return;\n }\n\n if (overscan === null || typeof overscan !== 'object' || Array.isArray(overscan)) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative integer or an overscan object.`);\n }\n\n if (overscan.start !== undefined) requireNonNegativeInteger(overscan.start, `${name}.start`);\n\n if (overscan.end !== undefined) requireNonNegativeInteger(overscan.end, `${name}.end`);\n}\n"],"mappings":"gCAEA,SAAgB,EAA0B,EAAe,EAAsB,CAC7E,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,EACjE,MAAM,IAAI,EAAA,yBAAyB,GAAG,EAAK,wCAAwC,EAGrF,OAAO,CACT,CAEA,SAAgB,EAAyB,EAAe,EAAsB,CAC5E,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,EAAQ,EACrC,MAAM,IAAI,EAAA,yBAAyB,GAAG,EAAK,uCAAuC,EAGpF,OAAO,CACT,CAEA,SAAgB,EAAsB,EAAe,EAAsB,CACzE,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,GAAS,GAAK,EAAQ,IACnD,MAAM,IAAI,EAAA,yBAAyB,GAAG,EAAK,4DAA4D,EAGzG,OAAO,CACT,CAEA,SAAgB,EAAiB,EAAqD,EAAO,WAAkB,CAC7G,GAAI,OAAO,GAAa,SAAU,CAChC,EAA0B,EAAU,CAAI,EAExC,MACF,CAEA,GAAyB,OAAO,GAAa,WAAzC,GAAqD,MAAM,QAAQ,CAAQ,EAC7E,MAAM,IAAI,EAAA,yBAAyB,GAAG,EAAK,8DAA8D,EAGvG,EAAS,QAAU,IAAA,IAAW,EAA0B,EAAS,MAAO,GAAG,EAAK,OAAO,EAEvF,EAAS,MAAQ,IAAA,IAAW,EAA0B,EAAS,IAAK,GAAG,EAAK,KAAK,CACvF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare function requireNonNegativeInteger(value: number, name: string): number;
|
|
2
|
+
export declare function requireNonNegativeNumber(value: number, name: string): number;
|
|
3
|
+
export declare function requirePositiveNumber(value: number, name: string): number;
|
|
4
|
+
export declare function validateOverscan(overscan: number | {
|
|
5
|
+
end?: number;
|
|
6
|
+
start?: number;
|
|
7
|
+
}, name?: string): void;
|
|
8
|
+
//# sourceMappingURL=_validation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_validation.d.ts","sourceRoot":"","sources":["../src/_validation.ts"],"names":[],"mappings":"AAEA,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAM7E;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAM5E;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAMzE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,IAAI,SAAa,GAAG,IAAI,CAc7G"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ScrollConfigurationError as e}from"./errors.js";function t(t,n){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e(`${n} must be a finite non-negative integer.`);return t}function n(t,n){if(!Number.isFinite(t)||t<0)throw new e(`${n} must be a finite non-negative number.`);return t}function r(t,n){if(!Number.isFinite(t)||t<=0||t>1e7)throw new e(`${n} must be a finite positive number no greater than 10000000.`);return t}function i(n,r=`overscan`){if(typeof n==`number`){t(n,r);return}if(typeof n!=`object`||!n||Array.isArray(n))throw new e(`${r} must be a finite non-negative integer or an overscan object.`);n.start!==void 0&&t(n.start,`${r}.start`),n.end!==void 0&&t(n.end,`${r}.end`)}export{t as requireNonNegativeInteger,n as requireNonNegativeNumber,r as requirePositiveNumber,i as validateOverscan};
|
|
2
|
+
//# sourceMappingURL=_validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_validation.js","names":[],"sources":["../src/_validation.ts"],"sourcesContent":["import { ScrollConfigurationError } from './errors';\n\nexport function requireNonNegativeInteger(value: number, name: string): number {\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative integer.`);\n }\n\n return value;\n}\n\nexport function requireNonNegativeNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value < 0) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative number.`);\n }\n\n return value;\n}\n\nexport function requirePositiveNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0 || value > 1e7) {\n throw new ScrollConfigurationError(`${name} must be a finite positive number no greater than 10000000.`);\n }\n\n return value;\n}\n\nexport function validateOverscan(overscan: number | { end?: number; start?: number }, name = 'overscan'): void {\n if (typeof overscan === 'number') {\n requireNonNegativeInteger(overscan, name);\n\n return;\n }\n\n if (overscan === null || typeof overscan !== 'object' || Array.isArray(overscan)) {\n throw new ScrollConfigurationError(`${name} must be a finite non-negative integer or an overscan object.`);\n }\n\n if (overscan.start !== undefined) requireNonNegativeInteger(overscan.start, `${name}.start`);\n\n if (overscan.end !== undefined) requireNonNegativeInteger(overscan.end, `${name}.end`);\n}\n"],"mappings":"uDAEA,SAAgB,EAA0B,EAAe,EAAsB,CAC7E,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,EACjE,MAAM,IAAI,EAAyB,GAAG,EAAK,wCAAwC,EAGrF,OAAO,CACT,CAEA,SAAgB,EAAyB,EAAe,EAAsB,CAC5E,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,EAAQ,EACrC,MAAM,IAAI,EAAyB,GAAG,EAAK,uCAAuC,EAGpF,OAAO,CACT,CAEA,SAAgB,EAAsB,EAAe,EAAsB,CACzE,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,GAAS,GAAK,EAAQ,IACnD,MAAM,IAAI,EAAyB,GAAG,EAAK,4DAA4D,EAGzG,OAAO,CACT,CAEA,SAAgB,EAAiB,EAAqD,EAAO,WAAkB,CAC7G,GAAI,OAAO,GAAa,SAAU,CAChC,EAA0B,EAAU,CAAI,EAExC,MACF,CAEA,GAAyB,OAAO,GAAa,WAAzC,GAAqD,MAAM,QAAQ,CAAQ,EAC7E,MAAM,IAAI,EAAyB,GAAG,EAAK,8DAA8D,EAGvG,EAAS,QAAU,IAAA,IAAW,EAA0B,EAAS,MAAO,GAAG,EAAK,OAAO,EAEvF,EAAS,MAAQ,IAAA,IAAW,EAA0B,EAAS,IAAK,GAAG,EAAK,KAAK,CACvF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");require("./_utils.cjs");const t=require("./virtualizer.cjs");function
|
|
1
|
+
const e=require("./errors.cjs");require("./_utils.cjs");const t=require("./_validation.cjs"),n=require("./virtualizer.cjs");function r(){let e=new Map,t=new Map,n=[],r=!1;return{acquire(i,a){if(!r)return a();let o=e.get(i);if(o)return t.set(i,o),o;let s=n.pop()??a();return t.set(i,s),s},beginCycle(){t=new Map,r=!0},clear(){for(let t of e.values())t.remove();e.clear(),t.clear(),n.length=0,r=!1},endCycle(){if(r){r=!1;for(let[r,i]of e)t.has(r)||(i.remove(),n.push(i));e=t}}}}function i(i){if(typeof i.estimateSize==`number`&&t.requirePositiveNumber(i.estimateSize,`estimateSize`),i.gap!==void 0&&t.requireNonNegativeInteger(i.gap,`gap`),i.overscan!==void 0&&t.validateOverscan(i.overscan),i.stickToBottom!==void 0&&typeof i.stickToBottom!=`boolean`){if(i.stickToBottom===null||Array.isArray(i.stickToBottom))throw new e.ScrollConfigurationError(`stickToBottom must be a boolean or options object.`);i.stickToBottom.threshold!==void 0&&t.requireNonNegativeNumber(i.stickToBottom.threshold,`stickToBottom.threshold`)}let a=[],o=!1,s=new AbortController,c=i.listElement,l=r(),u=null;function d(e){let t=a[e];return t!==void 0&&i.getItemKey?i.getItemKey(e,t):e}function f(e){if(i.estimateSize===void 0)return 36;if(typeof i.estimateSize==`number`)return i.estimateSize;let t=a[e];return t===void 0?36:i.estimateSize(e,t)}function p(e){i.horizontal?(c.style.height=``,c.style.width=`${e}px`):(c.style.height=`${e}px`,c.style.width=``)}function m(t){let n=a[t.index];if(n===void 0)throw new e.ScrollRangeError(`toRenderItem: index ${t.index} is out of range (currentItems.length=${a.length})`);return{...t,data:n}}function h(e){p(e.totalSize),l.beginCycle();try{i.render({items:e.items.map(m),listEl:c,recycle:(e,t)=>l.acquire(e,t),stickyItems:e.stickyItems.map(m),totalSize:e.totalSize})}finally{l.endCycle()}}function g(){l.clear(),i.clear?i.clear(c):c.textContent=``,c.style.height=``,c.style.width=``,c.style.position=``,c.style.contain=``}function _(){let e=i.stickToBottom;return e?e===!0?{enabled:!0,threshold:48}:{enabled:e.enabled??!0,threshold:e.threshold??48}:{enabled:!1,threshold:48}}function v(){let e=n.createVirtualizer(i.scrollElement,{count:a.length,estimateSize:f,gap:i.gap,getItemKey:d,horizontal:i.horizontal,measurementCache:i.measurementCache,onChange:h,overscan:i.overscan??3,sticky:i.sticky?e=>{let t=a[e];return t!==void 0&&i.sticky(e,t)}:void 0});return u=e,c.style.position=`relative`,c.style.contain=`layout`,e}function y(){o||(o=!0,s.abort(),u?.dispose(),u=null,g())}return{get count(){return u?.count??0},get disposalSignal(){return s.signal},dispose:y,get disposed(){return o},invalidate(){o||u?.invalidate()},isAtEnd(e){return u?.isAtEnd(e)??!0},get isScrolling(){return u?.isScrolling??!1},get items(){return u?.items??[]},measure(e,t){o||u?.measure(e,t)},measureBatch(e){o||u?.measureBatch(e)},measureEl(e,t){return o?()=>{}:u?.measureEl(e,t)??(()=>{})},refresh(){o||u?.refresh()},get scrollOffset(){return u?.scrollOffset??0},scrollToBottom(e){o||u?.scrollToBottom(e)},scrollToIndex(e,t){o||u?.scrollToIndex(e,t)},scrollToOffset(e,t){o||u?.scrollToOffset(e,t)},scrollToTop(e){o||u?.scrollToTop(e)},setItems(e){if(o)return;let t=_(),n=t.enabled&&(u?.isAtEnd(t.threshold)??!0);if(a=e,e.length===0){u?.dispose(),u=null,g();return}if(!u){let e=v();n&&e.scrollToBottom();return}let r=e.length!==u.count;u.update({count:e.length}),r?i.getItemKey||u.invalidate():i.getItemKey?u.refresh():u.invalidate(),n&&u.scrollToBottom()},get stickyItems(){return u?.stickyItems??[]},[Symbol.dispose]:y,get totalSize(){return u?.totalSize??0}}}function a(e,t){let n=document.createElement(`div`);n.style.cssText=t.horizontal?`overflow: auto hidden; width: 100%; height: 100%;`:`overflow: hidden auto; width: 100%; height: 100%;`,t.containerClass&&(n.className=t.containerClass);let r=document.createElement(`div`);n.appendChild(r),e.appendChild(n);let a;try{a=i({...t,listElement:r,scrollElement:n})}catch(e){throw n.remove(),e}let o=a.dispose.bind(a);return Object.assign(a,{dispose(){o(),n.remove()},[Symbol.dispose](){o(),n.remove()}})}exports.createDomVirtualList=i,exports.createVirtualScroller=a;
|
|
2
2
|
//# sourceMappingURL=dom-virtual-list.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom-virtual-list.cjs","names":[],"sources":["../src/dom-virtual-list.ts"],"sourcesContent":["import { DEFAULT_ESTIMATE_SIZE, DEFAULT_OVERSCAN, type MeasurementCache, type Overscan } from './_utils';\nimport { ScrollRangeError } from './errors';\nimport {\n createVirtualizer,\n type ScrollToIndexOptions,\n type VirtualItem,\n type Virtualizer,\n type VirtualizerState,\n type VirtualKey,\n} from './virtualizer';\n\nexport type {\n MeasurementCache,\n Overscan,\n ScrollToIndexOptions,\n VirtualItem,\n Virtualizer,\n VirtualizerState,\n VirtualKey,\n};\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/** A `VirtualItem` enriched with the corresponding data record. */\nexport type VirtualRenderItem<T> = VirtualItem & { readonly data: T };\n\n/**\n * Recycle a DOM node by key. If the pool has a live node for `key`, it is\n * returned and reused; otherwise `create()` is called to produce a new one.\n */\nexport type RecycleFn = (key: VirtualKey, create: () => HTMLElement) => HTMLElement;\n\nexport type DomVirtualListRenderArgs<T> = {\n items: Array<VirtualRenderItem<T>>;\n listEl: HTMLElement;\n recycle: RecycleFn;\n /** Sticky items from the underlying virtualizer, enriched with data. */\n stickyItems: Array<VirtualRenderItem<T>>;\n totalSize: number;\n};\n\nexport type StickToBottomOptions = {\n /** Enable/disable the behavior. Default: `true` once this object is provided. */\n enabled?: boolean;\n /**\n * Distance in pixels from the end still considered \"at the end\" — the bottom edge in\n * vertical mode, the trailing edge in horizontal mode. Default: `48`.\n */\n threshold?: number;\n};\n\nexport type DomVirtualListOptions<T> = {\n /** Custom teardown that clears listEl. Defaults to `listEl.textContent = ''`. */\n clear?: (listEl: HTMLElement) => void;\n estimateSize?: number | ((index: number, item: T) => number);\n gap?: number;\n getItemKey?: (index: number, item: T) => VirtualKey;\n horizontal?: boolean;\n listElement: HTMLElement;\n /** External measurement cache for scroll restoration. */\n measurementCache?: MeasurementCache;\n overscan?: Overscan;\n render: (args: DomVirtualListRenderArgs<T>) => void;\n scrollElement: HTMLElement | Window;\n /**\n * Auto-scroll to the end after `setItems()` whenever the list was already at (or near) the\n * end just before the update — the chat \"stick to bottom on new message\" pattern. Fires on\n * *any* update while at the end, not just growth, so it also follows a streaming last\n * item that grows in place without changing `items.length`. Does nothing while the user\n * has scrolled away from the end. Pass `true` for defaults, or an options object.\n */\n stickToBottom?: boolean | StickToBottomOptions;\n /** Mark items as sticky headers. Receives the item index and the item data. */\n sticky?: (index: number, item: T) => boolean;\n};\n\n/**\n * R11: Controller extends Virtualizer so all methods (scrollToIndex, refresh,\n * scrollToOffset, etc.) are accessible directly on the controller without\n * needing to unwrap an inner virtualizer handle.\n *\n * `prepend` and `update` are omitted — use `setItems()` for item updates and\n * there is no direct `prepend` concept in DomVirtualList.\n */\nexport type DomVirtualListController<T> = Omit<Virtualizer, 'prepend' | 'update'> & {\n setItems: (items: T[]) => void;\n};\n\nexport type VirtualScrollerOptions<T> = Omit<DomVirtualListOptions<T>, 'listElement' | 'scrollElement'> & {\n /** Additional CSS class names on the generated scroll container. */\n containerClass?: string;\n};\n\n// ─── Node pool ────────────────────────────────────────────────────────────────\n\nfunction createNodePool() {\n let live = new Map<VirtualKey, HTMLElement>();\n let nextLive = new Map<VirtualKey, HTMLElement>();\n const stale: HTMLElement[] = [];\n let inCycle = false;\n\n return {\n acquire(key: VirtualKey, create: () => HTMLElement): HTMLElement {\n if (!inCycle) return create();\n\n const existing = live.get(key);\n\n if (existing) {\n nextLive.set(key, existing);\n\n return existing;\n }\n\n const node = stale.pop() ?? create();\n\n nextLive.set(key, node);\n\n return node;\n },\n\n beginCycle(): void {\n nextLive = new Map();\n inCycle = true;\n },\n\n clear(): void {\n for (const node of live.values()) node.remove();\n\n live.clear();\n nextLive.clear();\n stale.length = 0;\n inCycle = false;\n },\n\n endCycle(): void {\n if (!inCycle) return;\n\n inCycle = false;\n\n for (const [key, node] of live) {\n if (!nextLive.has(key)) {\n node.remove();\n stale.push(node);\n }\n }\n\n live = nextLive;\n },\n };\n}\n\n// ─── Implementation ────────────────────────────────────────────────────────────\n\nexport function createDomVirtualList<T>(options: DomVirtualListOptions<T>): DomVirtualListController<T> {\n let currentItems: T[] = [];\n let isDestroyed = false;\n const ac = new AbortController();\n const listEl = options.listElement;\n\n // Pool must be declared before virtualizer since handleChange (passed as onChange)\n // is invoked during createVirtualizer initialization via computeVisible.\n const pool = createNodePool();\n\n // Virtualizer is lazily created on the first non-empty setItems call.\n let virtualizer: Virtualizer | null = null;\n\n function resolveKey(index: number): VirtualKey {\n const item = currentItems[index];\n\n if (item !== undefined && options.getItemKey) return options.getItemKey(index, item);\n\n return index;\n }\n\n function resolveEstimate(index: number): number {\n if (options.estimateSize === undefined) return DEFAULT_ESTIMATE_SIZE;\n\n if (typeof options.estimateSize === 'number') return options.estimateSize;\n\n const item = currentItems[index];\n\n return item !== undefined ? options.estimateSize(index, item) : DEFAULT_ESTIMATE_SIZE;\n }\n\n function applyListSize(totalSize: number): void {\n if (options.horizontal) {\n listEl.style.height = '';\n listEl.style.width = `${totalSize}px`;\n } else {\n listEl.style.height = `${totalSize}px`;\n listEl.style.width = '';\n }\n }\n\n /**\n * R10: Throw rather than silently produce `undefined as T`.\n * This catches bugs where `vi.index` is out of range for `currentItems`.\n */\n function toRenderItem(vi: VirtualItem): VirtualRenderItem<T> {\n const data = currentItems[vi.index];\n\n if (data === undefined) {\n throw new ScrollRangeError(\n `toRenderItem: index ${vi.index} is out of range (currentItems.length=${currentItems.length})`,\n );\n }\n\n return { ...vi, data };\n }\n\n function handleChange(state: VirtualizerState): void {\n applyListSize(state.totalSize);\n\n pool.beginCycle();\n\n // R5: try/finally ensures endCycle() runs even if render() throws, keeping\n // the pool in a consistent state.\n try {\n options.render({\n items: state.items.map(toRenderItem),\n listEl,\n recycle: (key, create) => pool.acquire(key, create),\n stickyItems: state.stickyItems.map(toRenderItem),\n totalSize: state.totalSize,\n });\n } finally {\n pool.endCycle();\n }\n }\n\n function clearAndReset(): void {\n pool.clear();\n\n if (options.clear) {\n options.clear(listEl);\n } else {\n listEl.textContent = '';\n }\n\n listEl.style.height = '';\n listEl.style.width = '';\n listEl.style.position = '';\n listEl.style.contain = '';\n }\n\n const DEFAULT_STICK_THRESHOLD = 48;\n\n function resolveStickToBottom(): { enabled: boolean; threshold: number } {\n const opt = options.stickToBottom;\n\n if (!opt) return { enabled: false, threshold: DEFAULT_STICK_THRESHOLD };\n\n if (opt === true) return { enabled: true, threshold: DEFAULT_STICK_THRESHOLD };\n\n return { enabled: opt.enabled ?? true, threshold: opt.threshold ?? DEFAULT_STICK_THRESHOLD };\n }\n\n function spawnVirtualizer(): Virtualizer {\n const v = createVirtualizer(options.scrollElement, {\n count: currentItems.length,\n estimateSize: resolveEstimate,\n gap: options.gap,\n getItemKey: resolveKey,\n horizontal: options.horizontal,\n measurementCache: options.measurementCache,\n onChange: handleChange,\n overscan: options.overscan ?? DEFAULT_OVERSCAN,\n sticky: options.sticky\n ? (index) => {\n const item = currentItems[index];\n\n return item !== undefined && options.sticky!(index, item);\n }\n : undefined,\n });\n\n virtualizer = v;\n listEl.style.position = 'relative';\n listEl.style.contain = 'layout';\n\n return v;\n }\n\n function _dispose(): void {\n if (isDestroyed) return;\n\n isDestroyed = true;\n ac.abort();\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n }\n\n return {\n // ── Virtualizer passthrough (R11) ──────────────────────────────────────\n get count() {\n return virtualizer?.count ?? 0;\n },\n\n get disposalSignal() {\n return ac.signal;\n },\n\n dispose: _dispose,\n\n get disposed() {\n return isDestroyed;\n },\n\n invalidate() {\n if (isDestroyed) return;\n\n virtualizer?.invalidate();\n },\n\n isAtEnd(threshold) {\n return virtualizer?.isAtEnd(threshold) ?? true;\n },\n\n get isScrolling() {\n return virtualizer?.isScrolling ?? false;\n },\n\n get items() {\n return virtualizer?.items ?? [];\n },\n\n measure(index, size) {\n if (isDestroyed) return;\n\n virtualizer?.measure(index, size);\n },\n\n measureBatch(entries) {\n if (isDestroyed) return;\n\n virtualizer?.measureBatch(entries);\n },\n\n measureEl(index, el) {\n if (isDestroyed) return () => {};\n\n return virtualizer?.measureEl(index, el) ?? (() => {});\n },\n\n refresh() {\n if (isDestroyed) return;\n\n virtualizer?.refresh();\n },\n\n get scrollOffset() {\n return virtualizer?.scrollOffset ?? 0;\n },\n\n scrollToBottom(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToBottom(scrollOptions);\n },\n\n scrollToIndex(index, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToIndex(index, scrollOptions);\n },\n\n scrollToOffset(offset, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToOffset(offset, scrollOptions);\n },\n\n scrollToTop(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToTop(scrollOptions);\n },\n\n // ── DomVirtualList-specific ────────────────────────────────────────────\n setItems(items) {\n if (isDestroyed) return;\n\n // Read *before* mutating state — the \"was the list already at the end?\" check must\n // reflect the pre-update layout, not the one `render()` is about to produce below.\n const stick = resolveStickToBottom();\n const wasAtEnd = stick.enabled && (virtualizer?.isAtEnd(stick.threshold) ?? true);\n\n currentItems = items;\n\n if (items.length === 0) {\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n\n return;\n }\n\n if (!virtualizer) {\n const v = spawnVirtualizer();\n\n if (wasAtEnd) v.scrollToBottom();\n\n return;\n }\n\n const countChanged = items.length !== virtualizer.count;\n\n // Only count needs explicit update — estimateSize and getItemKey are\n // closures that already reflect the latest currentItems automatically.\n virtualizer.update({ count: items.length });\n\n // When count changed, update() already triggered rebuild + computeVisible().\n // Only force re-emission when count is unchanged (data changed, count same).\n if (!countChanged) {\n // refresh() re-emits with current sizes for stable keys;\n // invalidate() clears position-based measurements when no stable keys.\n if (options.getItemKey) {\n virtualizer.refresh();\n } else {\n virtualizer.invalidate();\n }\n } else if (!options.getItemKey) {\n // Count changed AND no stable keys: position-based measurements are now\n // stale. Clear them so the next render remeasures from fresh estimates.\n virtualizer.invalidate();\n }\n\n if (wasAtEnd) virtualizer.scrollToBottom();\n },\n\n get stickyItems() {\n return virtualizer?.stickyItems ?? [];\n },\n\n [Symbol.dispose]: _dispose,\n\n get totalSize() {\n return virtualizer?.totalSize ?? 0;\n },\n };\n}\n\n// ─── F5: createVirtualScroller ────────────────────────────────────────────────\n\n/**\n * High-level factory that creates the scroll container and inner list element,\n * appends them to `container`, and returns a fully wired `DomVirtualListController`.\n *\n * @example\n * ```ts\n * const list = createVirtualScroller(document.getElementById('root')!, {\n * render({ items, listEl, recycle }) { … },\n * });\n * list.setItems(data);\n * ```\n */\nexport function createVirtualScroller<T>(\n container: HTMLElement,\n options: VirtualScrollerOptions<T>,\n): DomVirtualListController<T> {\n const scrollEl = document.createElement('div');\n\n scrollEl.style.cssText = options.horizontal\n ? 'overflow: auto hidden; width: 100%; height: 100%;'\n : 'overflow: hidden auto; width: 100%; height: 100%;';\n\n if (options.containerClass) scrollEl.className = options.containerClass;\n\n const listEl = document.createElement('div');\n\n scrollEl.appendChild(listEl);\n container.appendChild(scrollEl);\n\n let ctrl: DomVirtualListController<T>;\n\n try {\n ctrl = createDomVirtualList<T>({\n ...options,\n listElement: listEl,\n scrollElement: scrollEl,\n });\n } catch (e) {\n // Remove the scroll container if construction fails so we don't leak DOM nodes.\n scrollEl.remove();\n throw e;\n }\n\n // Override dispose and [Symbol.dispose] to also remove the scroll container.\n // Capture the original dispose before overwriting so there's no self-reference.\n const innerDispose = ctrl.dispose.bind(ctrl);\n\n return Object.assign(ctrl, {\n dispose() {\n innerDispose();\n scrollEl.remove();\n },\n [Symbol.dispose]() {\n innerDispose();\n scrollEl.remove();\n },\n });\n}\n"],"mappings":"6FA+FA,SAAS,GAAiB,CACxB,IAAI,EAAO,IAAI,IACX,EAAW,IAAI,IACb,EAAuB,CAAC,EAC1B,EAAU,GAEd,MAAO,CACL,QAAQ,EAAiB,EAAwC,CAC/D,GAAI,CAAC,EAAS,OAAO,EAAO,EAE5B,IAAM,EAAW,EAAK,IAAI,CAAG,EAE7B,GAAI,EAGF,OAFA,EAAS,IAAI,EAAK,CAAQ,EAEnB,EAGT,IAAM,EAAO,EAAM,IAAI,GAAK,EAAO,EAInC,OAFA,EAAS,IAAI,EAAK,CAAI,EAEf,CACT,EAEA,YAAmB,CACjB,EAAW,IAAI,IACf,EAAU,EACZ,EAEA,OAAc,CACZ,IAAK,IAAM,KAAQ,EAAK,OAAO,EAAG,EAAK,OAAO,EAE9C,EAAK,MAAM,EACX,EAAS,MAAM,EACf,EAAM,OAAS,EACf,EAAU,EACZ,EAEA,UAAiB,CACV,KAEL,GAAU,GAEV,IAAK,GAAM,CAAC,EAAK,KAAS,EACnB,EAAS,IAAI,CAAG,IACnB,EAAK,OAAO,EACZ,EAAM,KAAK,CAAI,GAInB,EAAO,CATG,CAUZ,CACF,CACF,CAIA,SAAgB,EAAwB,EAAgE,CACtG,IAAI,EAAoB,CAAC,EACrB,EAAc,GACZ,EAAK,IAAI,gBACT,EAAS,EAAQ,YAIjB,EAAO,EAAe,EAGxB,EAAkC,KAEtC,SAAS,EAAW,EAA2B,CAC7C,IAAM,EAAO,EAAa,GAI1B,OAFI,IAAS,IAAA,IAAa,EAAQ,WAAmB,EAAQ,WAAW,EAAO,CAAI,EAE5E,CACT,CAEA,SAAS,EAAgB,EAAuB,CAC9C,GAA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OAAS,EAAG,CAGV,MADA,EAAS,OAAO,EACV,CACR,CAIA,IAAM,EAAe,EAAK,QAAQ,KAAK,CAAI,EAE3C,OAAO,OAAO,OAAO,EAAM,CACzB,SAAU,CACR,EAAa,EACb,EAAS,OAAO,CAClB,EACA,CAAC,OAAO,UAAW,CACjB,EAAa,EACb,EAAS,OAAO,CAClB,CACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"dom-virtual-list.cjs","names":[],"sources":["../src/dom-virtual-list.ts"],"sourcesContent":["import { DEFAULT_ESTIMATE_SIZE, DEFAULT_OVERSCAN, type MeasurementCache, type Overscan } from './_utils';\nimport {\n requireNonNegativeInteger,\n requireNonNegativeNumber,\n requirePositiveNumber,\n validateOverscan,\n} from './_validation';\nimport { ScrollConfigurationError, ScrollRangeError } from './errors';\nimport {\n createVirtualizer,\n type ScrollToIndexOptions,\n type VirtualItem,\n type Virtualizer,\n type VirtualizerState,\n type VirtualKey,\n} from './virtualizer';\n\nexport type {\n MeasurementCache,\n Overscan,\n ScrollToIndexOptions,\n VirtualItem,\n Virtualizer,\n VirtualizerState,\n VirtualKey,\n};\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/** A `VirtualItem` enriched with the corresponding data record. */\nexport type VirtualRenderItem<T> = VirtualItem & { readonly data: T };\n\n/**\n * Recycle a DOM node by key. If the pool has a live node for `key`, it is\n * returned and reused; otherwise `create()` is called to produce a new one.\n */\nexport type RecycleFn = (key: VirtualKey, create: () => HTMLElement) => HTMLElement;\n\nexport type DomVirtualListRenderArgs<T> = {\n items: Array<VirtualRenderItem<T>>;\n listEl: HTMLElement;\n recycle: RecycleFn;\n /** Sticky items from the underlying virtualizer, enriched with data. */\n stickyItems: Array<VirtualRenderItem<T>>;\n totalSize: number;\n};\n\nexport type StickToBottomOptions = {\n /** Enable/disable the behavior. Default: `true` once this object is provided. */\n enabled?: boolean;\n /**\n * Distance in pixels from the end still considered \"at the end\" — the bottom edge in\n * vertical mode, the trailing edge in horizontal mode. Default: `48`.\n */\n threshold?: number;\n};\n\nexport type DomVirtualListOptions<T> = {\n /** Custom teardown that clears listEl. Defaults to `listEl.textContent = ''`. */\n clear?: (listEl: HTMLElement) => void;\n estimateSize?: number | ((index: number, item: T) => number);\n gap?: number;\n getItemKey?: (index: number, item: T) => VirtualKey;\n horizontal?: boolean;\n listElement: HTMLElement;\n /** External measurement cache for scroll restoration. */\n measurementCache?: MeasurementCache;\n overscan?: Overscan;\n render: (args: DomVirtualListRenderArgs<T>) => void;\n scrollElement: HTMLElement | Window;\n /**\n * Auto-scroll to the end after `setItems()` whenever the list was already at (or near) the\n * end just before the update — the chat \"stick to bottom on new message\" pattern. Fires on\n * *any* update while at the end, not just growth, so it also follows a streaming last\n * item that grows in place without changing `items.length`. Does nothing while the user\n * has scrolled away from the end. Pass `true` for defaults, or an options object.\n */\n stickToBottom?: boolean | StickToBottomOptions;\n /** Mark items as sticky headers. Receives the item index and the item data. */\n sticky?: (index: number, item: T) => boolean;\n};\n\n/**\n * R11: Controller extends Virtualizer so all methods (scrollToIndex, refresh,\n * scrollToOffset, etc.) are accessible directly on the controller without\n * needing to unwrap an inner virtualizer handle.\n *\n * `prepend` and `update` are omitted — use `setItems()` for item updates and\n * there is no direct `prepend` concept in DomVirtualList.\n */\nexport type DomVirtualListController<T> = Omit<Virtualizer, 'prepend' | 'update'> & {\n setItems: (items: T[]) => void;\n};\n\nexport type VirtualScrollerOptions<T> = Omit<DomVirtualListOptions<T>, 'listElement' | 'scrollElement'> & {\n /** Additional CSS class names on the generated scroll container. */\n containerClass?: string;\n};\n\n// ─── Node pool ────────────────────────────────────────────────────────────────\n\nfunction createNodePool() {\n let live = new Map<VirtualKey, HTMLElement>();\n let nextLive = new Map<VirtualKey, HTMLElement>();\n const stale: HTMLElement[] = [];\n let inCycle = false;\n\n return {\n acquire(key: VirtualKey, create: () => HTMLElement): HTMLElement {\n if (!inCycle) return create();\n\n const existing = live.get(key);\n\n if (existing) {\n nextLive.set(key, existing);\n\n return existing;\n }\n\n const node = stale.pop() ?? create();\n\n nextLive.set(key, node);\n\n return node;\n },\n\n beginCycle(): void {\n nextLive = new Map();\n inCycle = true;\n },\n\n clear(): void {\n for (const node of live.values()) node.remove();\n\n live.clear();\n nextLive.clear();\n stale.length = 0;\n inCycle = false;\n },\n\n endCycle(): void {\n if (!inCycle) return;\n\n inCycle = false;\n\n for (const [key, node] of live) {\n if (!nextLive.has(key)) {\n node.remove();\n stale.push(node);\n }\n }\n\n live = nextLive;\n },\n };\n}\n\n// ─── Implementation ────────────────────────────────────────────────────────────\n\nexport function createDomVirtualList<T>(options: DomVirtualListOptions<T>): DomVirtualListController<T> {\n if (typeof options.estimateSize === 'number') requirePositiveNumber(options.estimateSize, 'estimateSize');\n\n if (options.gap !== undefined) requireNonNegativeInteger(options.gap, 'gap');\n\n if (options.overscan !== undefined) validateOverscan(options.overscan);\n\n if (options.stickToBottom !== undefined && typeof options.stickToBottom !== 'boolean') {\n if (options.stickToBottom === null || Array.isArray(options.stickToBottom)) {\n throw new ScrollConfigurationError('stickToBottom must be a boolean or options object.');\n }\n\n if (options.stickToBottom.threshold !== undefined) {\n requireNonNegativeNumber(options.stickToBottom.threshold, 'stickToBottom.threshold');\n }\n }\n\n let currentItems: T[] = [];\n let isDestroyed = false;\n const ac = new AbortController();\n const listEl = options.listElement;\n\n // Pool must be declared before virtualizer since handleChange (passed as onChange)\n // is invoked during createVirtualizer initialization via computeVisible.\n const pool = createNodePool();\n\n // Virtualizer is lazily created on the first non-empty setItems call.\n let virtualizer: Virtualizer | null = null;\n\n function resolveKey(index: number): VirtualKey {\n const item = currentItems[index];\n\n if (item !== undefined && options.getItemKey) return options.getItemKey(index, item);\n\n return index;\n }\n\n function resolveEstimate(index: number): number {\n if (options.estimateSize === undefined) return DEFAULT_ESTIMATE_SIZE;\n\n if (typeof options.estimateSize === 'number') return options.estimateSize;\n\n const item = currentItems[index];\n\n return item !== undefined ? options.estimateSize(index, item) : DEFAULT_ESTIMATE_SIZE;\n }\n\n function applyListSize(totalSize: number): void {\n if (options.horizontal) {\n listEl.style.height = '';\n listEl.style.width = `${totalSize}px`;\n } else {\n listEl.style.height = `${totalSize}px`;\n listEl.style.width = '';\n }\n }\n\n /**\n * R10: Throw rather than silently produce `undefined as T`.\n * This catches bugs where `vi.index` is out of range for `currentItems`.\n */\n function toRenderItem(vi: VirtualItem): VirtualRenderItem<T> {\n const data = currentItems[vi.index];\n\n if (data === undefined) {\n throw new ScrollRangeError(\n `toRenderItem: index ${vi.index} is out of range (currentItems.length=${currentItems.length})`,\n );\n }\n\n return { ...vi, data };\n }\n\n function handleChange(state: VirtualizerState): void {\n applyListSize(state.totalSize);\n\n pool.beginCycle();\n\n // R5: try/finally ensures endCycle() runs even if render() throws, keeping\n // the pool in a consistent state.\n try {\n options.render({\n items: state.items.map(toRenderItem),\n listEl,\n recycle: (key, create) => pool.acquire(key, create),\n stickyItems: state.stickyItems.map(toRenderItem),\n totalSize: state.totalSize,\n });\n } finally {\n pool.endCycle();\n }\n }\n\n function clearAndReset(): void {\n pool.clear();\n\n if (options.clear) {\n options.clear(listEl);\n } else {\n listEl.textContent = '';\n }\n\n listEl.style.height = '';\n listEl.style.width = '';\n listEl.style.position = '';\n listEl.style.contain = '';\n }\n\n const DEFAULT_STICK_THRESHOLD = 48;\n\n function resolveStickToBottom(): { enabled: boolean; threshold: number } {\n const opt = options.stickToBottom;\n\n if (!opt) return { enabled: false, threshold: DEFAULT_STICK_THRESHOLD };\n\n if (opt === true) return { enabled: true, threshold: DEFAULT_STICK_THRESHOLD };\n\n return { enabled: opt.enabled ?? true, threshold: opt.threshold ?? DEFAULT_STICK_THRESHOLD };\n }\n\n function spawnVirtualizer(): Virtualizer {\n const v = createVirtualizer(options.scrollElement, {\n count: currentItems.length,\n estimateSize: resolveEstimate,\n gap: options.gap,\n getItemKey: resolveKey,\n horizontal: options.horizontal,\n measurementCache: options.measurementCache,\n onChange: handleChange,\n overscan: options.overscan ?? DEFAULT_OVERSCAN,\n sticky: options.sticky\n ? (index) => {\n const item = currentItems[index];\n\n return item !== undefined && options.sticky!(index, item);\n }\n : undefined,\n });\n\n virtualizer = v;\n listEl.style.position = 'relative';\n listEl.style.contain = 'layout';\n\n return v;\n }\n\n function _dispose(): void {\n if (isDestroyed) return;\n\n isDestroyed = true;\n ac.abort();\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n }\n\n return {\n // ── Virtualizer passthrough (R11) ──────────────────────────────────────\n get count() {\n return virtualizer?.count ?? 0;\n },\n\n get disposalSignal() {\n return ac.signal;\n },\n\n dispose: _dispose,\n\n get disposed() {\n return isDestroyed;\n },\n\n invalidate() {\n if (isDestroyed) return;\n\n virtualizer?.invalidate();\n },\n\n isAtEnd(threshold) {\n return virtualizer?.isAtEnd(threshold) ?? true;\n },\n\n get isScrolling() {\n return virtualizer?.isScrolling ?? false;\n },\n\n get items() {\n return virtualizer?.items ?? [];\n },\n\n measure(index, size) {\n if (isDestroyed) return;\n\n virtualizer?.measure(index, size);\n },\n\n measureBatch(entries) {\n if (isDestroyed) return;\n\n virtualizer?.measureBatch(entries);\n },\n\n measureEl(index, el) {\n if (isDestroyed) return () => {};\n\n return virtualizer?.measureEl(index, el) ?? (() => {});\n },\n\n refresh() {\n if (isDestroyed) return;\n\n virtualizer?.refresh();\n },\n\n get scrollOffset() {\n return virtualizer?.scrollOffset ?? 0;\n },\n\n scrollToBottom(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToBottom(scrollOptions);\n },\n\n scrollToIndex(index, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToIndex(index, scrollOptions);\n },\n\n scrollToOffset(offset, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToOffset(offset, scrollOptions);\n },\n\n scrollToTop(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToTop(scrollOptions);\n },\n\n // ── DomVirtualList-specific ────────────────────────────────────────────\n setItems(items) {\n if (isDestroyed) return;\n\n // Read *before* mutating state — the \"was the list already at the end?\" check must\n // reflect the pre-update layout, not the one `render()` is about to produce below.\n const stick = resolveStickToBottom();\n const wasAtEnd = stick.enabled && (virtualizer?.isAtEnd(stick.threshold) ?? true);\n\n currentItems = items;\n\n if (items.length === 0) {\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n\n return;\n }\n\n if (!virtualizer) {\n const v = spawnVirtualizer();\n\n if (wasAtEnd) v.scrollToBottom();\n\n return;\n }\n\n const countChanged = items.length !== virtualizer.count;\n\n // Only count needs explicit update — estimateSize and getItemKey are\n // closures that already reflect the latest currentItems automatically.\n virtualizer.update({ count: items.length });\n\n // When count changed, update() already triggered rebuild + computeVisible().\n // Only force re-emission when count is unchanged (data changed, count same).\n if (!countChanged) {\n // refresh() re-emits with current sizes for stable keys;\n // invalidate() clears position-based measurements when no stable keys.\n if (options.getItemKey) {\n virtualizer.refresh();\n } else {\n virtualizer.invalidate();\n }\n } else if (!options.getItemKey) {\n // Count changed AND no stable keys: position-based measurements are now\n // stale. Clear them so the next render remeasures from fresh estimates.\n virtualizer.invalidate();\n }\n\n if (wasAtEnd) virtualizer.scrollToBottom();\n },\n\n get stickyItems() {\n return virtualizer?.stickyItems ?? [];\n },\n\n [Symbol.dispose]: _dispose,\n\n get totalSize() {\n return virtualizer?.totalSize ?? 0;\n },\n };\n}\n\n// ─── F5: createVirtualScroller ────────────────────────────────────────────────\n\n/**\n * High-level factory that creates the scroll container and inner list element,\n * appends them to `container`, and returns a fully wired `DomVirtualListController`.\n *\n * @example\n * ```ts\n * const list = createVirtualScroller(document.getElementById('root')!, {\n * render({ items, listEl, recycle }) { … },\n * });\n * list.setItems(data);\n * ```\n */\nexport function createVirtualScroller<T>(\n container: HTMLElement,\n options: VirtualScrollerOptions<T>,\n): DomVirtualListController<T> {\n const scrollEl = document.createElement('div');\n\n scrollEl.style.cssText = options.horizontal\n ? 'overflow: auto hidden; width: 100%; height: 100%;'\n : 'overflow: hidden auto; width: 100%; height: 100%;';\n\n if (options.containerClass) scrollEl.className = options.containerClass;\n\n const listEl = document.createElement('div');\n\n scrollEl.appendChild(listEl);\n container.appendChild(scrollEl);\n\n let ctrl: DomVirtualListController<T>;\n\n try {\n ctrl = createDomVirtualList<T>({\n ...options,\n listElement: listEl,\n scrollElement: scrollEl,\n });\n } catch (e) {\n // Remove the scroll container if construction fails so we don't leak DOM nodes.\n scrollEl.remove();\n throw e;\n }\n\n // Override dispose and [Symbol.dispose] to also remove the scroll container.\n // Capture the original dispose before overwriting so there's no self-reference.\n const innerDispose = ctrl.dispose.bind(ctrl);\n\n return Object.assign(ctrl, {\n dispose() {\n innerDispose();\n scrollEl.remove();\n },\n [Symbol.dispose]() {\n innerDispose();\n scrollEl.remove();\n },\n });\n}\n"],"mappings":"4HAqGA,SAAS,GAAiB,CACxB,IAAI,EAAO,IAAI,IACX,EAAW,IAAI,IACb,EAAuB,CAAC,EAC1B,EAAU,GAEd,MAAO,CACL,QAAQ,EAAiB,EAAwC,CAC/D,GAAI,CAAC,EAAS,OAAO,EAAO,EAE5B,IAAM,EAAW,EAAK,IAAI,CAAG,EAE7B,GAAI,EAGF,OAFA,EAAS,IAAI,EAAK,CAAQ,EAEnB,EAGT,IAAM,EAAO,EAAM,IAAI,GAAK,EAAO,EAInC,OAFA,EAAS,IAAI,EAAK,CAAI,EAEf,CACT,EAEA,YAAmB,CACjB,EAAW,IAAI,IACf,EAAU,EACZ,EAEA,OAAc,CACZ,IAAK,IAAM,KAAQ,EAAK,OAAO,EAAG,EAAK,OAAO,EAE9C,EAAK,MAAM,EACX,EAAS,MAAM,EACf,EAAM,OAAS,EACf,EAAU,EACZ,EAEA,UAAiB,CACV,KAEL,GAAU,GAEV,IAAK,GAAM,CAAC,EAAK,KAAS,EACnB,EAAS,IAAI,CAAG,IACnB,EAAK,OAAO,EACZ,EAAM,KAAK,CAAI,GAInB,EAAO,CATG,CAUZ,CACF,CACF,CAIA,SAAgB,EAAwB,EAAgE,CAOtG,GANI,OAAO,EAAQ,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AU,EAAE,eAAe,EAE/B,MACF,CAEA,IAAM,EAAe,EAAM,SAAW,EAAY,MAIlD,EAAY,OAAO,CAAE,MAAO,EAAM,MAAO,CAAC,EAIrC,EAQO,EAAQ,YAGlB,EAAY,WAAW,EARnB,EAAQ,WACV,EAAY,QAAQ,EAEpB,EAAY,WAAW,EAQvB,GAAU,EAAY,eAAe,CAC3C,EAEA,IAAI,aAAc,CAChB,OAAO,GAAa,aAAe,CAAC,CACtC,GAEC,OAAO,SAAU,EAElB,IAAI,WAAY,CACd,OAAO,GAAa,WAAa,CACnC,CACF,CACF,CAgBA,SAAgB,EACd,EACA,EAC6B,CAC7B,IAAM,EAAW,SAAS,cAAc,KAAK,EAE7C,EAAS,MAAM,QAAU,EAAQ,WAC7B,oDACA,oDAEA,EAAQ,iBAAgB,EAAS,UAAY,EAAQ,gBAEzD,IAAM,EAAS,SAAS,cAAc,KAAK,EAE3C,EAAS,YAAY,CAAM,EAC3B,EAAU,YAAY,CAAQ,EAE9B,IAAI,EAEJ,GAAI,CACF,EAAO,EAAwB,CAC7B,GAAG,EACH,YAAa,EACb,cAAe,CACjB,CAAC,CACH,OAAS,EAAG,CAGV,MADA,EAAS,OAAO,EACV,CACR,CAIA,IAAM,EAAe,EAAK,QAAQ,KAAK,CAAI,EAE3C,OAAO,OAAO,OAAO,EAAM,CACzB,SAAU,CACR,EAAa,EACb,EAAS,OAAO,CAClB,EACA,CAAC,OAAO,UAAW,CACjB,EAAa,EACb,EAAS,OAAO,CAClB,CACF,CAAC,CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom-virtual-list.d.ts","sourceRoot":"","sources":["../src/dom-virtual-list.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2C,KAAK,gBAAgB,EAAE,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"dom-virtual-list.d.ts","sourceRoot":"","sources":["../src/dom-virtual-list.ts"],"names":[],"mappings":"AAAA,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GACjC,wBAAwB,CAAC,CAAC,CAAC,CA0C7B"}
|
package/dist/dom-virtual-list.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ScrollRangeError as
|
|
1
|
+
import{ScrollConfigurationError as e,ScrollRangeError as t}from"./errors.js";import"./_utils.js";import{requireNonNegativeInteger as n,requireNonNegativeNumber as r,requirePositiveNumber as i,validateOverscan as a}from"./_validation.js";import{createVirtualizer as o}from"./virtualizer.js";function s(){let e=new Map,t=new Map,n=[],r=!1;return{acquire(i,a){if(!r)return a();let o=e.get(i);if(o)return t.set(i,o),o;let s=n.pop()??a();return t.set(i,s),s},beginCycle(){t=new Map,r=!0},clear(){for(let t of e.values())t.remove();e.clear(),t.clear(),n.length=0,r=!1},endCycle(){if(r){r=!1;for(let[r,i]of e)t.has(r)||(i.remove(),n.push(i));e=t}}}}function c(c){if(typeof c.estimateSize==`number`&&i(c.estimateSize,`estimateSize`),c.gap!==void 0&&n(c.gap,`gap`),c.overscan!==void 0&&a(c.overscan),c.stickToBottom!==void 0&&typeof c.stickToBottom!=`boolean`){if(c.stickToBottom===null||Array.isArray(c.stickToBottom))throw new e(`stickToBottom must be a boolean or options object.`);c.stickToBottom.threshold!==void 0&&r(c.stickToBottom.threshold,`stickToBottom.threshold`)}let l=[],u=!1,d=new AbortController,f=c.listElement,p=s(),m=null;function h(e){let t=l[e];return t!==void 0&&c.getItemKey?c.getItemKey(e,t):e}function g(e){if(c.estimateSize===void 0)return 36;if(typeof c.estimateSize==`number`)return c.estimateSize;let t=l[e];return t===void 0?36:c.estimateSize(e,t)}function _(e){c.horizontal?(f.style.height=``,f.style.width=`${e}px`):(f.style.height=`${e}px`,f.style.width=``)}function v(e){let n=l[e.index];if(n===void 0)throw new t(`toRenderItem: index ${e.index} is out of range (currentItems.length=${l.length})`);return{...e,data:n}}function y(e){_(e.totalSize),p.beginCycle();try{c.render({items:e.items.map(v),listEl:f,recycle:(e,t)=>p.acquire(e,t),stickyItems:e.stickyItems.map(v),totalSize:e.totalSize})}finally{p.endCycle()}}function b(){p.clear(),c.clear?c.clear(f):f.textContent=``,f.style.height=``,f.style.width=``,f.style.position=``,f.style.contain=``}function x(){let e=c.stickToBottom;return e?e===!0?{enabled:!0,threshold:48}:{enabled:e.enabled??!0,threshold:e.threshold??48}:{enabled:!1,threshold:48}}function S(){let e=o(c.scrollElement,{count:l.length,estimateSize:g,gap:c.gap,getItemKey:h,horizontal:c.horizontal,measurementCache:c.measurementCache,onChange:y,overscan:c.overscan??3,sticky:c.sticky?e=>{let t=l[e];return t!==void 0&&c.sticky(e,t)}:void 0});return m=e,f.style.position=`relative`,f.style.contain=`layout`,e}function C(){u||(u=!0,d.abort(),m?.dispose(),m=null,b())}return{get count(){return m?.count??0},get disposalSignal(){return d.signal},dispose:C,get disposed(){return u},invalidate(){u||m?.invalidate()},isAtEnd(e){return m?.isAtEnd(e)??!0},get isScrolling(){return m?.isScrolling??!1},get items(){return m?.items??[]},measure(e,t){u||m?.measure(e,t)},measureBatch(e){u||m?.measureBatch(e)},measureEl(e,t){return u?()=>{}:m?.measureEl(e,t)??(()=>{})},refresh(){u||m?.refresh()},get scrollOffset(){return m?.scrollOffset??0},scrollToBottom(e){u||m?.scrollToBottom(e)},scrollToIndex(e,t){u||m?.scrollToIndex(e,t)},scrollToOffset(e,t){u||m?.scrollToOffset(e,t)},scrollToTop(e){u||m?.scrollToTop(e)},setItems(e){if(u)return;let t=x(),n=t.enabled&&(m?.isAtEnd(t.threshold)??!0);if(l=e,e.length===0){m?.dispose(),m=null,b();return}if(!m){let e=S();n&&e.scrollToBottom();return}let r=e.length!==m.count;m.update({count:e.length}),r?c.getItemKey||m.invalidate():c.getItemKey?m.refresh():m.invalidate(),n&&m.scrollToBottom()},get stickyItems(){return m?.stickyItems??[]},[Symbol.dispose]:C,get totalSize(){return m?.totalSize??0}}}function l(e,t){let n=document.createElement(`div`);n.style.cssText=t.horizontal?`overflow: auto hidden; width: 100%; height: 100%;`:`overflow: hidden auto; width: 100%; height: 100%;`,t.containerClass&&(n.className=t.containerClass);let r=document.createElement(`div`);n.appendChild(r),e.appendChild(n);let i;try{i=c({...t,listElement:r,scrollElement:n})}catch(e){throw n.remove(),e}let a=i.dispose.bind(i);return Object.assign(i,{dispose(){a(),n.remove()},[Symbol.dispose](){a(),n.remove()}})}export{c as createDomVirtualList,l as createVirtualScroller};
|
|
2
2
|
//# sourceMappingURL=dom-virtual-list.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom-virtual-list.js","names":[],"sources":["../src/dom-virtual-list.ts"],"sourcesContent":["import { DEFAULT_ESTIMATE_SIZE, DEFAULT_OVERSCAN, type MeasurementCache, type Overscan } from './_utils';\nimport { ScrollRangeError } from './errors';\nimport {\n createVirtualizer,\n type ScrollToIndexOptions,\n type VirtualItem,\n type Virtualizer,\n type VirtualizerState,\n type VirtualKey,\n} from './virtualizer';\n\nexport type {\n MeasurementCache,\n Overscan,\n ScrollToIndexOptions,\n VirtualItem,\n Virtualizer,\n VirtualizerState,\n VirtualKey,\n};\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/** A `VirtualItem` enriched with the corresponding data record. */\nexport type VirtualRenderItem<T> = VirtualItem & { readonly data: T };\n\n/**\n * Recycle a DOM node by key. If the pool has a live node for `key`, it is\n * returned and reused; otherwise `create()` is called to produce a new one.\n */\nexport type RecycleFn = (key: VirtualKey, create: () => HTMLElement) => HTMLElement;\n\nexport type DomVirtualListRenderArgs<T> = {\n items: Array<VirtualRenderItem<T>>;\n listEl: HTMLElement;\n recycle: RecycleFn;\n /** Sticky items from the underlying virtualizer, enriched with data. */\n stickyItems: Array<VirtualRenderItem<T>>;\n totalSize: number;\n};\n\nexport type StickToBottomOptions = {\n /** Enable/disable the behavior. Default: `true` once this object is provided. */\n enabled?: boolean;\n /**\n * Distance in pixels from the end still considered \"at the end\" — the bottom edge in\n * vertical mode, the trailing edge in horizontal mode. Default: `48`.\n */\n threshold?: number;\n};\n\nexport type DomVirtualListOptions<T> = {\n /** Custom teardown that clears listEl. Defaults to `listEl.textContent = ''`. */\n clear?: (listEl: HTMLElement) => void;\n estimateSize?: number | ((index: number, item: T) => number);\n gap?: number;\n getItemKey?: (index: number, item: T) => VirtualKey;\n horizontal?: boolean;\n listElement: HTMLElement;\n /** External measurement cache for scroll restoration. */\n measurementCache?: MeasurementCache;\n overscan?: Overscan;\n render: (args: DomVirtualListRenderArgs<T>) => void;\n scrollElement: HTMLElement | Window;\n /**\n * Auto-scroll to the end after `setItems()` whenever the list was already at (or near) the\n * end just before the update — the chat \"stick to bottom on new message\" pattern. Fires on\n * *any* update while at the end, not just growth, so it also follows a streaming last\n * item that grows in place without changing `items.length`. Does nothing while the user\n * has scrolled away from the end. Pass `true` for defaults, or an options object.\n */\n stickToBottom?: boolean | StickToBottomOptions;\n /** Mark items as sticky headers. Receives the item index and the item data. */\n sticky?: (index: number, item: T) => boolean;\n};\n\n/**\n * R11: Controller extends Virtualizer so all methods (scrollToIndex, refresh,\n * scrollToOffset, etc.) are accessible directly on the controller without\n * needing to unwrap an inner virtualizer handle.\n *\n * `prepend` and `update` are omitted — use `setItems()` for item updates and\n * there is no direct `prepend` concept in DomVirtualList.\n */\nexport type DomVirtualListController<T> = Omit<Virtualizer, 'prepend' | 'update'> & {\n setItems: (items: T[]) => void;\n};\n\nexport type VirtualScrollerOptions<T> = Omit<DomVirtualListOptions<T>, 'listElement' | 'scrollElement'> & {\n /** Additional CSS class names on the generated scroll container. */\n containerClass?: string;\n};\n\n// ─── Node pool ────────────────────────────────────────────────────────────────\n\nfunction createNodePool() {\n let live = new Map<VirtualKey, HTMLElement>();\n let nextLive = new Map<VirtualKey, HTMLElement>();\n const stale: HTMLElement[] = [];\n let inCycle = false;\n\n return {\n acquire(key: VirtualKey, create: () => HTMLElement): HTMLElement {\n if (!inCycle) return create();\n\n const existing = live.get(key);\n\n if (existing) {\n nextLive.set(key, existing);\n\n return existing;\n }\n\n const node = stale.pop() ?? create();\n\n nextLive.set(key, node);\n\n return node;\n },\n\n beginCycle(): void {\n nextLive = new Map();\n inCycle = true;\n },\n\n clear(): void {\n for (const node of live.values()) node.remove();\n\n live.clear();\n nextLive.clear();\n stale.length = 0;\n inCycle = false;\n },\n\n endCycle(): void {\n if (!inCycle) return;\n\n inCycle = false;\n\n for (const [key, node] of live) {\n if (!nextLive.has(key)) {\n node.remove();\n stale.push(node);\n }\n }\n\n live = nextLive;\n },\n };\n}\n\n// ─── Implementation ────────────────────────────────────────────────────────────\n\nexport function createDomVirtualList<T>(options: DomVirtualListOptions<T>): DomVirtualListController<T> {\n let currentItems: T[] = [];\n let isDestroyed = false;\n const ac = new AbortController();\n const listEl = options.listElement;\n\n // Pool must be declared before virtualizer since handleChange (passed as onChange)\n // is invoked during createVirtualizer initialization via computeVisible.\n const pool = createNodePool();\n\n // Virtualizer is lazily created on the first non-empty setItems call.\n let virtualizer: Virtualizer | null = null;\n\n function resolveKey(index: number): VirtualKey {\n const item = currentItems[index];\n\n if (item !== undefined && options.getItemKey) return options.getItemKey(index, item);\n\n return index;\n }\n\n function resolveEstimate(index: number): number {\n if (options.estimateSize === undefined) return DEFAULT_ESTIMATE_SIZE;\n\n if (typeof options.estimateSize === 'number') return options.estimateSize;\n\n const item = currentItems[index];\n\n return item !== undefined ? options.estimateSize(index, item) : DEFAULT_ESTIMATE_SIZE;\n }\n\n function applyListSize(totalSize: number): void {\n if (options.horizontal) {\n listEl.style.height = '';\n listEl.style.width = `${totalSize}px`;\n } else {\n listEl.style.height = `${totalSize}px`;\n listEl.style.width = '';\n }\n }\n\n /**\n * R10: Throw rather than silently produce `undefined as T`.\n * This catches bugs where `vi.index` is out of range for `currentItems`.\n */\n function toRenderItem(vi: VirtualItem): VirtualRenderItem<T> {\n const data = currentItems[vi.index];\n\n if (data === undefined) {\n throw new ScrollRangeError(\n `toRenderItem: index ${vi.index} is out of range (currentItems.length=${currentItems.length})`,\n );\n }\n\n return { ...vi, data };\n }\n\n function handleChange(state: VirtualizerState): void {\n applyListSize(state.totalSize);\n\n pool.beginCycle();\n\n // R5: try/finally ensures endCycle() runs even if render() throws, keeping\n // the pool in a consistent state.\n try {\n options.render({\n items: state.items.map(toRenderItem),\n listEl,\n recycle: (key, create) => pool.acquire(key, create),\n stickyItems: state.stickyItems.map(toRenderItem),\n totalSize: state.totalSize,\n });\n } finally {\n pool.endCycle();\n }\n }\n\n function clearAndReset(): void {\n pool.clear();\n\n if (options.clear) {\n options.clear(listEl);\n } else {\n listEl.textContent = '';\n }\n\n listEl.style.height = '';\n listEl.style.width = '';\n listEl.style.position = '';\n listEl.style.contain = '';\n }\n\n const DEFAULT_STICK_THRESHOLD = 48;\n\n function resolveStickToBottom(): { enabled: boolean; threshold: number } {\n const opt = options.stickToBottom;\n\n if (!opt) return { enabled: false, threshold: DEFAULT_STICK_THRESHOLD };\n\n if (opt === true) return { enabled: true, threshold: DEFAULT_STICK_THRESHOLD };\n\n return { enabled: opt.enabled ?? true, threshold: opt.threshold ?? DEFAULT_STICK_THRESHOLD };\n }\n\n function spawnVirtualizer(): Virtualizer {\n const v = createVirtualizer(options.scrollElement, {\n count: currentItems.length,\n estimateSize: resolveEstimate,\n gap: options.gap,\n getItemKey: resolveKey,\n horizontal: options.horizontal,\n measurementCache: options.measurementCache,\n onChange: handleChange,\n overscan: options.overscan ?? DEFAULT_OVERSCAN,\n sticky: options.sticky\n ? (index) => {\n const item = currentItems[index];\n\n return item !== undefined && options.sticky!(index, item);\n }\n : undefined,\n });\n\n virtualizer = v;\n listEl.style.position = 'relative';\n listEl.style.contain = 'layout';\n\n return v;\n }\n\n function _dispose(): void {\n if (isDestroyed) return;\n\n isDestroyed = true;\n ac.abort();\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n }\n\n return {\n // ── Virtualizer passthrough (R11) ──────────────────────────────────────\n get count() {\n return virtualizer?.count ?? 0;\n },\n\n get disposalSignal() {\n return ac.signal;\n },\n\n dispose: _dispose,\n\n get disposed() {\n return isDestroyed;\n },\n\n invalidate() {\n if (isDestroyed) return;\n\n virtualizer?.invalidate();\n },\n\n isAtEnd(threshold) {\n return virtualizer?.isAtEnd(threshold) ?? true;\n },\n\n get isScrolling() {\n return virtualizer?.isScrolling ?? false;\n },\n\n get items() {\n return virtualizer?.items ?? [];\n },\n\n measure(index, size) {\n if (isDestroyed) return;\n\n virtualizer?.measure(index, size);\n },\n\n measureBatch(entries) {\n if (isDestroyed) return;\n\n virtualizer?.measureBatch(entries);\n },\n\n measureEl(index, el) {\n if (isDestroyed) return () => {};\n\n return virtualizer?.measureEl(index, el) ?? (() => {});\n },\n\n refresh() {\n if (isDestroyed) return;\n\n virtualizer?.refresh();\n },\n\n get scrollOffset() {\n return virtualizer?.scrollOffset ?? 0;\n },\n\n scrollToBottom(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToBottom(scrollOptions);\n },\n\n scrollToIndex(index, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToIndex(index, scrollOptions);\n },\n\n scrollToOffset(offset, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToOffset(offset, scrollOptions);\n },\n\n scrollToTop(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToTop(scrollOptions);\n },\n\n // ── DomVirtualList-specific ────────────────────────────────────────────\n setItems(items) {\n if (isDestroyed) return;\n\n // Read *before* mutating state — the \"was the list already at the end?\" check must\n // reflect the pre-update layout, not the one `render()` is about to produce below.\n const stick = resolveStickToBottom();\n const wasAtEnd = stick.enabled && (virtualizer?.isAtEnd(stick.threshold) ?? true);\n\n currentItems = items;\n\n if (items.length === 0) {\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n\n return;\n }\n\n if (!virtualizer) {\n const v = spawnVirtualizer();\n\n if (wasAtEnd) v.scrollToBottom();\n\n return;\n }\n\n const countChanged = items.length !== virtualizer.count;\n\n // Only count needs explicit update — estimateSize and getItemKey are\n // closures that already reflect the latest currentItems automatically.\n virtualizer.update({ count: items.length });\n\n // When count changed, update() already triggered rebuild + computeVisible().\n // Only force re-emission when count is unchanged (data changed, count same).\n if (!countChanged) {\n // refresh() re-emits with current sizes for stable keys;\n // invalidate() clears position-based measurements when no stable keys.\n if (options.getItemKey) {\n virtualizer.refresh();\n } else {\n virtualizer.invalidate();\n }\n } else if (!options.getItemKey) {\n // Count changed AND no stable keys: position-based measurements are now\n // stale. Clear them so the next render remeasures from fresh estimates.\n virtualizer.invalidate();\n }\n\n if (wasAtEnd) virtualizer.scrollToBottom();\n },\n\n get stickyItems() {\n return virtualizer?.stickyItems ?? [];\n },\n\n [Symbol.dispose]: _dispose,\n\n get totalSize() {\n return virtualizer?.totalSize ?? 0;\n },\n };\n}\n\n// ─── F5: createVirtualScroller ────────────────────────────────────────────────\n\n/**\n * High-level factory that creates the scroll container and inner list element,\n * appends them to `container`, and returns a fully wired `DomVirtualListController`.\n *\n * @example\n * ```ts\n * const list = createVirtualScroller(document.getElementById('root')!, {\n * render({ items, listEl, recycle }) { … },\n * });\n * list.setItems(data);\n * ```\n */\nexport function createVirtualScroller<T>(\n container: HTMLElement,\n options: VirtualScrollerOptions<T>,\n): DomVirtualListController<T> {\n const scrollEl = document.createElement('div');\n\n scrollEl.style.cssText = options.horizontal\n ? 'overflow: auto hidden; width: 100%; height: 100%;'\n : 'overflow: hidden auto; width: 100%; height: 100%;';\n\n if (options.containerClass) scrollEl.className = options.containerClass;\n\n const listEl = document.createElement('div');\n\n scrollEl.appendChild(listEl);\n container.appendChild(scrollEl);\n\n let ctrl: DomVirtualListController<T>;\n\n try {\n ctrl = createDomVirtualList<T>({\n ...options,\n listElement: listEl,\n scrollElement: scrollEl,\n });\n } catch (e) {\n // Remove the scroll container if construction fails so we don't leak DOM nodes.\n scrollEl.remove();\n throw e;\n }\n\n // Override dispose and [Symbol.dispose] to also remove the scroll container.\n // Capture the original dispose before overwriting so there's no self-reference.\n const innerDispose = ctrl.dispose.bind(ctrl);\n\n return Object.assign(ctrl, {\n dispose() {\n innerDispose();\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AO,CAClB,EACA,CAAC,OAAO,UAAW,CACjB,EAAa,EACb,EAAS,OAAO,CAClB,CACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"dom-virtual-list.js","names":[],"sources":["../src/dom-virtual-list.ts"],"sourcesContent":["import { DEFAULT_ESTIMATE_SIZE, DEFAULT_OVERSCAN, type MeasurementCache, type Overscan } from './_utils';\nimport {\n requireNonNegativeInteger,\n requireNonNegativeNumber,\n requirePositiveNumber,\n validateOverscan,\n} from './_validation';\nimport { ScrollConfigurationError, ScrollRangeError } from './errors';\nimport {\n createVirtualizer,\n type ScrollToIndexOptions,\n type VirtualItem,\n type Virtualizer,\n type VirtualizerState,\n type VirtualKey,\n} from './virtualizer';\n\nexport type {\n MeasurementCache,\n Overscan,\n ScrollToIndexOptions,\n VirtualItem,\n Virtualizer,\n VirtualizerState,\n VirtualKey,\n};\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/** A `VirtualItem` enriched with the corresponding data record. */\nexport type VirtualRenderItem<T> = VirtualItem & { readonly data: T };\n\n/**\n * Recycle a DOM node by key. If the pool has a live node for `key`, it is\n * returned and reused; otherwise `create()` is called to produce a new one.\n */\nexport type RecycleFn = (key: VirtualKey, create: () => HTMLElement) => HTMLElement;\n\nexport type DomVirtualListRenderArgs<T> = {\n items: Array<VirtualRenderItem<T>>;\n listEl: HTMLElement;\n recycle: RecycleFn;\n /** Sticky items from the underlying virtualizer, enriched with data. */\n stickyItems: Array<VirtualRenderItem<T>>;\n totalSize: number;\n};\n\nexport type StickToBottomOptions = {\n /** Enable/disable the behavior. Default: `true` once this object is provided. */\n enabled?: boolean;\n /**\n * Distance in pixels from the end still considered \"at the end\" — the bottom edge in\n * vertical mode, the trailing edge in horizontal mode. Default: `48`.\n */\n threshold?: number;\n};\n\nexport type DomVirtualListOptions<T> = {\n /** Custom teardown that clears listEl. Defaults to `listEl.textContent = ''`. */\n clear?: (listEl: HTMLElement) => void;\n estimateSize?: number | ((index: number, item: T) => number);\n gap?: number;\n getItemKey?: (index: number, item: T) => VirtualKey;\n horizontal?: boolean;\n listElement: HTMLElement;\n /** External measurement cache for scroll restoration. */\n measurementCache?: MeasurementCache;\n overscan?: Overscan;\n render: (args: DomVirtualListRenderArgs<T>) => void;\n scrollElement: HTMLElement | Window;\n /**\n * Auto-scroll to the end after `setItems()` whenever the list was already at (or near) the\n * end just before the update — the chat \"stick to bottom on new message\" pattern. Fires on\n * *any* update while at the end, not just growth, so it also follows a streaming last\n * item that grows in place without changing `items.length`. Does nothing while the user\n * has scrolled away from the end. Pass `true` for defaults, or an options object.\n */\n stickToBottom?: boolean | StickToBottomOptions;\n /** Mark items as sticky headers. Receives the item index and the item data. */\n sticky?: (index: number, item: T) => boolean;\n};\n\n/**\n * R11: Controller extends Virtualizer so all methods (scrollToIndex, refresh,\n * scrollToOffset, etc.) are accessible directly on the controller without\n * needing to unwrap an inner virtualizer handle.\n *\n * `prepend` and `update` are omitted — use `setItems()` for item updates and\n * there is no direct `prepend` concept in DomVirtualList.\n */\nexport type DomVirtualListController<T> = Omit<Virtualizer, 'prepend' | 'update'> & {\n setItems: (items: T[]) => void;\n};\n\nexport type VirtualScrollerOptions<T> = Omit<DomVirtualListOptions<T>, 'listElement' | 'scrollElement'> & {\n /** Additional CSS class names on the generated scroll container. */\n containerClass?: string;\n};\n\n// ─── Node pool ────────────────────────────────────────────────────────────────\n\nfunction createNodePool() {\n let live = new Map<VirtualKey, HTMLElement>();\n let nextLive = new Map<VirtualKey, HTMLElement>();\n const stale: HTMLElement[] = [];\n let inCycle = false;\n\n return {\n acquire(key: VirtualKey, create: () => HTMLElement): HTMLElement {\n if (!inCycle) return create();\n\n const existing = live.get(key);\n\n if (existing) {\n nextLive.set(key, existing);\n\n return existing;\n }\n\n const node = stale.pop() ?? create();\n\n nextLive.set(key, node);\n\n return node;\n },\n\n beginCycle(): void {\n nextLive = new Map();\n inCycle = true;\n },\n\n clear(): void {\n for (const node of live.values()) node.remove();\n\n live.clear();\n nextLive.clear();\n stale.length = 0;\n inCycle = false;\n },\n\n endCycle(): void {\n if (!inCycle) return;\n\n inCycle = false;\n\n for (const [key, node] of live) {\n if (!nextLive.has(key)) {\n node.remove();\n stale.push(node);\n }\n }\n\n live = nextLive;\n },\n };\n}\n\n// ─── Implementation ────────────────────────────────────────────────────────────\n\nexport function createDomVirtualList<T>(options: DomVirtualListOptions<T>): DomVirtualListController<T> {\n if (typeof options.estimateSize === 'number') requirePositiveNumber(options.estimateSize, 'estimateSize');\n\n if (options.gap !== undefined) requireNonNegativeInteger(options.gap, 'gap');\n\n if (options.overscan !== undefined) validateOverscan(options.overscan);\n\n if (options.stickToBottom !== undefined && typeof options.stickToBottom !== 'boolean') {\n if (options.stickToBottom === null || Array.isArray(options.stickToBottom)) {\n throw new ScrollConfigurationError('stickToBottom must be a boolean or options object.');\n }\n\n if (options.stickToBottom.threshold !== undefined) {\n requireNonNegativeNumber(options.stickToBottom.threshold, 'stickToBottom.threshold');\n }\n }\n\n let currentItems: T[] = [];\n let isDestroyed = false;\n const ac = new AbortController();\n const listEl = options.listElement;\n\n // Pool must be declared before virtualizer since handleChange (passed as onChange)\n // is invoked during createVirtualizer initialization via computeVisible.\n const pool = createNodePool();\n\n // Virtualizer is lazily created on the first non-empty setItems call.\n let virtualizer: Virtualizer | null = null;\n\n function resolveKey(index: number): VirtualKey {\n const item = currentItems[index];\n\n if (item !== undefined && options.getItemKey) return options.getItemKey(index, item);\n\n return index;\n }\n\n function resolveEstimate(index: number): number {\n if (options.estimateSize === undefined) return DEFAULT_ESTIMATE_SIZE;\n\n if (typeof options.estimateSize === 'number') return options.estimateSize;\n\n const item = currentItems[index];\n\n return item !== undefined ? options.estimateSize(index, item) : DEFAULT_ESTIMATE_SIZE;\n }\n\n function applyListSize(totalSize: number): void {\n if (options.horizontal) {\n listEl.style.height = '';\n listEl.style.width = `${totalSize}px`;\n } else {\n listEl.style.height = `${totalSize}px`;\n listEl.style.width = '';\n }\n }\n\n /**\n * R10: Throw rather than silently produce `undefined as T`.\n * This catches bugs where `vi.index` is out of range for `currentItems`.\n */\n function toRenderItem(vi: VirtualItem): VirtualRenderItem<T> {\n const data = currentItems[vi.index];\n\n if (data === undefined) {\n throw new ScrollRangeError(\n `toRenderItem: index ${vi.index} is out of range (currentItems.length=${currentItems.length})`,\n );\n }\n\n return { ...vi, data };\n }\n\n function handleChange(state: VirtualizerState): void {\n applyListSize(state.totalSize);\n\n pool.beginCycle();\n\n // R5: try/finally ensures endCycle() runs even if render() throws, keeping\n // the pool in a consistent state.\n try {\n options.render({\n items: state.items.map(toRenderItem),\n listEl,\n recycle: (key, create) => pool.acquire(key, create),\n stickyItems: state.stickyItems.map(toRenderItem),\n totalSize: state.totalSize,\n });\n } finally {\n pool.endCycle();\n }\n }\n\n function clearAndReset(): void {\n pool.clear();\n\n if (options.clear) {\n options.clear(listEl);\n } else {\n listEl.textContent = '';\n }\n\n listEl.style.height = '';\n listEl.style.width = '';\n listEl.style.position = '';\n listEl.style.contain = '';\n }\n\n const DEFAULT_STICK_THRESHOLD = 48;\n\n function resolveStickToBottom(): { enabled: boolean; threshold: number } {\n const opt = options.stickToBottom;\n\n if (!opt) return { enabled: false, threshold: DEFAULT_STICK_THRESHOLD };\n\n if (opt === true) return { enabled: true, threshold: DEFAULT_STICK_THRESHOLD };\n\n return { enabled: opt.enabled ?? true, threshold: opt.threshold ?? DEFAULT_STICK_THRESHOLD };\n }\n\n function spawnVirtualizer(): Virtualizer {\n const v = createVirtualizer(options.scrollElement, {\n count: currentItems.length,\n estimateSize: resolveEstimate,\n gap: options.gap,\n getItemKey: resolveKey,\n horizontal: options.horizontal,\n measurementCache: options.measurementCache,\n onChange: handleChange,\n overscan: options.overscan ?? DEFAULT_OVERSCAN,\n sticky: options.sticky\n ? (index) => {\n const item = currentItems[index];\n\n return item !== undefined && options.sticky!(index, item);\n }\n : undefined,\n });\n\n virtualizer = v;\n listEl.style.position = 'relative';\n listEl.style.contain = 'layout';\n\n return v;\n }\n\n function _dispose(): void {\n if (isDestroyed) return;\n\n isDestroyed = true;\n ac.abort();\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n }\n\n return {\n // ── Virtualizer passthrough (R11) ──────────────────────────────────────\n get count() {\n return virtualizer?.count ?? 0;\n },\n\n get disposalSignal() {\n return ac.signal;\n },\n\n dispose: _dispose,\n\n get disposed() {\n return isDestroyed;\n },\n\n invalidate() {\n if (isDestroyed) return;\n\n virtualizer?.invalidate();\n },\n\n isAtEnd(threshold) {\n return virtualizer?.isAtEnd(threshold) ?? true;\n },\n\n get isScrolling() {\n return virtualizer?.isScrolling ?? false;\n },\n\n get items() {\n return virtualizer?.items ?? [];\n },\n\n measure(index, size) {\n if (isDestroyed) return;\n\n virtualizer?.measure(index, size);\n },\n\n measureBatch(entries) {\n if (isDestroyed) return;\n\n virtualizer?.measureBatch(entries);\n },\n\n measureEl(index, el) {\n if (isDestroyed) return () => {};\n\n return virtualizer?.measureEl(index, el) ?? (() => {});\n },\n\n refresh() {\n if (isDestroyed) return;\n\n virtualizer?.refresh();\n },\n\n get scrollOffset() {\n return virtualizer?.scrollOffset ?? 0;\n },\n\n scrollToBottom(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToBottom(scrollOptions);\n },\n\n scrollToIndex(index, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToIndex(index, scrollOptions);\n },\n\n scrollToOffset(offset, scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToOffset(offset, scrollOptions);\n },\n\n scrollToTop(scrollOptions) {\n if (isDestroyed) return;\n\n virtualizer?.scrollToTop(scrollOptions);\n },\n\n // ── DomVirtualList-specific ────────────────────────────────────────────\n setItems(items) {\n if (isDestroyed) return;\n\n // Read *before* mutating state — the \"was the list already at the end?\" check must\n // reflect the pre-update layout, not the one `render()` is about to produce below.\n const stick = resolveStickToBottom();\n const wasAtEnd = stick.enabled && (virtualizer?.isAtEnd(stick.threshold) ?? true);\n\n currentItems = items;\n\n if (items.length === 0) {\n virtualizer?.dispose();\n virtualizer = null;\n clearAndReset();\n\n return;\n }\n\n if (!virtualizer) {\n const v = spawnVirtualizer();\n\n if (wasAtEnd) v.scrollToBottom();\n\n return;\n }\n\n const countChanged = items.length !== virtualizer.count;\n\n // Only count needs explicit update — estimateSize and getItemKey are\n // closures that already reflect the latest currentItems automatically.\n virtualizer.update({ count: items.length });\n\n // When count changed, update() already triggered rebuild + computeVisible().\n // Only force re-emission when count is unchanged (data changed, count same).\n if (!countChanged) {\n // refresh() re-emits with current sizes for stable keys;\n // invalidate() clears position-based measurements when no stable keys.\n if (options.getItemKey) {\n virtualizer.refresh();\n } else {\n virtualizer.invalidate();\n }\n } else if (!options.getItemKey) {\n // Count changed AND no stable keys: position-based measurements are now\n // stale. Clear them so the next render remeasures from fresh estimates.\n virtualizer.invalidate();\n }\n\n if (wasAtEnd) virtualizer.scrollToBottom();\n },\n\n get stickyItems() {\n return virtualizer?.stickyItems ?? [];\n },\n\n [Symbol.dispose]: _dispose,\n\n get totalSize() {\n return virtualizer?.totalSize ?? 0;\n },\n };\n}\n\n// ─── F5: createVirtualScroller ────────────────────────────────────────────────\n\n/**\n * High-level factory that creates the scroll container and inner list element,\n * appends them to `container`, and returns a fully wired `DomVirtualListController`.\n *\n * @example\n * ```ts\n * const list = createVirtualScroller(document.getElementById('root')!, {\n * render({ items, listEl, recycle }) { … },\n * });\n * list.setItems(data);\n * ```\n */\nexport function createVirtualScroller<T>(\n container: HTMLElement,\n options: VirtualScrollerOptions<T>,\n): DomVirtualListController<T> {\n const scrollEl = document.createElement('div');\n\n scrollEl.style.cssText = options.horizontal\n ? 'overflow: auto hidden; width: 100%; height: 100%;'\n : 'overflow: hidden auto; width: 100%; height: 100%;';\n\n if (options.containerClass) scrollEl.className = options.containerClass;\n\n const listEl = document.createElement('div');\n\n scrollEl.appendChild(listEl);\n container.appendChild(scrollEl);\n\n let ctrl: DomVirtualListController<T>;\n\n try {\n ctrl = createDomVirtualList<T>({\n ...options,\n listElement: listEl,\n scrollElement: scrollEl,\n });\n } catch (e) {\n // Remove the scroll container if construction fails so we don't leak DOM nodes.\n scrollEl.remove();\n throw e;\n }\n\n // Override dispose and [Symbol.dispose] to also remove the scroll container.\n // Capture the original dispose before overwriting so there's no self-reference.\n const innerDispose = ctrl.dispose.bind(ctrl);\n\n return Object.assign(ctrl, {\n dispose() {\n innerDispose();\n scrollEl.remove();\n },\n [Symbol.dispose]() {\n innerDispose();\n scrollEl.remove();\n },\n });\n}\n"],"mappings":"kSAqGA,SAAS,GAAiB,CACxB,IAAI,EAAO,IAAI,IACX,EAAW,IAAI,IACb,EAAuB,CAAC,EAC1B,EAAU,GAEd,MAAO,CACL,QAAQ,EAAiB,EAAwC,CAC/D,GAAI,CAAC,EAAS,OAAO,EAAO,EAE5B,IAAM,EAAW,EAAK,IAAI,CAAG,EAE7B,GAAI,EAGF,OAFA,EAAS,IAAI,EAAK,CAAQ,EAEnB,EAGT,IAAM,EAAO,EAAM,IAAI,GAAK,EAAO,EAInC,OAFA,EAAS,IAAI,EAAK,CAAI,EAEf,CACT,EAEA,YAAmB,CACjB,EAAW,IAAI,IACf,EAAU,EACZ,EAEA,OAAc,CACZ,IAAK,IAAM,KAAQ,EAAK,OAAO,EAAG,EAAK,OAAO,EAE9C,EAAK,MAAM,EACX,EAAS,MAAM,EACf,EAAM,OAAS,EACf,EAAU,EACZ,EAEA,UAAiB,CACV,KAEL,GAAU,GAEV,IAAK,GAAM,CAAC,EAAK,KAAS,EACnB,EAAS,IAAI,CAAG,IACnB,EAAK,OAAO,EACZ,EAAM,KAAK,CAAI,GAInB,EAAO,CATG,CAUZ,CACF,CACF,CAIA,SAAgB,EAAwB,EAAgE,CAOtG,GANI,OAAO,EAAQ,cAAiB,UAAU,EAAsB,EAAQ,aAAc,cAAc,EAEpG,EAAQ,MAAQ,IAAA,IAAW,EAA0B,EAAQ,IAAK,KAAK,EAEvE,EAAQ,WAAa,IAAA,IAAW,EAAiB,EAAQ,QAAQ,EAE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B,GAAU,EAAY,eAAe,CAC3C,EAEA,IAAI,aAAc,CAChB,OAAO,GAAa,aAAe,CAAC,CACtC,GAEC,OAAO,SAAU,EAElB,IAAI,WAAY,CACd,OAAO,GAAa,WAAa,CACnC,CACF,CACF,CAgBA,SAAgB,EACd,EACA,EAC6B,CAC7B,IAAM,EAAW,SAAS,cAAc,KAAK,EAE7C,EAAS,MAAM,QAAU,EAAQ,WAC7B,oDACA,oDAEA,EAAQ,iBAAgB,EAAS,UAAY,EAAQ,gBAEzD,IAAM,EAAS,SAAS,cAAc,KAAK,EAE3C,EAAS,YAAY,CAAM,EAC3B,EAAU,YAAY,CAAQ,EAE9B,IAAI,EAEJ,GAAI,CACF,EAAO,EAAwB,CAC7B,GAAG,EACH,YAAa,EACb,cAAe,CACjB,CAAC,CACH,OAAS,EAAG,CAGV,MADA,EAAS,OAAO,EACV,CACR,CAIA,IAAM,EAAe,EAAK,QAAQ,KAAK,CAAI,EAE3C,OAAO,OAAO,OAAO,EAAM,CACzB,SAAU,CACR,EAAa,EACb,EAAS,OAAO,CAClB,EACA,CAAC,OAAO,UAAW,CACjB,EAAa,EACb,EAAS,OAAO,CAClB,CACF,CAAC,CACH"}
|
package/dist/errors.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{};exports.ScrollError=e,exports.ScrollRangeError=
|
|
1
|
+
var e=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{},n=class extends e{};exports.ScrollConfigurationError=t,exports.ScrollError=e,exports.ScrollRangeError=n;
|
|
2
2
|
//# sourceMappingURL=errors.cjs.map
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all scroll errors. */\nexport class ScrollError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is ScrollError {\n return err instanceof ScrollError;\n }\n}\n\n/** Thrown when a virtual-list index is out of bounds. */\nexport class ScrollRangeError extends ScrollError {}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CAEA,OAAO,GAAG,EAAkC,CAC1C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAsC,CAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all scroll errors. */\nexport class ScrollError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is ScrollError {\n return err instanceof ScrollError;\n }\n}\n\n/** Thrown when a virtualizer receives an invalid static configuration. */\nexport class ScrollConfigurationError extends ScrollError {}\n\n/** Thrown when a virtual-list index is out of bounds. */\nexport class ScrollRangeError extends ScrollError {}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CAEA,OAAO,GAAG,EAAkC,CAC1C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAA8C,CAAY,CAAC,EAG9C,EAAb,cAAsC,CAAY,CAAC"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ export declare class ScrollError extends Error {
|
|
|
3
3
|
constructor(message: string, opts?: ErrorOptions);
|
|
4
4
|
static is(err: unknown): err is ScrollError;
|
|
5
5
|
}
|
|
6
|
+
/** Thrown when a virtualizer receives an invalid static configuration. */
|
|
7
|
+
export declare class ScrollConfigurationError extends ScrollError {
|
|
8
|
+
}
|
|
6
9
|
/** Thrown when a virtual-list index is out of bounds. */
|
|
7
10
|
export declare class ScrollRangeError extends ScrollError {
|
|
8
11
|
}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC,qBAAa,WAAY,SAAQ,KAAK;gBACxB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;IAMhD,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,WAAW;CAG5C;AAED,yDAAyD;AACzD,qBAAa,gBAAiB,SAAQ,WAAW;CAAG"}
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC,qBAAa,WAAY,SAAQ,KAAK;gBACxB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;IAMhD,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,WAAW;CAG5C;AAED,0EAA0E;AAC1E,qBAAa,wBAAyB,SAAQ,WAAW;CAAG;AAE5D,yDAAyD;AACzD,qBAAa,gBAAiB,SAAQ,WAAW;CAAG"}
|
package/dist/errors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{};export{e as ScrollError,
|
|
1
|
+
var e=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{},n=class extends e{};export{t as ScrollConfigurationError,e as ScrollError,n as ScrollRangeError};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all scroll errors. */\nexport class ScrollError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is ScrollError {\n return err instanceof ScrollError;\n }\n}\n\n/** Thrown when a virtual-list index is out of bounds. */\nexport class ScrollRangeError extends ScrollError {}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CAEA,OAAO,GAAG,EAAkC,CAC1C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAsC,CAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all scroll errors. */\nexport class ScrollError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is ScrollError {\n return err instanceof ScrollError;\n }\n}\n\n/** Thrown when a virtualizer receives an invalid static configuration. */\nexport class ScrollConfigurationError extends ScrollError {}\n\n/** Thrown when a virtual-list index is out of bounds. */\nexport class ScrollRangeError extends ScrollError {}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAoB,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CAEA,OAAO,GAAG,EAAkC,CAC1C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAA8C,CAAY,CAAC,EAG9C,EAAb,cAAsC,CAAY,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_utils.cjs"),t=require("./
|
|
1
|
+
const e=require("./_utils.cjs"),t=require("./_validation.cjs"),n=require("./_adapter.cjs"),r=require("./_axis1d.cjs"),i=require("./_alignment.cjs");function a(a,o){typeof o.estimateRowSize==`number`&&t.requirePositiveNumber(o.estimateRowSize,`estimateRowSize`),typeof o.estimateColSize==`number`&&t.requirePositiveNumber(o.estimateColSize,`estimateColSize`),o.initialScrollTop!==void 0&&t.requireNonNegativeNumber(o.initialScrollTop,`initialScrollTop`),o.initialScrollLeft!==void 0&&t.requireNonNegativeNumber(o.initialScrollLeft,`initialScrollLeft`),o.rowGap!==void 0&&t.requireNonNegativeInteger(o.rowGap,`rowGap`),o.colGap!==void 0&&t.requireNonNegativeInteger(o.colGap,`colGap`),o.overscanY!==void 0&&t.validateOverscan(o.overscanY,`overscanY`),o.overscanX!==void 0&&t.validateOverscan(o.overscanX,`overscanX`);let s=t.requireNonNegativeInteger(o.rowCount,`rowCount`),c=t.requireNonNegativeInteger(o.colCount,`colCount`),l=e.resolveEstimateFn(o.estimateRowSize,36),u=e.resolveEstimateFn(o.estimateColSize,36),d=e.normalizeOverscan(o.overscanY,3),f=e.normalizeOverscan(o.overscanX,3),p=o.onChange,m=o.onRangeChange,h=o.rowMeasurementCache??new Map,g=o.colMeasurementCache??new Map,_=0,v=0,y=0,b=0,x=[],S=[],C=!1,w=r.createAxis1D(s,e=>h.get(e)??l(e),e.toNonNegativeInt(o.rowGap??0)),T=r.createAxis1D(c,e=>g.get(e)??u(e),e.toNonNegativeInt(o.colGap??0)),E=!1;function D(e){let t=Number.isFinite(e)?e:0;return Math.min(Math.max(0,w.totalSize-y),Math.max(0,t))}function O(e){let t=Number.isFinite(e)?e:0;return Math.min(Math.max(0,T.totalSize-b),Math.max(0,t))}function k(){if(C)return;let e=w.totalSize,t=T.totalSize;if(s===0||c===0||y<=0||b<=0){(w.prevStart!==-1||w.prevTotalSize!==e||T.prevTotalSize!==t)&&(w.commitDedup(-1,-1),T.commitDedup(-1,-1),x=[],S=[],p?.({cols:[],rows:[],totalHeight:e,totalWidth:t}));return}let{renderEnd:n,renderStart:r}=w.computeRange(_,_+y,d.start,d.end),{renderEnd:i,renderStart:a}=T.computeRange(v,v+b,f.start,f.end),o=w.isDedupSame(r,n),l=T.isDedupSame(a,i);if(o&&l)return;w.commitDedup(r,n),T.commitDedup(a,i),(!o||!l)&&m&&m({firstCol:a,firstRow:r,lastCol:i,lastRow:n});let u=[];for(let e=r;e<=n;e++)u.push(w.itemAt(e));let h=[];for(let e=a;e<=i;e++)h.push(T.itemAt(e));x=u,S=h,p?.({cols:S,rows:x,totalHeight:e,totalWidth:t})}function A(t,n){if(!Number.isFinite(t))return!1;let r=Math.floor(t);if(r<0||r>=s)return!1;let i=e.toPositiveNumber(n,-1);return i<=0||h.get(r)===i?!1:(h.set(r,i),w.markChanged(r),!0)}function j(t,n){if(!Number.isFinite(t))return!1;let r=Math.floor(t);if(r<0||r>=c)return!1;let i=e.toPositiveNumber(n,-1);return i<=0||g.get(r)===i?!1:(g.set(r,i),T.markChanged(r),!0)}function M(){E||(E=!0,queueMicrotask(()=>{E=!1;let e=w.consumeMinChangedIndex();e!==1/0&&w.rebuildFrom(e);let t=T.consumeMinChangedIndex();t!==1/0&&T.rebuildFrom(t),k()}))}function N(e,t){C||A(e,t)&&M()}function P(e,t){C||j(e,t)&&M()}function F(e,t){if(C)return;let n=!1;for(let{index:t,size:r}of e)A(t,r)&&(n=!0);for(let{index:e,size:r}of t)j(e,r)&&(n=!0);n&&M()}function I(t,n){return C?()=>{}:e.observeResize(G.signal,n,e=>N(t,e.contentRect.height))}function L(t,n){return C?()=>{}:e.observeResize(G.signal,n,e=>P(t,e.contentRect.width))}function R(){C||(h.clear(),g.clear(),w.rebuild(!0),T.rebuild(!0),k())}function z(){C||(w.rebuild(!0),T.rebuild(!0),k())}function B(t){if(C)return;let n=e.toNonNegativeInt(t);if(n===0)return;s+=n,w.setCount(s),w.rebuild(!0);let r=w.startAt(n),i=D(_+r);Y.scrollTo(v,i,`auto`),_=i,k()}function V(e,t={}){if(C||s===0)return;let n=Math.max(0,Math.min(Math.floor(Number.isFinite(e)?e:0),s-1)),r=t.behavior??`auto`,a=w.startAt(n),o=w.sizeAt(n),c=i.alignOffset(a,a+o,o,_,y,t.rowAlign??`auto`);c!==null&&Y.scrollTo(v,D(c),r)}function H(e,t={}){if(C||c===0)return;let n=Math.max(0,Math.min(Math.floor(Number.isFinite(e)?e:0),c-1)),r=t.behavior??`auto`,a=T.startAt(n),o=T.sizeAt(n),s=i.alignOffset(a,a+o,o,v,b,t.colAlign??`auto`);s!==null&&Y.scrollTo(O(s),_,r)}function U(e,t,n={}){if(C||s===0||c===0)return;let r=Math.max(0,Math.min(Math.floor(Number.isFinite(e)?e:0),s-1)),a=Math.max(0,Math.min(Math.floor(Number.isFinite(t)?t:0),c-1)),o=n.behavior??`auto`,l=w.startAt(r),u=w.sizeAt(r),d=T.startAt(a),f=T.sizeAt(a),p=i.alignOffset(l,l+u,u,_,y,n.rowAlign??`auto`),m=i.alignOffset(d,d+f,f,v,b,n.colAlign??`auto`);(p!==null||m!==null)&&Y.scrollTo(m===null?v:O(m),p===null?_:D(p),o)}function W(n){if(C)return;n.rowCount!==void 0&&t.requireNonNegativeInteger(n.rowCount,`rowCount`),n.colCount!==void 0&&t.requireNonNegativeInteger(n.colCount,`colCount`),typeof n.estimateRowSize==`number`&&t.requirePositiveNumber(n.estimateRowSize,`estimateRowSize`),typeof n.estimateColSize==`number`&&t.requirePositiveNumber(n.estimateColSize,`estimateColSize`),n.rowGap!==void 0&&t.requireNonNegativeInteger(n.rowGap,`rowGap`),n.colGap!==void 0&&t.requireNonNegativeInteger(n.colGap,`colGap`),n.overscanY!==void 0&&t.validateOverscan(n.overscanY,`overscanY`),n.overscanX!==void 0&&t.validateOverscan(n.overscanX,`overscanX`);let r=!1,i=!1,a=!1;if(Object.hasOwn(n,`onChange`)&&(p=n.onChange),Object.hasOwn(n,`onRangeChange`)&&(m=n.onRangeChange),n.rowCount!==void 0){let e=n.rowCount;e!==s&&(s=e,w.setCount(s),r=!0)}if(n.colCount!==void 0){let e=n.colCount;e!==c&&(c=e,T.setCount(c),i=!0)}if(n.rowGap!==void 0){let e=n.rowGap;e!==w.gap&&(w.setGap(e),r=!0)}if(n.colGap!==void 0){let e=n.colGap;e!==T.gap&&(T.setGap(e),i=!0)}if(`estimateRowSize`in n&&(l=e.resolveEstimateFn(n.estimateRowSize,36),h.clear(),r=!0),`estimateColSize`in n&&(u=e.resolveEstimateFn(n.estimateColSize,36),g.clear(),i=!0),n.overscanY!==void 0){let t=e.normalizeOverscan(n.overscanY,3);(t.start!==d.start||t.end!==d.end)&&(d=t,a=!0)}if(n.overscanX!==void 0){let t=e.normalizeOverscan(n.overscanX,3);(t.start!==f.start||t.end!==f.end)&&(f=t,a=!0)}r&&w.rebuild(!0),i&&T.rebuild(!0),(r||i||a)&&k()}let G=new AbortController;function K(){C||(C=!0,G.abort(),Y.detach())}function q(){_=D(Y.y.readOffset()),v=O(Y.x.readOffset()),k()}function J(){y=Y.y.readViewportSize(),b=Y.x.readViewportSize(),k()}let Y=n.createScrollAdapter(a,q,J);return w.rebuild(!0),T.rebuild(!0),y=Y.y.readViewportSize(),b=Y.x.readViewportSize(),o.initialScrollTop===void 0?o.initialScrollLeft!==void 0&&Y.scrollTo(O(o.initialScrollLeft),0,`auto`):Y.scrollTo(o.initialScrollLeft??0,D(o.initialScrollTop),`auto`),_=D(Y.y.readOffset()),v=O(Y.x.readOffset()),k(),{get cols(){return S},get disposalSignal(){return G.signal},dispose:K,get disposed(){return C},invalidate:R,measureBatch:F,measureColEl:L,measureColumn:P,measureRow:N,measureRowEl:I,prependRows:B,refresh:z,get rows(){return x},get scrollLeft(){return v},scrollToCell:U,scrollToColumn:H,get scrollTop(){return _},scrollToRow:V,[Symbol.dispose]:K,get totalHeight(){return w.totalSize},get totalWidth(){return T.totalSize},update:W}}exports.createGridVirtualizer=a;
|
|
2
2
|
//# sourceMappingURL=grid-virtualizer.cjs.map
|