virtua 0.2.2 → 0.2.4
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 +71 -17
- package/lib/core/dom.d.ts +1 -0
- package/lib/core/resizer.d.ts +13 -0
- package/lib/core/scroller.d.ts +1 -6
- package/lib/core/store.d.ts +16 -12
- package/lib/core/utils.d.ts +1 -1
- package/lib/index.d.ts +4 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +1 -1
- package/lib/index.mjs.map +1 -1
- package/lib/react/VGrid.d.ts +96 -0
- package/lib/react/VList.d.ts +16 -4
- package/lib/react/types.d.ts +2 -0
- package/lib/react/utils.d.ts +2 -0
- package/package.json +19 -18
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/src/core/utils.ts","../src/src/core/cache.ts","../src/src/react/useIsomorphicLayoutEffect.ts","../src/src/react/useSyncExternalStore.ts","../src/src/react/utils.ts","../src/src/react/useStatic.ts","../src/src/react/useRefWithUpdate.ts","../src/src/react/VList.tsx","../src/src/core/store.ts","../src/src/core/scroller.ts"],"sourcesContent":["export const min = Math.min;\nexport const max = Math.max;\nexport const abs = Math.abs;\nexport const now = Date.now;\n\nexport const exists = <T>(v: T): v is Exclude<T, null | undefined> => v != null;\n\nexport const range = <T>(length: number, cb: (i: number) => T): T[] =>\n Array.from({ length }, (_, i) => cb(i));\n\nexport const debounce = <T extends (...args: any[]) => void>(\n fn: T,\n ms: number\n) => {\n let id: NodeJS.Timeout | undefined | null;\n\n const cancel = () => {\n if (exists(id)) {\n clearTimeout(id);\n }\n };\n const debouncedFn = () => {\n cancel();\n id = setTimeout(() => {\n id = null;\n fn();\n }, ms);\n };\n debouncedFn._cancel = cancel;\n return debouncedFn;\n};\n\nexport const throttle = <T extends (...args: any[]) => void>(\n fn: T,\n ms: number\n) => {\n let time = now() - ms;\n return (...args: Parameters<T>) => {\n const n = now();\n if (time + ms < n) {\n time = n;\n fn(...args);\n }\n };\n};\n","import type { DeepReadonly, Writeable } from \"./types\";\nimport { exists, max, min, range } from \"./utils\";\n\nexport const UNCACHED = -1;\n\nexport type Cache = DeepReadonly<{\n _defaultItemSize: number;\n _length: number;\n _sizes: number[];\n _measuredOffsetIndex: number;\n _offsets: number[];\n}>;\n\nexport const getItemSize = (cache: Cache, index: number): number => {\n const size = cache._sizes[index]!;\n return size === UNCACHED ? cache._defaultItemSize : size;\n};\n\nexport const setItemSize = (\n cache: Writeable<Cache>,\n index: number,\n size: number\n) => {\n cache._sizes[index] = size;\n // mark as dirty\n cache._measuredOffsetIndex = min(index, cache._measuredOffsetIndex);\n};\n\nconst computeOffset = (\n cache: Writeable<Cache>,\n index: number,\n isTotal?: boolean\n): number => {\n if (!cache._length) return 0;\n if (cache._measuredOffsetIndex >= index) {\n if (isTotal) {\n return cache._offsets[index]! + getItemSize(cache, index);\n } else {\n return cache._offsets[index]!;\n }\n }\n\n let i = cache._measuredOffsetIndex;\n let top = cache._offsets[i]!;\n while (i <= index) {\n cache._offsets[i] = top;\n if (i === index && !isTotal) {\n break;\n }\n top += getItemSize(cache, i);\n i++;\n }\n // mark as measured\n cache._measuredOffsetIndex = index;\n return top;\n};\n\nexport const computeTotalSize = (cache: Writeable<Cache>): number => {\n return computeOffset(cache, cache._length - 1, true);\n};\n\nexport const computeStartOffset = (\n cache: Writeable<Cache>,\n index: number\n): number => {\n return computeOffset(cache, index);\n};\n\nconst findIndex = (cache: Cache, i: number, distance: number): number => {\n let sum = 0;\n if (distance >= 0) {\n // search forward\n while (i < cache._length - 1) {\n const h = getItemSize(cache, i++);\n if ((sum += h) >= distance) {\n if (sum - h / 2 >= distance) {\n i--;\n }\n break;\n }\n }\n } else {\n // search backward\n while (i > 0) {\n const h = getItemSize(cache, --i);\n if ((sum -= h) <= distance) {\n if (sum + h / 2 < distance) {\n i++;\n }\n break;\n }\n }\n }\n\n return min(max(i, 0), cache._length - 1);\n};\n\nexport const findStartIndexWithOffset = (\n cache: Cache,\n offset: number,\n prevStartIndex: number,\n prevOffset: number\n): number => {\n return findIndex(cache, prevStartIndex, offset - prevOffset);\n};\n\nexport const findEndIndex = findIndex;\n\nexport const hasUnmeasuredItemsInRange = (\n cache: Cache,\n startIndex: number,\n endIndex: number\n): boolean => {\n for (let i = startIndex; i <= endIndex; i++) {\n if (cache._sizes[i] === UNCACHED) {\n return true;\n }\n }\n return false;\n};\n\nexport const resetCache = (\n length: number,\n itemSize: number,\n cache?: Cache\n): Cache => {\n return {\n _defaultItemSize: itemSize,\n _length: length,\n _measuredOffsetIndex: cache\n ? min(cache._measuredOffsetIndex, length - 1)\n : 0,\n _sizes: range(length, (i) => {\n const size = cache && cache._sizes[i];\n if (exists(size)) {\n return size;\n }\n return UNCACHED;\n }),\n _offsets: range(length, (i) => {\n if (i === 0) {\n // first offset must be 0\n return 0;\n }\n const offset = cache && cache._offsets[i];\n if (exists(offset)) {\n return offset;\n }\n return UNCACHED;\n }),\n };\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\n// https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85\nexport const useIsomorphicLayoutEffect =\n typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n","import { useSyncExternalStore as _useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\n\nexport const useSyncExternalStore = <T>(\n subscibe: (onStoreChange: () => void) => () => void,\n getSnapShot: () => T\n): T => {\n return _useSyncExternalStore(subscibe, getSnapShot, getSnapShot);\n};\n","export const refKey = \"current\";\n","import { useRef } from \"react\";\nimport { refKey } from \"./utils\";\n\nexport const useStatic = <T>(init: () => T): T => {\n const ref = useRef<T>();\n return ref[refKey] || (ref[refKey] = init());\n};\n","import { useRef } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { refKey } from \"./utils\";\n\nexport const useRefWithUpdate = <T>(value: T) => {\n const ref = useRef<T>(value);\n\n useIsomorphicLayoutEffect(() => {\n ref[refKey] = value;\n }, [value]);\n\n return ref;\n};\n","import {\n Children,\n memo,\n useRef,\n useMemo,\n CSSProperties,\n ReactElement,\n forwardRef,\n useImperativeHandle,\n ReactNode,\n useEffect,\n RefObject,\n useState,\n ReactFragment,\n} from \"react\";\nimport { VirtualStore, createVirtualStore } from \"../core/store\";\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore\";\nimport { exists, max, min } from \"../core/utils\";\nimport { createScroller, Scroller } from \"../core/scroller\";\nimport { refKey } from \"./utils\";\nimport { useStatic } from \"./useStatic\";\nimport { useRefWithUpdate } from \"./useRefWithUpdate\";\n\ntype ItemProps = {\n _children: ReactNode;\n _scroller: Scroller;\n _store: VirtualStore;\n _index: number;\n _element: \"div\";\n};\n\nconst Item = memo(\n ({\n _children: children,\n _scroller: scroller,\n _store: store,\n _index: index,\n _element: Element,\n }: ItemProps): ReactElement => {\n const ref = useRef<HTMLDivElement>(null);\n\n const offset = useSyncExternalStore(store._subscribe, () =>\n store._getItemOffset(index)\n );\n const hide = useSyncExternalStore(store._subscribe, () =>\n store._isUnmeasuredItem(index)\n );\n\n // The index may be changed if elements are inserted to or removed from the start of props.children\n useIsomorphicLayoutEffect(\n () => scroller._initItem(ref[refKey]!, index),\n [index]\n );\n\n return (\n <Element\n ref={ref}\n style={useMemo((): CSSProperties => {\n const isHorizontal = store._isHorizontal();\n const leftOrRightKey = store._isRtl() ? \"right\" : \"left\";\n const style: CSSProperties = {\n margin: 0,\n padding: 0,\n position: \"absolute\",\n [isHorizontal ? \"height\" : \"width\"]: \"100%\",\n [isHorizontal ? \"top\" : leftOrRightKey]: 0,\n [isHorizontal ? leftOrRightKey : \"top\"]: offset,\n visibility: hide ? \"hidden\" : \"visible\",\n // willChange: \"transform\",\n };\n if (isHorizontal) {\n style.display = \"flex\";\n }\n return style;\n }, [offset, hide])}\n >\n {children}\n </Element>\n );\n }\n);\n\nconst isInvalidElement = <T extends ReactNode>(\n e: T\n): e is Extract<T, null | undefined | boolean> =>\n !exists(e) || typeof e === \"boolean\";\n\nexport type WindowComponentAttributes = Pick<\n React.HTMLAttributes<HTMLElement>,\n \"className\" | \"style\" | \"id\" | \"role\" | \"tabIndex\"\n> &\n React.AriaAttributes;\n\n/**\n * Props of customized scrollable component.\n */\nexport interface CustomWindowComponentProps {\n children: ReactNode;\n scrollSize: number;\n scrolling: boolean;\n horizontal: boolean;\n attrs: WindowComponentAttributes;\n}\n\nconst DefaultWindow = forwardRef<any, CustomWindowComponentProps>(\n (\n { children, scrollSize, scrolling, horizontal, attrs },\n ref\n ): ReactElement => {\n return (\n <div ref={ref} {...attrs}>\n <div\n style={useMemo((): CSSProperties => {\n return {\n position: \"relative\",\n visibility: \"hidden\",\n width: horizontal ? scrollSize : \"100%\",\n height: horizontal ? \"100%\" : scrollSize,\n pointerEvents: scrolling ? \"none\" : \"auto\",\n };\n }, [scrollSize, scrolling])}\n >\n {children}\n </div>\n </div>\n );\n }\n);\n\nexport type CustomWindowComponent = typeof DefaultWindow;\n\nconst Window = ({\n _children: children,\n _ref: ref,\n _store: store,\n _element: Element,\n _scrolling: scrolling,\n _attrs: attrs,\n}: {\n _children: ReactNode;\n _ref: RefObject<HTMLDivElement>;\n _store: VirtualStore;\n _element: CustomWindowComponent;\n _scrolling: boolean;\n _attrs: WindowComponentAttributes;\n}) => {\n const scrollSize = useSyncExternalStore(\n store._subscribe,\n store._getScrollSize\n );\n\n const horizontal = store._isHorizontal();\n\n return (\n <Element\n ref={ref}\n scrollSize={scrollSize}\n scrolling={scrolling}\n horizontal={horizontal}\n attrs={useMemo(\n () => ({\n ...attrs,\n style: {\n overflow: horizontal ? \"auto hidden\" : \"hidden auto\",\n contain: \"strict\",\n // transform: \"translate3d(0px, 0px, 0px)\",\n // willChange: \"scroll-position\",\n // backfaceVisibility: \"hidden\",\n width: \"100%\",\n height: \"100%\",\n padding: 0,\n margin: 0,\n ...attrs.style,\n },\n }),\n [attrs]\n )}\n >\n {children}\n </Element>\n );\n};\n\n/**\n * Props of customized item component.\n */\nexport interface CustomItemComponentProps {\n style: CSSProperties;\n children: ReactNode;\n}\n\nexport type CustomItemComponent = React.ForwardRefExoticComponent<\n React.PropsWithoutRef<CustomItemComponentProps> & React.RefAttributes<any>\n>;\n\ntype CustomItemComponentOrElement =\n | keyof JSX.IntrinsicElements\n | CustomItemComponent;\n\n/**\n * Methods of {@link VList}.\n */\nexport interface VListHandle {\n /**\n * Get current scrollTop or scrollLeft.\n */\n readonly scrollOffset: number;\n /**\n * Get current scrollHeight or scrollWidth.\n */\n readonly scrollSize: number;\n /**\n * Get current offsetHeight or offsetWidth.\n */\n readonly viewportSize: number;\n /**\n * Scroll to the item specified by index.\n * @param index index of item\n */\n scrollToIndex(index: number): void;\n /**\n * Scroll to the given offset.\n * @param offset offset from start\n */\n scrollTo(offset: number): void;\n /**\n * Scroll by the given offset.\n * @param offset offset from current position\n */\n scrollBy(offset: number): void;\n}\n\n/**\n * Props of {@link VList}.\n */\nexport interface VListProps extends WindowComponentAttributes {\n /**\n * Elements rendered by this component.\n */\n children: ReactNode;\n /**\n * Item size hint for unmeasured items. It's recommended to specify this prop if item sizes are fixed and known, or much larger than the defaultValue. It will help to reduce scroll jump when items are measured.\n * @defaultValue 40\n */\n itemSize?: number;\n /**\n * Number of items to render above/below the visible bounds of the list. You can increase to avoid showing blank items in fast scrolling.\n * @defaultValue 4\n */\n overscan?: number;\n /**\n * If true, rendered as a horizontally scrollable list. Otherwise rendered as a vertically scrollable list.\n */\n horizontal?: boolean;\n /**\n * You have to set true if you use this component under `direction: rtl` style.\n */\n rtl?: boolean;\n /**\n * Customized element type for scrollable element. This element will get {@link CustomWindowComponentProps} as props.\n * @defaultValue {@link DefaultWindow}\n */\n element?: CustomWindowComponent;\n /**\n * Customized element type for item element. This element will get {@link CustomItemComponentProps} as props.\n * @defaultValue \"div\"\n */\n itemElement?: CustomItemComponentOrElement;\n /**\n * Callback invoked whenever scroll offset changes.\n * @param offset Current scrollTop or scrollLeft.\n */\n onScroll?: (offset: number) => void;\n /**\n * Callback invoked when scrolling stops.\n */\n onScrollStop?: () => void;\n /**\n * Callback invoked when visible items range changes.\n * @param payload `start` is the start index of viewable items. `end` is the end index of viewable items. `count` is the total count of items.\n */\n onRangeChange?: (payload: {\n start: number;\n end: number;\n count: number;\n }) => void;\n}\n\n/**\n * Virtualized list component. See {@link VListProps} and {@link VListHandle}.\n */\nexport const VList = forwardRef<VListHandle, VListProps>(\n (\n {\n children,\n itemSize: itemSizeProp = 40,\n overscan = 4,\n horizontal: horizontalProp,\n rtl: rtlProp,\n element = DefaultWindow,\n itemElement = \"div\",\n onScroll: onScrollProp,\n onScrollStop: onScrollStopProp,\n onRangeChange: onRangeChangeProp,\n ...windowAttrs\n },\n ref\n ): ReactElement => {\n // Memoize element array\n const elements = useMemo(() => {\n const arr: (ReactElement | ReactFragment | string | number)[] = [];\n Children.forEach(children, (e) => {\n if (isInvalidElement(e)) {\n return;\n }\n arr.push(e);\n });\n return arr;\n }, [children]);\n const count = elements.length;\n\n // https://github.com/facebook/react/issues/25191#issuecomment-1237456448\n const store = useStatic(() =>\n createVirtualStore(count, itemSizeProp, !!horizontalProp, !!rtlProp)\n );\n // The elements length and cached items length are different just after element is added/removed.\n store._updateCacheLength(count);\n\n const [startIndex, endIndex] = useSyncExternalStore(\n store._subscribe,\n store._getRange\n );\n const jump = useSyncExternalStore(store._subscribe, store._getJump);\n const rootRef = useRef<HTMLDivElement>(null);\n\n const onScroll = useRefWithUpdate(onScrollProp);\n const onScrollStop = useRefWithUpdate(onScrollStopProp);\n\n const [mountedIndexes, reset] = useState<Set<number>>(new Set<number>());\n const [scrolling, setScrolling] = useState(false);\n const scroller = useStatic(() =>\n createScroller(\n store,\n (offset) => {\n onScroll[refKey] && onScroll[refKey](offset);\n },\n (isScrolling) => {\n setScrolling(isScrolling);\n if (!isScrolling) {\n reset(new Set());\n onScrollStop[refKey] && onScrollStop[refKey]();\n }\n }\n )\n );\n\n useIsomorphicLayoutEffect(() => scroller._initRoot(rootRef[refKey]!), []);\n\n useIsomorphicLayoutEffect(() => {\n if (!jump.length) return;\n\n scroller._fixScrollJump(jump, startIndex);\n }, [jump]);\n\n useEffect(() => {\n if (!onRangeChangeProp) return;\n\n onRangeChangeProp({\n start: startIndex,\n end: endIndex,\n count,\n });\n }, [startIndex, endIndex]);\n\n useImperativeHandle(\n ref,\n () => {\n return {\n get scrollOffset() {\n return store._getScrollOffset();\n },\n get scrollSize() {\n return scroller._getActualScrollSize();\n },\n get viewportSize() {\n return store._getViewportSize();\n },\n scrollToIndex(index) {\n scroller._scrollToIndex(index, count);\n },\n scrollTo: scroller._scrollTo,\n scrollBy(offset) {\n scroller._scrollTo(store._getScrollOffset() + offset);\n },\n };\n },\n [count]\n );\n\n const startIndexWithMargin = max(startIndex - overscan, 0);\n const endIndexWithMargin = min(endIndex + overscan, count - 1);\n const items = useMemo(() => {\n const res: ReactElement[] = [];\n for (let i = startIndexWithMargin; i <= endIndexWithMargin; i++) {\n // https://github.com/sergi/virtual-list/commit/8e7e06dc63568334c1ab809ea83c1be36572e9ed\n mountedIndexes.add(i);\n }\n mountedIndexes.forEach((i) => {\n const e = elements[i];\n // This can be undefined when items are removed\n if (exists(e)) {\n res.push(\n <Item\n key={(e as { key?: ReactElement[\"key\"] })?.key || i}\n _scroller={scroller}\n _store={store}\n _index={i}\n _element={itemElement as \"div\"}\n _children={e}\n />\n );\n }\n });\n return res;\n }, [elements, mountedIndexes, startIndexWithMargin, endIndexWithMargin]);\n\n return (\n <Window\n _ref={rootRef}\n _store={store}\n _element={element}\n _scrolling={scrolling}\n _children={items}\n _attrs={windowAttrs}\n />\n );\n }\n);\n","import {\n findStartIndexWithOffset,\n resetCache,\n getItemSize,\n computeTotalSize,\n findEndIndex,\n computeStartOffset,\n Cache,\n UNCACHED,\n setItemSize,\n hasUnmeasuredItemsInRange,\n} from \"./cache\";\nimport type { Writeable } from \"./types\";\n\nexport type ScrollJump = Readonly<[index: number, sizeDiff: number][]>;\nexport type ItemResize = [index: number, size: number];\ntype ItemsRange = [startIndex: number, endIndex: number];\n\nexport const ACTION_UPDATE_ITEM_SIZES = 1;\nexport const ACTION_UPDATE_VIEWPORT = 2;\nexport const ACTION_HANDLE_SCROLL = 3;\n\ntype Actions =\n | [type: typeof ACTION_UPDATE_ITEM_SIZES, entries: ItemResize[]]\n | [\n type: typeof ACTION_UPDATE_VIEWPORT,\n rect: { _width: number; _height: number }\n ]\n | [type: typeof ACTION_HANDLE_SCROLL, offset: number];\n\nexport type VirtualStore = {\n _getRange(): ItemsRange;\n _isUnmeasuredItem(index: number): boolean;\n _hasUnmeasuredItemsInRange(startIndex: number): boolean;\n _getItemOffset(index: number): number;\n _getScrollOffset(): number;\n _getViewportSize(): number;\n _getScrollSize(): number;\n _getJump(): ScrollJump;\n _isHorizontal(): boolean;\n _isRtl(): boolean;\n _getItemIndexForScrollTo(offset: number): number;\n _waitForScrollDestinationItemsMeasured(): Promise<void>;\n _subscribe(cb: () => void): () => void;\n _update(...action: Actions): void;\n _updateCacheLength(length: number): void;\n};\n\nexport const createVirtualStore = (\n itemCount: number,\n itemSize: number,\n isHorizontal: boolean,\n isRtl: boolean\n): VirtualStore => {\n let viewportWidth = 0;\n let viewportHeight = 0;\n let scrollOffset = 0;\n let jump: ScrollJump = [];\n let cache = resetCache(itemCount, itemSize);\n let _prevRange: ItemsRange = [0, 0];\n let _scrollToQueue: [() => void, () => void] | undefined;\n\n const subscribers = new Set<() => void>();\n const getViewportSize = (): number =>\n isHorizontal ? viewportWidth : viewportHeight;\n\n return {\n _getRange() {\n const [prevStartIndex, prevEndIndex] = _prevRange;\n const prevOffset = computeStartOffset(\n cache as Writeable<Cache>,\n prevStartIndex\n );\n const start = findStartIndexWithOffset(\n cache,\n scrollOffset,\n prevStartIndex,\n prevOffset\n );\n const end = findEndIndex(cache, start, getViewportSize());\n if (prevStartIndex === start && prevEndIndex === end) {\n return _prevRange;\n }\n return (_prevRange = [start, end]);\n },\n _isUnmeasuredItem(index) {\n return cache._sizes[index] === UNCACHED;\n },\n _hasUnmeasuredItemsInRange(startIndex) {\n return hasUnmeasuredItemsInRange(\n cache,\n startIndex,\n findEndIndex(cache, startIndex, getViewportSize())\n );\n },\n _getItemOffset(index) {\n return computeStartOffset(cache as Writeable<Cache>, index);\n },\n _getScrollOffset() {\n return scrollOffset;\n },\n _getViewportSize() {\n return getViewportSize();\n },\n _getScrollSize() {\n return computeTotalSize(cache as Writeable<Cache>);\n },\n _getJump() {\n return jump;\n },\n _isHorizontal() {\n return isHorizontal;\n },\n _isRtl() {\n return isRtl;\n },\n _getItemIndexForScrollTo(offset) {\n return findStartIndexWithOffset(cache, offset, 0, 0);\n },\n _waitForScrollDestinationItemsMeasured() {\n if (_scrollToQueue) {\n // Cancel waiting scrollTo\n _scrollToQueue[1]();\n }\n // The measurement will be done asynchronously and the timing is not predictable so we use promise.\n // For example, ResizeObserver may not fire when window is not visible.\n return new Promise((resolve, reject) => {\n _scrollToQueue = [\n () => {\n // HACK: It should be resolved in the next microtask that is after React's render\n Promise.resolve().then(() => {\n resolve();\n _scrollToQueue = undefined;\n });\n },\n reject,\n ];\n });\n },\n _subscribe(cb) {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n _update(type, payload) {\n const mutated = ((): boolean => {\n switch (type) {\n case ACTION_UPDATE_ITEM_SIZES: {\n const updated = payload.filter(\n ([index, size]) => cache._sizes[index] !== size\n );\n // Skip if all items are cached and not updated\n if (!updated.length) {\n return false;\n }\n\n const updatedJump: [index: number, sizeDiff: number][] = [];\n updated.forEach(([index, size]) => {\n updatedJump.push([index, size - getItemSize(cache, index)]);\n setItemSize(cache as Writeable<Cache>, index, size);\n });\n jump = updatedJump;\n return true;\n }\n case ACTION_UPDATE_VIEWPORT: {\n if (\n viewportWidth === payload._width &&\n viewportHeight === payload._height\n ) {\n return false;\n }\n viewportWidth = payload._width;\n viewportHeight = payload._height;\n return true;\n }\n case ACTION_HANDLE_SCROLL: {\n const prevOffset = scrollOffset;\n return (scrollOffset = payload) !== prevOffset;\n }\n }\n })();\n\n if (mutated) {\n subscribers.forEach((cb) => {\n cb();\n });\n if (_scrollToQueue && type === ACTION_UPDATE_ITEM_SIZES) {\n _scrollToQueue[0]();\n }\n }\n },\n _updateCacheLength(length) {\n // It's ok to be updated in render because states should be calculated consistently regardless cache length\n if (cache._length === length) return;\n cache = resetCache(length, itemSize, cache);\n },\n };\n};\n","import {\n ACTION_HANDLE_SCROLL,\n ACTION_UPDATE_ITEM_SIZES,\n ACTION_UPDATE_VIEWPORT,\n ItemResize,\n ScrollJump,\n VirtualStore,\n} from \"./store\";\nimport { abs, debounce, throttle, exists, max, min } from \"./utils\";\n\nexport const SCROLL_STOP = 0;\nexport const SCROLL_DOWN = 1;\nexport const SCROLL_UP = 2;\nexport const SCROLL_MANUAL = 3;\ntype ScrollDirection =\n | typeof SCROLL_STOP\n | typeof SCROLL_DOWN\n | typeof SCROLL_UP\n | typeof SCROLL_MANUAL;\n\nexport type Scroller = {\n _initRoot: (rootElement: HTMLElement) => () => void;\n _initItem: (itemElement: HTMLElement, index: number) => () => void;\n _getActualScrollSize: () => number;\n _scrollTo: (offset: number) => void;\n _scrollToIndex: (index: number, count: number) => void;\n _fixScrollJump: (jump: ScrollJump, startIndex: number) => void;\n};\n\nexport const createScroller = (\n store: VirtualStore,\n emitScrollOffsetChange: (offset: number) => void,\n emitScrollStateChange: (scrolling: boolean) => void\n): Scroller => {\n let prevOffset = -1;\n let scrollDirection: ScrollDirection = SCROLL_STOP;\n let resized = false;\n let isNegativeOffset: boolean | undefined;\n let rootElement: HTMLElement | undefined;\n let _ro: ResizeObserver | undefined;\n const isHorizontal = store._isHorizontal();\n const isRtl = store._isRtl();\n const scrollToKey = isHorizontal ? \"scrollLeft\" : \"scrollTop\";\n const mountedIndexes = new WeakMap<Element, number>();\n const getResizeObserver = (): ResizeObserver => {\n // Initialize ResizeObserver lazily for SSR\n return (\n _ro ||\n (_ro = new ResizeObserver((entries) => {\n // https://www.w3.org/TR/resize-observer/#intro\n const resizes: ItemResize[] = [];\n for (const entry of entries) {\n if (entry.target === rootElement) {\n store._update(ACTION_UPDATE_VIEWPORT, {\n _width: entry.contentRect.width,\n _height: entry.contentRect.height,\n });\n } else {\n const index = mountedIndexes.get(entry.target);\n if (exists(index)) {\n resizes.push([\n index,\n entry.contentRect[isHorizontal ? \"width\" : \"height\"],\n ]);\n }\n }\n }\n\n if (resizes.length) {\n store._update(ACTION_UPDATE_ITEM_SIZES, resizes);\n resized = true;\n }\n }))\n );\n };\n const getActualScrollSize = (): number => {\n if (!rootElement) return 0;\n // Use element's scrollHeight/scrollWidth instead of stored scrollSize.\n // This is because stored size may differ from the actual size, for example when a new item is added and not yet measured.\n return store._isHorizontal()\n ? rootElement.scrollWidth\n : rootElement.scrollHeight;\n };\n const updateScrollPosition = (offset: number, diff?: boolean) => {\n if (!rootElement) return;\n if (isRtl) {\n if (!exists(isNegativeOffset)) {\n // Assume offset type in rtl direction.\n // The scroll position is negative in spec however its not in some browsers, for example Chrome earlier than v85.\n // https://github.com/othree/jquery.rtl-scroll-type\n const prev = rootElement[scrollToKey];\n rootElement[scrollToKey] = 1;\n isNegativeOffset = rootElement[scrollToKey] === 0;\n rootElement[scrollToKey] = prev;\n }\n if (isNegativeOffset) {\n offset *= -1;\n }\n }\n if (diff) {\n rootElement[scrollToKey] += offset;\n } else {\n rootElement[scrollToKey] = offset;\n scrollDirection = SCROLL_MANUAL;\n }\n };\n const scrollTo = async (index: number, getCurrentOffset: () => number) => {\n const getOffset = (): number => {\n let offset = getCurrentOffset();\n const scrollSize = getActualScrollSize();\n const viewportSize = store._getViewportSize();\n if (scrollSize - (offset + viewportSize) <= 0) {\n // Adjust if the offset is over the end, to get correct startIndex.\n offset = scrollSize - viewportSize;\n }\n return offset;\n };\n\n if (store._hasUnmeasuredItemsInRange(index)) {\n do {\n // In order to scroll to the correct position, mount the items and measure their sizes before scrolling.\n store._update(ACTION_HANDLE_SCROLL, getOffset());\n try {\n // Wait for the scroll destination items to be measured.\n await store._waitForScrollDestinationItemsMeasured();\n } catch (e) {\n // canceled\n return;\n }\n } while (store._hasUnmeasuredItemsInRange(index));\n\n // Scroll with the updated value\n updateScrollPosition(getOffset());\n } else {\n const offset = getOffset();\n updateScrollPosition(offset);\n // Sync viewport to scroll destination\n store._update(ACTION_HANDLE_SCROLL, offset);\n }\n };\n\n const calcTotalJump = (jump: ScrollJump): number =>\n jump.reduce((acc, [, j]) => acc + j, 0);\n\n return {\n _initRoot(root) {\n rootElement = root;\n const ro = getResizeObserver();\n\n const syncViewportToScrollPosition = () => {\n let offset = root[scrollToKey];\n if (isRtl) {\n // The scroll position may be negative value in rtl direction.\n // https://github.com/othree/jquery.rtl-scroll-type\n offset = abs(offset);\n }\n if (prevOffset === offset) {\n return;\n }\n // Skip scroll direction detection just after resizing because it may result in the opposite direction.\n // Scroll events are dispatched enough so it's ok to skip some of them.\n if (scrollDirection === SCROLL_STOP || !resized) {\n // Ignore until manual scrolling\n if (scrollDirection !== SCROLL_MANUAL) {\n scrollDirection = prevOffset > offset ? SCROLL_UP : SCROLL_DOWN;\n }\n } else {\n resized = false;\n }\n store._update(ACTION_HANDLE_SCROLL, (prevOffset = offset));\n emitScrollOffsetChange(offset);\n };\n\n const onScrollStopped = debounce(() => {\n // Check scroll position once just after scrolling stopped\n syncViewportToScrollPosition();\n scrollDirection = SCROLL_STOP;\n emitScrollStateChange(false);\n }, 150);\n\n const onScroll = () => {\n const isScrollStart = scrollDirection === SCROLL_STOP;\n syncViewportToScrollPosition();\n if (isScrollStart) {\n emitScrollStateChange(true);\n }\n onScrollStopped();\n };\n\n // Infer scroll state also from wheel events\n // Sometimes scroll events do not fire when frame dropped even if the visual have been already scrolled\n const onWheel = throttle((e: WheelEvent) => {\n if (scrollDirection === SCROLL_STOP) {\n // Scroll start should be detected with scroll event\n return;\n }\n if (e.ctrlKey) {\n // Probably a pinch-to-zoom gesture\n return;\n }\n // Get delta before checking deltaMode for firefox behavior\n // https://github.com/w3c/uievents/issues/181#issuecomment-392648065\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1392460#c34\n if (isHorizontal ? e.deltaX : e.deltaY) {\n if (\n prevOffset > 0 &&\n prevOffset < store._getScrollSize() - store._getViewportSize()\n ) {\n onScrollStopped();\n }\n }\n }, 50);\n\n ro.observe(root);\n root.addEventListener(\"scroll\", onScroll);\n root.addEventListener(\"wheel\", onWheel, { passive: true });\n\n return () => {\n ro.disconnect();\n root.removeEventListener(\"scroll\", onScroll);\n root.removeEventListener(\"wheel\", onWheel);\n onScrollStopped._cancel();\n };\n },\n _initItem(el, i) {\n const ro = getResizeObserver();\n mountedIndexes.set(el, i);\n ro.observe(el);\n return () => {\n mountedIndexes.delete(el);\n ro.unobserve(el);\n };\n },\n _getActualScrollSize: getActualScrollSize,\n _scrollTo(offset) {\n offset = max(offset, 0);\n\n scrollTo(store._getItemIndexForScrollTo(offset), () => offset);\n },\n _scrollToIndex(index, count) {\n index = max(min(index, count - 1), 0);\n\n scrollTo(index, () => store._getItemOffset(index));\n },\n _fixScrollJump: (jump, startIndex) => {\n // Compensate scroll jump\n if (scrollDirection === SCROLL_UP) {\n const diff = calcTotalJump(jump);\n if (diff) {\n updateScrollPosition(diff, true);\n }\n } else if (scrollDirection === SCROLL_MANUAL) {\n const offset = store._getScrollOffset();\n if (offset === 0) {\n // Do nothing to stick to the start\n } else {\n const allDiff = calcTotalJump(jump);\n if (\n store._getScrollSize() -\n (offset + store._getViewportSize() + allDiff) <=\n 0\n ) {\n // Keep end to stick to the end\n if (allDiff) {\n updateScrollPosition(offset + allDiff);\n }\n } else {\n // Keep start at mid\n const diff = jump.reduce((acc, [index, j]) => {\n if (index < startIndex) {\n acc += j;\n }\n return acc;\n }, 0);\n if (diff) {\n updateScrollPosition(diff, true);\n }\n }\n }\n } else {\n // NOP\n }\n },\n };\n};\n"],"names":["min","Math","max","abs","now","Date","exists","v","range","length","cb","Array","from","_","i","getItemSize","cache","index","size","_sizes","_defaultItemSize","computeOffset","isTotal","_length","_measuredOffsetIndex","_offsets","top","computeStartOffset","findIndex","distance","sum","h","findStartIndexWithOffset","offset","prevStartIndex","prevOffset","findEndIndex","resetCache","itemSize","useIsomorphicLayoutEffect","window","useLayoutEffect","useEffect","useSyncExternalStore","subscibe","getSnapShot","_useSyncExternalStore","refKey","useStatic","init","ref","useRef","useRefWithUpdate","value","Item","memo","_children","children","_scroller","scroller","_store","store","_index","_element","Element","_subscribe","_getItemOffset","hide","_isUnmeasuredItem","_initItem","_jsx","style","useMemo","isHorizontal","_isHorizontal","leftOrRightKey","_isRtl","margin","padding","position","visibility","display","DefaultWindow","forwardRef","scrollSize","scrolling","horizontal","attrs","jsx","width","height","pointerEvents","Window","_ref","_scrolling","_attrs","_getScrollSize","overflow","contain","VList","itemSizeProp","overscan","horizontalProp","rtl","rtlProp","element","itemElement","onScroll","onScrollProp","onScrollStop","onScrollStopProp","onRangeChange","onRangeChangeProp","windowAttrs","elements","arr","Children","forEach","e","isInvalidElement","push","count","createVirtualStore","itemCount","isRtl","_scrollToQueue","viewportWidth","viewportHeight","scrollOffset","jump","_prevRange","subscribers","Set","getViewportSize","_getRange","prevEndIndex","start","end","_hasUnmeasuredItemsInRange","startIndex","hasUnmeasuredItemsInRange","endIndex","_getScrollOffset","_getViewportSize","computeTotalSize","_getJump","_getItemIndexForScrollTo","_waitForScrollDestinationItemsMeasured","Promise","resolve","reject","then","undefined","add","delete","_update","type","payload","mutated","updated","filter","updatedJump","setItemSize","_width","_height","_updateCacheLength","rootRef","mountedIndexes","reset","useState","setScrolling","createScroller","emitScrollOffsetChange","emitScrollStateChange","isNegativeOffset","rootElement","_ro","scrollDirection","resized","scrollToKey","WeakMap","getResizeObserver","ResizeObserver","entries","resizes","entry","target","contentRect","get","getActualScrollSize","scrollWidth","scrollHeight","updateScrollPosition","diff","prev","scrollTo","async","getCurrentOffset","getOffset","viewportSize","calcTotalJump","reduce","acc","j","_initRoot","root","ro","syncViewportToScrollPosition","onScrollStopped","debounce","id","cancel","clearTimeout","debouncedFn","setTimeout","_cancel","isScrollStart","onWheel","throttle","time","args","n","ctrlKey","deltaX","deltaY","fn","observe","addEventListener","passive","disconnect","removeEventListener","el","set","unobserve","_getActualScrollSize","_scrollTo","_scrollToIndex","_fixScrollJump","allDiff","isScrolling","useImperativeHandle","scrollToIndex","scrollBy","startIndexWithMargin","endIndexWithMargin","items","res","key"],"mappings":"yGAAO,MAAMA,EAAMC,KAAKD,IACXE,EAAMD,KAAKC,IACXC,EAAMF,KAAKE,IACXC,EAAMC,KAAKD,IAEXE,EAAaC,GAAiD,MAALA,EAEzDC,EAAQA,CAAIC,EAAgBC,IACvCC,MAAMC,KAAK,CAAEH,WAAU,CAACI,EAAGC,IAAMJ,EAAGI,KCKzBC,EAAcA,CAACC,EAAcC,KACxC,MAAMC,EAAOF,EAAMG,EAAOF,GAC1B,OAZsB,IAYfC,EAAoBF,EAAMI,EAAmBF,CAAI,EAapDG,EAAgBA,CACpBL,EACAC,EACAK,KAEA,IAAKN,EAAMO,EAAS,OAAO,EAC3B,GAAIP,EAAMQ,GAAwBP,EAChC,OAAIK,EACKN,EAAMS,EAASR,GAAUF,EAAYC,EAAOC,GAE5CD,EAAMS,EAASR,GAI1B,IAAIH,EAAIE,EAAMQ,EACVE,EAAMV,EAAMS,EAASX,GACzB,KAAOA,GAAKG,IACVD,EAAMS,EAASX,GAAKY,EAChBZ,IAAMG,GAAUK,IAGpBI,GAAOX,EAAYC,EAAOF,GAC1BA,IAIF,OADAE,EAAMQ,EAAuBP,EACtBS,CAAG,EAOCC,EAAqBA,CAChCX,EACAC,IAEOI,EAAcL,EAAOC,GAGxBW,EAAYA,CAACZ,EAAcF,EAAWe,KAC1C,IAAIC,EAAM,EACV,GAAID,GAAY,EAEd,KAAOf,EAAIE,EAAMO,EAAU,GAAG,CAC5B,MAAMQ,EAAIhB,EAAYC,EAAOF,KAC7B,IAA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,iBACF,OAAOzB,EAAS+K,GACjB,EACGnC,mBACF,OAAO1I,EAAMkF,GACd,EACDkG,cAAchO,GACZ0C,EAASiL,EAAe3N,EAAOwG,EAChC,EACD0E,SAAUxI,EAASgL,EACnBO,SAASjN,GACP0B,EAASgL,EAAU9K,EAAMiF,IAAqB7G,EAC/C,KAGL,CAACwF,IAGH,MAAM0H,EAAuBjP,EAAIyI,EAAatC,EAAU,GAClD+I,EAAqBpP,EAAI6I,EAAWxC,EAAUoB,EAAQ,GACtD4H,EAAQ7K,EAAAA,SAAQ,KACpB,MAAM8K,EAAsB,GAC5B,IAAK,IAAIxO,EAAIqO,EAAsBrO,GAAKsO,EAAoBtO,IAE1DyJ,EAAed,IAAI3I,GAkBrB,OAhBAyJ,EAAelD,SAASvG,IACtB,MAAMwG,EAAIJ,EAASpG,GAEfR,EAAOgH,IACTgI,EAAI9H,KACFlD,MAAChB,GAECI,EAAWC,EACXC,EAAQC,EACRC,EAAQhD,EACRiD,EAAU2C,EACVlD,EAAW8D,IALLA,aAAC,EAADA,EAAqCiI,MAAOzO,GAQvD,IAEIwO,CAAG,GACT,CAACpI,EAAUqD,EAAgB4E,EAAsBC,IAEpD,OACE9K,EAAAA,IAACsB,EAAM,CACLC,EAAMyE,EACN1G,EAAQC,EACRE,EAAU0C,EACVX,EAAYT,EACZ7B,EAAW6L,EACXtJ,GACA"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/src/core/utils.ts","../src/src/core/cache.ts","../src/src/core/store.ts","../src/src/react/useIsomorphicLayoutEffect.ts","../src/src/react/useSyncExternalStore.ts","../src/src/core/dom.ts","../src/src/core/scroller.ts","../src/src/react/utils.ts","../src/src/react/useStatic.ts","../src/src/react/useRefWithUpdate.ts","../src/src/react/VList.tsx","../src/src/core/resizer.ts","../src/src/react/VGrid.tsx"],"sourcesContent":["export const min = Math.min;\nexport const max = Math.max;\nexport const now = Date.now;\n\nexport const exists = <T>(v: T): v is Exclude<T, null | undefined> => v != null;\n\nexport const range = <T>(length: number, cb: (i: number) => T): T[] =>\n Array.from({ length }, (_, i) => cb(i));\n\nexport const debounce = <T extends (...args: any[]) => void>(\n fn: T,\n ms: number\n) => {\n let id: NodeJS.Timeout | undefined | null;\n\n const cancel = () => {\n if (exists(id)) {\n clearTimeout(id);\n }\n };\n const debouncedFn = () => {\n cancel();\n id = setTimeout(() => {\n id = null;\n fn();\n }, ms);\n };\n debouncedFn._cancel = cancel;\n return debouncedFn;\n};\n\nexport const throttle = <T extends (...args: any[]) => void>(\n fn: T,\n ms: number\n) => {\n let time = now() - ms;\n return (...args: Parameters<T>) => {\n const n = now();\n if (time + ms < n) {\n time = n;\n fn(...args);\n }\n };\n};\n\nexport const once = <F extends (...args: any[]) => any>(fn: F): F => {\n let called: undefined | boolean;\n let cache: ReturnType<F>;\n\n return ((...args) => {\n if (!called) {\n called = true;\n cache = fn(...args);\n }\n return cache;\n }) as F;\n};\n","import type { DeepReadonly, Writeable } from \"./types\";\nimport { exists, max, min, range } from \"./utils\";\n\nexport const UNCACHED = -1;\n\nexport type Cache = DeepReadonly<{\n _defaultItemSize: number;\n _length: number;\n _sizes: number[];\n _measuredOffsetIndex: number;\n _offsets: number[];\n}>;\n\nexport const getItemSize = (cache: Cache, index: number): number => {\n const size = cache._sizes[index]!;\n return size === UNCACHED ? cache._defaultItemSize : size;\n};\n\nexport const setItemSize = (\n cache: Writeable<Cache>,\n index: number,\n size: number\n) => {\n cache._sizes[index] = size;\n // mark as dirty\n cache._measuredOffsetIndex = min(index, cache._measuredOffsetIndex);\n};\n\nconst computeOffset = (\n cache: Writeable<Cache>,\n index: number,\n isTotal?: boolean\n): number => {\n if (!cache._length) return 0;\n if (cache._measuredOffsetIndex >= index) {\n if (isTotal) {\n return cache._offsets[index]! + getItemSize(cache, index);\n } else {\n return cache._offsets[index]!;\n }\n }\n\n let i = cache._measuredOffsetIndex;\n let top = cache._offsets[i]!;\n while (i <= index) {\n cache._offsets[i] = top;\n if (i === index && !isTotal) {\n break;\n }\n top += getItemSize(cache, i);\n i++;\n }\n // mark as measured\n cache._measuredOffsetIndex = index;\n return top;\n};\n\nexport const computeTotalSize = (cache: Writeable<Cache>): number => {\n return computeOffset(cache, cache._length - 1, true);\n};\n\nexport const computeStartOffset = (\n cache: Writeable<Cache>,\n index: number\n): number => {\n return computeOffset(cache, index);\n};\n\nconst findIndex = (cache: Cache, i: number, distance: number): number => {\n let sum = 0;\n if (distance >= 0) {\n // search forward\n while (i < cache._length - 1) {\n const h = getItemSize(cache, i++);\n if ((sum += h) >= distance) {\n if (sum - h / 2 >= distance) {\n i--;\n }\n break;\n }\n }\n } else {\n // search backward\n while (i > 0) {\n const h = getItemSize(cache, --i);\n if ((sum -= h) <= distance) {\n if (sum + h / 2 < distance) {\n i++;\n }\n break;\n }\n }\n }\n\n return min(max(i, 0), cache._length - 1);\n};\n\nexport const findStartIndexWithOffset = (\n cache: Cache,\n offset: number,\n prevStartIndex: number,\n prevOffset: number\n): number => {\n return findIndex(cache, prevStartIndex, offset - prevOffset);\n};\n\nexport const findEndIndex = findIndex;\n\nexport const hasUnmeasuredItemsInRange = (\n cache: Cache,\n startIndex: number,\n endIndex: number\n): boolean => {\n for (let i = startIndex; i <= endIndex; i++) {\n if (cache._sizes[i] === UNCACHED) {\n return true;\n }\n }\n return false;\n};\n\nexport const resetCache = (\n length: number,\n itemSize: number,\n cache?: Cache\n): Cache => {\n return {\n _defaultItemSize: itemSize,\n _length: length,\n _measuredOffsetIndex: cache\n ? min(cache._measuredOffsetIndex, length - 1)\n : 0,\n _sizes: range(length, (i) => {\n const size = cache && cache._sizes[i];\n if (exists(size)) {\n return size;\n }\n return UNCACHED;\n }),\n _offsets: range(length, (i) => {\n if (i === 0) {\n // first offset must be 0\n return 0;\n }\n const offset = cache && cache._offsets[i];\n if (exists(offset)) {\n return offset;\n }\n return UNCACHED;\n }),\n };\n};\n","import {\n findStartIndexWithOffset,\n resetCache,\n getItemSize,\n computeTotalSize,\n findEndIndex,\n computeStartOffset,\n Cache,\n UNCACHED,\n setItemSize,\n hasUnmeasuredItemsInRange,\n} from \"./cache\";\nimport type { Writeable } from \"./types\";\nimport { max } from \"./utils\";\n\ntype ItemJump = [sizeDiff: number, index: number];\nexport type ScrollJump = Readonly<ItemJump[]>;\nexport type ItemResize = [index: number, size: number];\ntype ItemsRange = [startIndex: number, endIndex: number];\n\nexport const SCROLL_STOP = 0;\nexport const SCROLL_DOWN = 1;\nexport const SCROLL_UP = 2;\nexport const SCROLL_MANUAL = 3;\ntype ScrollDirection =\n | typeof SCROLL_STOP\n | typeof SCROLL_DOWN\n | typeof SCROLL_UP\n | typeof SCROLL_MANUAL;\n\nexport const ACTION_ITEM_RESIZE = 1;\nexport const ACTION_WINDOW_RESIZE = 2;\nexport const ACTION_SCROLL = 3;\nexport const ACTION_MANUAL_SCROLL = 4;\n\ntype Actions =\n | [type: typeof ACTION_ITEM_RESIZE, entries: ItemResize[]]\n | [type: typeof ACTION_WINDOW_RESIZE, size: number]\n | [type: typeof ACTION_SCROLL, offset: number]\n | [type: typeof ACTION_MANUAL_SCROLL, offset: number];\n\nexport type VirtualStore = {\n _getRange(): ItemsRange;\n _isUnmeasuredItem(index: number): boolean;\n _hasUnmeasuredItemsInRange(startIndex: number): boolean;\n _getItemOffset(index: number): number;\n _getItemSize(index: number): number;\n _getScrollOffset(): number;\n _getViewportSize(): number;\n _getScrollSize(): number;\n _getJump(): ScrollJump;\n _isHorizontal(): boolean;\n _isRtl(): boolean;\n _getItemIndexForScrollTo(offset: number): number;\n _waitForScrollDestinationItemsMeasured(): Promise<void>;\n _subscribe(cb: () => void): () => void;\n _update(...action: Actions): void;\n _getScrollDirection(): ScrollDirection;\n _setScrollDirection(direction: ScrollDirection): void;\n _updateCacheLength(length: number): void;\n};\n\nexport const createVirtualStore = (\n itemCount: number,\n itemSize: number,\n isHorizontal: boolean,\n isRtl: boolean,\n initialItemCount: number = 0,\n onScrollStateChange: (scrolling: boolean) => void,\n onScrollOffsetChange: (offset: number) => void\n): VirtualStore => {\n let viewportSize = itemSize * max(initialItemCount - 1, 0);\n let scrollOffset = 0;\n let jump: ItemJump[] = [];\n let cache = resetCache(itemCount, itemSize);\n let scrollDirection: ScrollDirection = SCROLL_STOP;\n let _prevRange: ItemsRange = [0, initialItemCount];\n let _scrollToQueue: [() => void, () => void] | undefined;\n\n const subscribers = new Set<() => void>();\n\n return {\n _getRange() {\n const [prevStartIndex, prevEndIndex] = _prevRange;\n const prevOffset = computeStartOffset(\n cache as Writeable<Cache>,\n prevStartIndex\n );\n const start = findStartIndexWithOffset(\n cache,\n scrollOffset,\n prevStartIndex,\n prevOffset\n );\n const end = findEndIndex(cache, start, viewportSize);\n if (prevStartIndex === start && prevEndIndex === end) {\n return _prevRange;\n }\n return (_prevRange = [start, end]);\n },\n _isUnmeasuredItem(index) {\n return cache._sizes[index] === UNCACHED;\n },\n _hasUnmeasuredItemsInRange(startIndex) {\n return hasUnmeasuredItemsInRange(\n cache,\n startIndex,\n findEndIndex(cache, startIndex, viewportSize)\n );\n },\n _getItemOffset(index) {\n return computeStartOffset(cache as Writeable<Cache>, index);\n },\n _getItemSize(index) {\n return getItemSize(cache, index);\n },\n _getScrollOffset() {\n return scrollOffset;\n },\n _getViewportSize() {\n return viewportSize;\n },\n _getScrollSize() {\n return computeTotalSize(cache as Writeable<Cache>);\n },\n _getJump() {\n return jump;\n },\n _isHorizontal() {\n return isHorizontal;\n },\n _isRtl() {\n return isRtl;\n },\n _getItemIndexForScrollTo(offset) {\n return findStartIndexWithOffset(cache, offset, 0, 0);\n },\n _waitForScrollDestinationItemsMeasured() {\n if (_scrollToQueue) {\n // Cancel waiting scrollTo\n _scrollToQueue[1]();\n }\n // The measurement will be done asynchronously and the timing is not predictable so we use promise.\n // For example, ResizeObserver may not fire when window is not visible.\n return new Promise((resolve, reject) => {\n _scrollToQueue = [\n () => {\n // HACK: It should be resolved in the next microtask that is after React's render\n Promise.resolve().then(() => {\n resolve();\n _scrollToQueue = undefined;\n });\n },\n reject,\n ];\n });\n },\n _subscribe(cb) {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n _update(type, payload) {\n const mutated = ((): boolean => {\n switch (type) {\n case ACTION_ITEM_RESIZE: {\n const updated = payload.filter(\n ([index, size]) => cache._sizes[index] !== size\n );\n // Skip if all items are cached and not updated\n if (!updated.length) {\n return false;\n }\n\n const updatedJump: ItemJump[] = [];\n updated.forEach(([index, size]) => {\n updatedJump.push([size - getItemSize(cache, index), index]);\n setItemSize(cache as Writeable<Cache>, index, size);\n });\n jump = updatedJump;\n return true;\n }\n case ACTION_WINDOW_RESIZE: {\n if (viewportSize === payload) {\n return false;\n }\n viewportSize = payload;\n return true;\n }\n case ACTION_SCROLL:\n case ACTION_MANUAL_SCROLL: {\n const prevOffset = scrollOffset;\n return (scrollOffset = payload) !== prevOffset;\n }\n }\n })();\n\n if (mutated) {\n subscribers.forEach((cb) => {\n cb();\n });\n\n if (type === ACTION_SCROLL) {\n onScrollOffsetChange(scrollOffset);\n } else if (_scrollToQueue && type === ACTION_ITEM_RESIZE) {\n _scrollToQueue[0]();\n }\n }\n },\n _getScrollDirection() {\n return scrollDirection;\n },\n _setScrollDirection(dir) {\n const prev = scrollDirection;\n scrollDirection = dir;\n if (scrollDirection === SCROLL_STOP) {\n onScrollStateChange(false);\n } else if (\n prev === SCROLL_STOP &&\n (scrollDirection === SCROLL_DOWN || scrollDirection === SCROLL_UP)\n ) {\n onScrollStateChange(true);\n }\n },\n _updateCacheLength(length) {\n // It's ok to be updated in render because states should be calculated consistently regardless cache length\n if (cache._length === length) return;\n cache = resetCache(length, itemSize, cache);\n },\n };\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\n// https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85\nexport const useIsomorphicLayoutEffect =\n typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n","import { useSyncExternalStore as _useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\n\nexport const useSyncExternalStore = <T>(\n subscibe: (onStoreChange: () => void) => () => void,\n getSnapShot: () => T\n): T => {\n return _useSyncExternalStore(subscibe, getSnapShot, getSnapShot);\n};\n","import { once } from \"./utils\";\n\n// The scroll position may be negative value in rtl direction.\n//\n// left right result\n// -100 0 true spec compliant\n// 0 100 false probably Chrome earlier than v85\n// https://github.com/othree/jquery.rtl-scroll-type\nexport const hasNegativeOffsetInRtl = once((scrollable: HTMLElement) => {\n const key = \"scrollLeft\";\n const prev = scrollable[key];\n scrollable[key] = 1;\n // scrollLeft can be positive under some specific situations even if negative mode, so we use `<` for now.\n const isNegative = scrollable[key] < 1;\n scrollable[key] = prev;\n return isNegative;\n});\n","import { hasNegativeOffsetInRtl } from \"./dom\";\nimport {\n ACTION_SCROLL,\n ACTION_MANUAL_SCROLL,\n ScrollJump,\n VirtualStore,\n SCROLL_MANUAL,\n SCROLL_STOP,\n SCROLL_UP,\n SCROLL_DOWN,\n} from \"./store\";\nimport { debounce, throttle, max, min } from \"./utils\";\n\nexport type Scroller = {\n _initRoot: (rootElement: HTMLElement) => () => void;\n _getActualScrollSize: () => number;\n _scrollTo: (offset: number) => void;\n _scrollToIndex: (index: number, count: number) => void;\n _fixScrollJump: (jump: ScrollJump, startIndex: number) => void;\n};\n\nexport const createScroller = (\n store: VirtualStore,\n isJustResized: () => boolean\n): Scroller => {\n let rootElement: HTMLElement | undefined;\n const isHorizontal = store._isHorizontal();\n const isRtl = store._isRtl();\n const scrollToKey = isHorizontal ? \"scrollLeft\" : \"scrollTop\";\n\n const getActualScrollSize = (): number => {\n if (!rootElement) return 0;\n // Use element's scrollHeight/scrollWidth instead of stored scrollSize.\n // This is because stored size may differ from the actual size, for example when a new item is added and not yet measured.\n return isHorizontal ? rootElement.scrollWidth : rootElement.scrollHeight;\n };\n const normalizeRtlOffset = (offset: number, diff?: boolean): number => {\n if (hasNegativeOffsetInRtl(rootElement!)) {\n return -offset;\n } else {\n return diff\n ? -offset\n : store._getScrollSize() - store._getViewportSize() - offset;\n }\n };\n const scrollTo = (offset: number, diff?: boolean) => {\n if (!rootElement) return;\n if (isHorizontal && isRtl) {\n offset = normalizeRtlOffset(offset, diff);\n }\n if (diff) {\n rootElement[scrollToKey] += offset;\n } else {\n rootElement[scrollToKey] = offset;\n store._setScrollDirection(SCROLL_MANUAL);\n }\n };\n const scrollManually = async (\n index: number,\n getCurrentOffset: () => number\n ) => {\n const getOffset = (): number => {\n let offset = getCurrentOffset();\n const scrollSize = getActualScrollSize();\n const viewportSize = store._getViewportSize();\n if (scrollSize - (offset + viewportSize) <= 0) {\n // Adjust if the offset is over the end, to get correct startIndex.\n offset = scrollSize - viewportSize;\n }\n return offset;\n };\n\n if (store._hasUnmeasuredItemsInRange(index)) {\n do {\n // In order to scroll to the correct position, mount the items and measure their sizes before scrolling.\n store._update(ACTION_MANUAL_SCROLL, getOffset());\n try {\n // Wait for the scroll destination items to be measured.\n await store._waitForScrollDestinationItemsMeasured();\n } catch (e) {\n // canceled\n return;\n }\n } while (store._hasUnmeasuredItemsInRange(index));\n\n // Scroll with the updated value\n scrollTo(getOffset());\n } else {\n const offset = getOffset();\n scrollTo(offset);\n // Sync viewport to scroll destination\n store._update(ACTION_MANUAL_SCROLL, offset);\n }\n };\n\n const calcTotalJump = (jump: ScrollJump): number =>\n jump.reduce((acc, [j]) => acc + j, 0);\n\n return {\n _initRoot(root) {\n rootElement = root;\n\n const syncViewportToScrollPosition = () => {\n let offset = root[scrollToKey];\n if (isHorizontal && isRtl) {\n offset = normalizeRtlOffset(offset);\n }\n const prevOffset = store._getScrollOffset();\n if (prevOffset === offset) {\n return;\n }\n const scrollDirection = store._getScrollDirection();\n // Skip scroll direction detection just after resizing because it may result in the opposite direction.\n // Scroll events are dispatched enough so it's ok to skip some of them.\n const resized = isJustResized();\n if (\n (scrollDirection === SCROLL_STOP || !resized) &&\n // Ignore until manual scrolling\n scrollDirection !== SCROLL_MANUAL\n ) {\n store._setScrollDirection(\n prevOffset > offset ? SCROLL_UP : SCROLL_DOWN\n );\n }\n store._update(ACTION_SCROLL, offset);\n };\n\n const onScrollStopped = debounce(() => {\n // Check scroll position once just after scrolling stopped\n syncViewportToScrollPosition();\n store._setScrollDirection(SCROLL_STOP);\n }, 150);\n\n const onScroll = () => {\n syncViewportToScrollPosition();\n onScrollStopped();\n };\n\n // Infer scroll state also from wheel events\n // Sometimes scroll events do not fire when frame dropped even if the visual have been already scrolled\n const onWheel = throttle((e: WheelEvent) => {\n if (store._getScrollDirection() === SCROLL_STOP) {\n // Scroll start should be detected with scroll event\n return;\n }\n if (e.ctrlKey) {\n // Probably a pinch-to-zoom gesture\n return;\n }\n // Get delta before checking deltaMode for firefox behavior\n // https://github.com/w3c/uievents/issues/181#issuecomment-392648065\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1392460#c34\n if (isHorizontal ? e.deltaX : e.deltaY) {\n const offset = store._getScrollOffset();\n if (\n offset > 0 &&\n offset < store._getScrollSize() - store._getViewportSize()\n ) {\n onScrollStopped();\n }\n }\n }, 50);\n\n root.addEventListener(\"scroll\", onScroll);\n root.addEventListener(\"wheel\", onWheel, { passive: true });\n\n return () => {\n root.removeEventListener(\"scroll\", onScroll);\n root.removeEventListener(\"wheel\", onWheel);\n onScrollStopped._cancel();\n };\n },\n _getActualScrollSize: getActualScrollSize,\n _scrollTo(offset) {\n offset = max(offset, 0);\n\n scrollManually(store._getItemIndexForScrollTo(offset), () => offset);\n },\n _scrollToIndex(index, count) {\n index = max(min(index, count - 1), 0);\n\n scrollManually(index, () => store._getItemOffset(index));\n },\n _fixScrollJump: (jump, startIndex) => {\n const scrollDirection = store._getScrollDirection();\n // Compensate scroll jump\n if (scrollDirection === SCROLL_UP) {\n const diff = calcTotalJump(jump);\n if (diff) {\n scrollTo(diff, true);\n }\n } else if (scrollDirection === SCROLL_MANUAL) {\n const offset = store._getScrollOffset();\n if (offset === 0) {\n // Do nothing to stick to the start\n } else {\n const allDiff = calcTotalJump(jump);\n if (\n store._getScrollSize() -\n (offset + store._getViewportSize() + allDiff) <=\n 0\n ) {\n // Keep end to stick to the end\n if (allDiff) {\n scrollTo(offset + allDiff);\n }\n } else {\n // Keep start at mid\n const diff = jump.reduce((acc, [j, index]) => {\n if (index < startIndex) {\n acc += j;\n }\n return acc;\n }, 0);\n if (diff) {\n scrollTo(diff, true);\n }\n }\n }\n } else {\n // NOP\n }\n },\n };\n};\n","import { ReactNode } from \"react\";\nimport { exists } from \"../core/utils\";\n\nexport const refKey = \"current\";\n\nexport const isInvalidElement = <T extends ReactNode>(\n e: T\n): e is Extract<T, null | undefined | boolean> =>\n !exists(e) || typeof e === \"boolean\";\n","import { useRef } from \"react\";\nimport { refKey } from \"./utils\";\n\nexport const useStatic = <T>(init: () => T): T => {\n const ref = useRef<T>();\n return ref[refKey] || (ref[refKey] = init());\n};\n","import { useRef } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { refKey } from \"./utils\";\n\nexport const useRefWithUpdate = <T>(value: T) => {\n const ref = useRef<T>(value);\n\n useIsomorphicLayoutEffect(() => {\n ref[refKey] = value;\n }, [value]);\n\n return ref;\n};\n","import {\n Children,\n memo,\n useRef,\n useMemo,\n CSSProperties,\n ReactElement,\n forwardRef,\n useImperativeHandle,\n ReactNode,\n useEffect,\n RefObject,\n useState,\n ReactFragment,\n} from \"react\";\nimport { VirtualStore, createVirtualStore } from \"../core/store\";\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore\";\nimport { exists, max, min } from \"../core/utils\";\nimport { createScroller } from \"../core/scroller\";\nimport { isInvalidElement, refKey } from \"./utils\";\nimport { useStatic } from \"./useStatic\";\nimport { useRefWithUpdate } from \"./useRefWithUpdate\";\nimport { Resizer, createResizer } from \"../core/resizer\";\nimport { WindowComponentAttributes } from \"..\";\n\ntype ItemProps = {\n _children: ReactNode;\n _resizer: Resizer;\n _store: VirtualStore;\n _index: number;\n _element: \"div\";\n};\n\nconst Item = memo(\n ({\n _children: children,\n _resizer: resizer,\n _store: store,\n _index: index,\n _element: Element,\n }: ItemProps): ReactElement => {\n const ref = useRef<HTMLDivElement>(null);\n\n const offset = useSyncExternalStore(store._subscribe, () =>\n store._getItemOffset(index)\n );\n const hide = useSyncExternalStore(store._subscribe, () =>\n store._isUnmeasuredItem(index)\n );\n\n // The index may be changed if elements are inserted to or removed from the start of props.children\n useIsomorphicLayoutEffect(\n () => resizer._observeItem(ref[refKey]!, index),\n [index]\n );\n\n return (\n <Element\n ref={ref}\n style={useMemo((): CSSProperties => {\n const isHorizontal = store._isHorizontal();\n const leftOrRightKey = store._isRtl() ? \"right\" : \"left\";\n const style: CSSProperties = {\n margin: 0,\n padding: 0,\n position: \"absolute\",\n [isHorizontal ? \"height\" : \"width\"]: \"100%\",\n [isHorizontal ? \"top\" : leftOrRightKey]: 0,\n [isHorizontal ? leftOrRightKey : \"top\"]: offset,\n visibility: hide ? \"hidden\" : \"visible\",\n // willChange: \"transform\",\n };\n if (isHorizontal) {\n style.display = \"flex\";\n }\n return style;\n }, [offset, hide])}\n >\n {children}\n </Element>\n );\n }\n);\n\n/**\n * Props of customized scrollable component for {@link VList}.\n */\nexport interface CustomWindowComponentProps {\n children: ReactNode;\n scrollSize: number;\n scrolling: boolean;\n horizontal: boolean;\n attrs: WindowComponentAttributes;\n}\n\nconst DefaultWindow = forwardRef<any, CustomWindowComponentProps>(\n (\n { children, scrollSize, scrolling, horizontal, attrs },\n ref\n ): ReactElement => {\n return (\n <div ref={ref} {...attrs}>\n <div\n style={useMemo((): CSSProperties => {\n return {\n position: \"relative\",\n visibility: \"hidden\",\n width: horizontal ? scrollSize : \"100%\",\n height: horizontal ? \"100%\" : scrollSize,\n pointerEvents: scrolling ? \"none\" : \"auto\",\n };\n }, [scrollSize, scrolling])}\n >\n {children}\n </div>\n </div>\n );\n }\n);\n\nexport type CustomWindowComponent = typeof DefaultWindow;\n\nconst Window = ({\n _children: children,\n _ref: ref,\n _store: store,\n _element: Element,\n _scrolling: scrolling,\n _attrs: attrs,\n}: {\n _children: ReactNode;\n _ref: RefObject<HTMLDivElement>;\n _store: VirtualStore;\n _element: CustomWindowComponent;\n _scrolling: boolean;\n _attrs: WindowComponentAttributes;\n}) => {\n const scrollSize = useSyncExternalStore(\n store._subscribe,\n store._getScrollSize\n );\n\n const horizontal = store._isHorizontal();\n\n return (\n <Element\n ref={ref}\n scrollSize={scrollSize}\n scrolling={scrolling}\n horizontal={horizontal}\n attrs={useMemo(\n () => ({\n ...attrs,\n style: {\n overflow: horizontal ? \"auto hidden\" : \"hidden auto\",\n contain: \"strict\",\n // transform: \"translate3d(0px, 0px, 0px)\",\n // willChange: \"scroll-position\",\n // backfaceVisibility: \"hidden\",\n width: \"100%\",\n height: \"100%\",\n padding: 0,\n margin: 0,\n ...attrs.style,\n },\n }),\n [attrs]\n )}\n >\n {children}\n </Element>\n );\n};\n\n/**\n * Props of customized item component for {@link VList}.\n */\nexport interface CustomItemComponentProps {\n style: CSSProperties;\n children: ReactNode;\n}\n\nexport type CustomItemComponent = React.ForwardRefExoticComponent<\n React.PropsWithoutRef<CustomItemComponentProps> & React.RefAttributes<any>\n>;\n\ntype CustomItemComponentOrElement =\n | keyof JSX.IntrinsicElements\n | CustomItemComponent;\n\n/**\n * Methods of {@link VList}.\n */\nexport interface VListHandle {\n /**\n * Get current scrollTop or scrollLeft.\n */\n readonly scrollOffset: number;\n /**\n * Get current scrollHeight or scrollWidth.\n */\n readonly scrollSize: number;\n /**\n * Get current offsetHeight or offsetWidth.\n */\n readonly viewportSize: number;\n /**\n * Scroll to the item specified by index.\n * @param index index of item\n */\n scrollToIndex(index: number): void;\n /**\n * Scroll to the given offset.\n * @param offset offset from start\n */\n scrollTo(offset: number): void;\n /**\n * Scroll by the given offset.\n * @param offset offset from current position\n */\n scrollBy(offset: number): void;\n}\n\n/**\n * Props of {@link VList}.\n */\nexport interface VListProps extends WindowComponentAttributes {\n /**\n * Elements rendered by this component.\n */\n children: ReactNode;\n /**\n * Item size hint for unmeasured items. It's recommended to specify this prop if item sizes are fixed and known, or much larger than the defaultValue. It will help to reduce scroll jump when items are measured.\n * @defaultValue 40\n */\n itemSize?: number;\n /**\n * Number of items to render above/below the visible bounds of the list. You can increase to avoid showing blank items in fast scrolling.\n * @defaultValue 4\n */\n overscan?: number;\n /**\n * If set, the specified amount of items will be mounted in the initial rendering regardless of the container size. This prop is mostly for SSR.\n */\n initialItemCount?: number;\n /**\n * If true, rendered as a horizontally scrollable list. Otherwise rendered as a vertically scrollable list.\n */\n horizontal?: boolean;\n /**\n * You have to set true if you use this component under `direction: rtl` style.\n */\n rtl?: boolean;\n /**\n * Customized element type for scrollable element. This element will get {@link CustomWindowComponentProps} as props.\n * @defaultValue {@link DefaultWindow}\n */\n element?: CustomWindowComponent;\n /**\n * Customized element type for item element. This element will get {@link CustomItemComponentProps} as props.\n * @defaultValue \"div\"\n */\n itemElement?: CustomItemComponentOrElement;\n /**\n * Callback invoked whenever scroll offset changes.\n * @param offset Current scrollTop or scrollLeft.\n */\n onScroll?: (offset: number) => void;\n /**\n * Callback invoked when scrolling stops.\n */\n onScrollStop?: () => void;\n /**\n * Callback invoked when visible items range changes.\n */\n onRangeChange?: (payload: {\n /**\n * The start index of viewable items.\n */\n start: number;\n /**\n * The end index of viewable items.\n */\n end: number;\n /**\n * The total count of items.\n */\n count: number;\n }) => void;\n}\n\n/**\n * Virtualized list component. See {@link VListProps} and {@link VListHandle}.\n */\nexport const VList = forwardRef<VListHandle, VListProps>(\n (\n {\n children,\n itemSize: itemSizeProp = 40,\n overscan = 4,\n initialItemCount,\n horizontal: horizontalProp,\n rtl: rtlProp,\n element = DefaultWindow,\n itemElement = \"div\",\n onScroll: onScrollProp,\n onScrollStop: onScrollStopProp,\n onRangeChange: onRangeChangeProp,\n ...windowAttrs\n },\n ref\n ): ReactElement => {\n // Memoize element array\n const elements = useMemo(() => {\n const arr: (ReactElement | ReactFragment | string | number)[] = [];\n Children.forEach(children, (e) => {\n if (isInvalidElement(e)) {\n return;\n }\n arr.push(e);\n });\n return arr;\n }, [children]);\n const count = elements.length;\n\n const onScroll = useRefWithUpdate(onScrollProp);\n const onScrollStop = useRefWithUpdate(onScrollStopProp);\n\n const [mountedIndexes, reset] = useState<Set<number>>(new Set<number>());\n const [scrolling, setScrolling] = useState(false);\n // https://github.com/facebook/react/issues/25191#issuecomment-1237456448\n const [store, resizer, scroller] = useStatic(() => {\n const _store = createVirtualStore(\n count,\n itemSizeProp,\n !!horizontalProp,\n !!rtlProp,\n initialItemCount,\n (isScrolling) => {\n setScrolling(isScrolling);\n if (!isScrolling) {\n reset(new Set());\n onScrollStop[refKey] && onScrollStop[refKey]();\n }\n },\n (offset) => {\n onScroll[refKey] && onScroll[refKey](offset);\n }\n );\n const _resizer = createResizer(_store);\n return [\n _store,\n _resizer,\n createScroller(_store, _resizer._isJustResized),\n ];\n });\n // The elements length and cached items length are different just after element is added/removed.\n store._updateCacheLength(count);\n\n const [startIndex, endIndex] = useSyncExternalStore(\n store._subscribe,\n store._getRange\n );\n const jump = useSyncExternalStore(store._subscribe, store._getJump);\n const rootRef = useRef<HTMLDivElement>(null);\n\n useIsomorphicLayoutEffect(() => {\n const root = rootRef[refKey]!;\n const unobserve = resizer._observeRoot(root);\n const cleanup = scroller._initRoot(root);\n return () => {\n unobserve();\n cleanup();\n };\n }, []);\n\n useIsomorphicLayoutEffect(() => {\n if (!jump.length) return;\n\n scroller._fixScrollJump(jump, startIndex);\n }, [jump]);\n\n useEffect(() => {\n if (!onRangeChangeProp) return;\n\n onRangeChangeProp({\n start: startIndex,\n end: endIndex,\n count,\n });\n }, [startIndex, endIndex]);\n\n useImperativeHandle(\n ref,\n () => {\n return {\n get scrollOffset() {\n return store._getScrollOffset();\n },\n get scrollSize() {\n return scroller._getActualScrollSize();\n },\n get viewportSize() {\n return store._getViewportSize();\n },\n scrollToIndex(index) {\n scroller._scrollToIndex(index, count);\n },\n scrollTo: scroller._scrollTo,\n scrollBy(offset) {\n scroller._scrollTo(store._getScrollOffset() + offset);\n },\n };\n },\n [count]\n );\n\n const startIndexWithMargin = max(startIndex - overscan, 0);\n const endIndexWithMargin = min(endIndex + overscan, count - 1);\n const items = useMemo(() => {\n const res: ReactElement[] = [];\n for (let i = startIndexWithMargin; i <= endIndexWithMargin; i++) {\n // https://github.com/sergi/virtual-list/commit/8e7e06dc63568334c1ab809ea83c1be36572e9ed\n mountedIndexes.add(i);\n }\n mountedIndexes.forEach((i) => {\n const e = elements[i];\n // This can be undefined when items are removed\n if (exists(e)) {\n res.push(\n <Item\n key={(e as { key?: ReactElement[\"key\"] })?.key || i}\n _resizer={resizer}\n _store={store}\n _index={i}\n _element={itemElement as \"div\"}\n _children={e}\n />\n );\n }\n });\n return res;\n }, [elements, mountedIndexes, startIndexWithMargin, endIndexWithMargin]);\n\n return (\n <Window\n _ref={rootRef}\n _store={store}\n _element={element}\n _scrolling={scrolling}\n _children={items}\n _attrs={windowAttrs}\n />\n );\n }\n);\n","import {\n ACTION_ITEM_RESIZE,\n ACTION_WINDOW_RESIZE,\n ItemResize,\n VirtualStore,\n} from \"./store\";\nimport { exists, max, once } from \"./utils\";\n\nexport const createResizer = (store: VirtualStore) => {\n let resized = false;\n let rootElement: HTMLElement | undefined;\n const sizeKey = store._isHorizontal() ? \"width\" : \"height\";\n const mountedIndexes = new WeakMap<Element, number>();\n\n // Initialize ResizeObserver lazily for SSR\n const getResizeObserver = once(() => {\n // https://www.w3.org/TR/resize-observer/#intro\n return new ResizeObserver((entries) => {\n const resizes: ItemResize[] = [];\n for (const { target, contentRect } of entries) {\n if (target === rootElement) {\n store._update(ACTION_WINDOW_RESIZE, contentRect[sizeKey]);\n } else {\n const index = mountedIndexes.get(target);\n if (exists(index)) {\n resizes.push([index, contentRect[sizeKey]]);\n }\n }\n }\n\n if (resizes.length) {\n store._update(ACTION_ITEM_RESIZE, resizes);\n resized = true;\n }\n });\n });\n\n return {\n _observeRoot(root: HTMLElement) {\n rootElement = root;\n const ro = getResizeObserver();\n ro.observe(root);\n return () => {\n ro.disconnect();\n };\n },\n _observeItem(el: HTMLElement, i: number) {\n const ro = getResizeObserver();\n mountedIndexes.set(el, i);\n ro.observe(el);\n return () => {\n mountedIndexes.delete(el);\n ro.unobserve(el);\n };\n },\n _isJustResized(): boolean {\n const prev = resized;\n resized = false;\n return prev;\n },\n };\n};\n\nexport type Resizer = ReturnType<typeof createResizer>;\n\nexport const createGridResizer = (\n vStore: VirtualStore,\n hStore: VirtualStore\n) => {\n let heightResized = false;\n let widthResized = false;\n let rootElement: HTMLElement | undefined;\n\n const heightKey = \"height\";\n const widthKey = \"width\";\n const mountedIndexes = new WeakMap<\n Element,\n [rowIndex: number, colIndex: number]\n >();\n\n type CellSize = [height: number, width: number];\n const maybeCachedRowIndexes = new Set<number>();\n const maybeCachedColIndexes = new Set<number>();\n const sizeCache = new Map<string, CellSize>();\n const getKey = (rowIndex: number, colIndex: number): string =>\n `${rowIndex}-${colIndex}`;\n\n // Initialize ResizeObserver lazily for SSR\n const getResizeObserver = once(() => {\n // https://www.w3.org/TR/resize-observer/#intro\n return new ResizeObserver((entries) => {\n const resizedRows = new Set<number>();\n const resizedCols = new Set<number>();\n for (const { target, contentRect } of entries) {\n if (target === rootElement) {\n vStore._update(ACTION_WINDOW_RESIZE, contentRect[heightKey]);\n hStore._update(ACTION_WINDOW_RESIZE, contentRect[widthKey]);\n } else {\n const cell = mountedIndexes.get(target);\n if (cell) {\n const [rowIndex, colIndex] = cell;\n const key = getKey(rowIndex, colIndex);\n const prevSize = sizeCache.get(key);\n const size: CellSize = [\n contentRect[heightKey],\n contentRect[widthKey],\n ];\n let rowResized: boolean | undefined;\n let colResized: boolean | undefined;\n if (!prevSize) {\n rowResized = colResized = true;\n } else {\n if (prevSize[0] !== size[0]) {\n rowResized = true;\n }\n if (prevSize[1] !== size[1]) {\n colResized = true;\n }\n }\n if (rowResized) {\n resizedRows.add(rowIndex);\n }\n if (colResized) {\n resizedCols.add(colIndex);\n }\n if (rowResized || colResized) {\n sizeCache.set(key, size);\n }\n }\n }\n }\n\n if (resizedRows.size) {\n const heightResizes: ItemResize[] = [];\n resizedRows.forEach((rowIndex) => {\n let maxHeight = 0;\n maybeCachedColIndexes.forEach((colIndex) => {\n const size = sizeCache.get(getKey(rowIndex, colIndex));\n if (size) {\n maxHeight = max(maxHeight, size[0]);\n }\n });\n if (maxHeight) {\n heightResizes.push([rowIndex, maxHeight]);\n }\n });\n vStore._update(ACTION_ITEM_RESIZE, heightResizes);\n heightResized = true;\n }\n if (resizedCols.size) {\n const widthResizes: ItemResize[] = [];\n resizedCols.forEach((colIndex) => {\n let maxWidth = 0;\n maybeCachedRowIndexes.forEach((rowIndex) => {\n const size = sizeCache.get(getKey(rowIndex, colIndex));\n if (size) {\n maxWidth = max(maxWidth, size[1]);\n }\n });\n if (maxWidth) {\n widthResizes.push([colIndex, maxWidth]);\n }\n });\n hStore._update(ACTION_ITEM_RESIZE, widthResizes);\n widthResized = true;\n }\n });\n });\n\n return {\n _observeRoot(root: HTMLElement) {\n rootElement = root;\n const ro = getResizeObserver();\n ro.observe(root);\n return () => {\n ro.disconnect();\n };\n },\n _observeItem(el: HTMLElement, rowIndex: number, colIndex: number) {\n const ro = getResizeObserver();\n mountedIndexes.set(el, [rowIndex, colIndex]);\n maybeCachedRowIndexes.add(rowIndex);\n maybeCachedColIndexes.add(colIndex);\n ro.observe(el);\n return () => {\n mountedIndexes.delete(el);\n ro.unobserve(el);\n };\n },\n _isJustResized(horizontal?: boolean): boolean {\n const prev = horizontal ? widthResized : heightResized;\n if (horizontal) {\n widthResized = false;\n } else {\n heightResized = false;\n }\n return prev;\n },\n };\n};\n\nexport type GridResizer = ReturnType<typeof createGridResizer>;\n","import {\n memo,\n useRef,\n useMemo,\n CSSProperties,\n ReactElement,\n forwardRef,\n ReactNode,\n RefObject,\n useState,\n} from \"react\";\nimport { VirtualStore, createVirtualStore } from \"../core/store\";\nimport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore\";\nimport { max, min } from \"../core/utils\";\nimport { createScroller } from \"../core/scroller\";\nimport { refKey } from \"./utils\";\nimport { useStatic } from \"./useStatic\";\nimport { WindowComponentAttributes } from \"..\";\nimport { createGridResizer, GridResizer } from \"../core/resizer\";\n\nconst genKey = (i: number, j: number) => `${i}-${j}`;\n\n/**\n * Props of customized cell component for {@link VGrid}.\n */\nexport interface CustomCellComponentProps {\n style: CSSProperties;\n children: ReactNode;\n}\n\nexport type CustomCellComponent = React.ForwardRefExoticComponent<\n React.PropsWithoutRef<CustomCellComponentProps> & React.RefAttributes<any>\n>;\n\ntype CustomCellComponentOrElement =\n | keyof JSX.IntrinsicElements\n | CustomCellComponent;\n\ntype CellProps = {\n _children: ReactNode;\n _resizer: GridResizer;\n _verticalStore: VirtualStore;\n _horizontalStore: VirtualStore;\n _rowIndex: number;\n _colIndex: number;\n _element: \"div\";\n};\n\nconst Cell = memo(\n ({\n _children: children,\n _resizer: resizer,\n _verticalStore: verticalStore,\n _horizontalStore: horizontalStore,\n _rowIndex: rowIndex,\n _colIndex: colIndex,\n _element: Element,\n }: CellProps): ReactElement => {\n const ref = useRef<HTMLDivElement>(null);\n\n const top = useSyncExternalStore(verticalStore._subscribe, () =>\n verticalStore._getItemOffset(rowIndex)\n );\n const left = useSyncExternalStore(horizontalStore._subscribe, () =>\n horizontalStore._getItemOffset(colIndex)\n );\n const vHide = useSyncExternalStore(verticalStore._subscribe, () =>\n verticalStore._isUnmeasuredItem(rowIndex)\n );\n const hHide = useSyncExternalStore(horizontalStore._subscribe, () =>\n horizontalStore._isUnmeasuredItem(colIndex)\n );\n const height = useSyncExternalStore(verticalStore._subscribe, () =>\n verticalStore._getItemSize(rowIndex)\n );\n const width = useSyncExternalStore(horizontalStore._subscribe, () =>\n horizontalStore._getItemSize(colIndex)\n );\n\n // The index may be changed if elements are inserted to or removed from the start of props.children\n useIsomorphicLayoutEffect(\n () => resizer._observeItem(ref[refKey]!, rowIndex, colIndex),\n [colIndex, rowIndex]\n );\n\n return (\n <Element\n ref={ref}\n style={useMemo((): CSSProperties => {\n const style: CSSProperties = {\n display: \"grid\",\n margin: 0,\n padding: 0,\n position: \"absolute\",\n top: top,\n [verticalStore._isRtl() ? \"right\" : \"left\"]: left,\n visibility: vHide || hHide ? \"hidden\" : \"visible\",\n minHeight: height,\n minWidth: width,\n };\n return style;\n }, [top, left, width, height, vHide, hHide])}\n >\n {children}\n </Element>\n );\n }\n);\n\n/**\n * Props of customized scrollable component for {@link VGrid}.\n */\nexport interface CustomGridWindowComponentProps {\n children: ReactNode;\n scrollWidth: number;\n scrollHeight: number;\n scrolling: boolean;\n attrs: WindowComponentAttributes;\n}\n\nconst DefaultWindow = forwardRef<any, CustomGridWindowComponentProps>(\n (\n { children, scrollWidth, scrollHeight, scrolling, attrs },\n ref\n ): ReactElement => {\n return (\n <div ref={ref} {...attrs}>\n <div\n style={useMemo((): CSSProperties => {\n return {\n position: \"relative\",\n visibility: \"hidden\",\n width: scrollWidth,\n height: scrollHeight,\n pointerEvents: scrolling ? \"none\" : \"auto\",\n };\n }, [scrollWidth, scrollHeight, scrolling])}\n >\n {children}\n </div>\n </div>\n );\n }\n);\n\nexport type CustomGridWindowComponent = typeof DefaultWindow;\n\nconst Window = ({\n _children: children,\n _ref: ref,\n _vStore: vStore,\n _hStore: hStore,\n _element: Element,\n _scrolling: scrolling,\n _attrs: attrs,\n}: {\n _children: ReactNode;\n _ref: RefObject<HTMLDivElement>;\n _vStore: VirtualStore;\n _hStore: VirtualStore;\n _element: CustomGridWindowComponent;\n _scrolling: boolean;\n _attrs: WindowComponentAttributes;\n}) => {\n const height = useSyncExternalStore(vStore._subscribe, vStore._getScrollSize);\n const width = useSyncExternalStore(hStore._subscribe, hStore._getScrollSize);\n\n return (\n <Element\n ref={ref}\n scrollWidth={width}\n scrollHeight={height}\n scrolling={scrolling}\n attrs={useMemo(\n () => ({\n ...attrs,\n style: {\n overflow: \"auto\",\n contain: \"strict\",\n // transform: \"translate3d(0px, 0px, 0px)\",\n // willChange: \"scroll-position\",\n // backfaceVisibility: \"hidden\",\n width: \"100%\",\n height: \"100%\",\n padding: 0,\n margin: 0,\n ...attrs.style,\n },\n }),\n [attrs]\n )}\n >\n {children}\n </Element>\n );\n};\n\n/**\n * Methods of {@link VGrid}.\n */\nexport interface VGridHandle {}\n\n/**\n * Props of {@link VGrid}.\n */\nexport interface VGridProps extends WindowComponentAttributes {\n /**\n * A function to create elements rendered by this component.\n */\n children: (arg: {\n /**\n * row index of cell\n */\n rowIndex: number;\n /**\n * column index of cell\n */\n colIndex: number;\n }) => ReactNode;\n /**\n * Total row length of grid.\n */\n row: number;\n /**\n * Total column length of grid.\n */\n col: number;\n /**\n * Cell height hint for unmeasured items. It's recommended to specify this prop if item sizes are fixed and known, or much larger than the defaultValue. It will help to reduce scroll jump when items are measured.\n * @defaultValue 40\n */\n cellHeight?: number;\n /**\n * Cell width hint for unmeasured items. It's recommended to specify this prop if item sizes are fixed and known, or much larger than the defaultValue. It will help to reduce scroll jump when items are measured.\n * @defaultValue 100\n */\n cellWidth?: number;\n /**\n * Number of items to render above/below the visible bounds of the grid. You can increase to avoid showing blank items in fast scrolling.\n * @defaultValue 2\n */\n overscan?: number;\n /**\n * If set, the specified amount of rows will be mounted in the initial rendering regardless of the container size. This prop is mostly for SSR.\n */\n initialRowCount?: number;\n /**\n * If set, the specified amount of cols will be mounted in the initial rendering regardless of the container size. This prop is mostly for SSR.\n */\n initialColCount?: number;\n /**\n * You have to set true if you use this component under `direction: rtl` style.\n */\n rtl?: boolean;\n /**\n * Customized element type for scrollable element. This element will get {@link CustomGridWindowComponentProps} as props.\n * @defaultValue {@link DefaultWindow}\n */\n element?: CustomGridWindowComponent;\n /**\n * Customized element type for cell element. This element will get {@link CustomCellComponentProps} as props.\n * @defaultValue \"div\"\n */\n cellElement?: CustomCellComponentOrElement;\n}\n\n/**\n * Virtualized grid component. See {@link VGridProps} and {@link VGridHandle}.\n */\nexport const VGrid = forwardRef<VGridHandle, VGridProps>(\n (\n {\n children,\n row: rowCount,\n col: colCount,\n cellHeight = 40,\n cellWidth = 100,\n overscan = 2,\n initialRowCount,\n initialColCount,\n rtl: rtlProp,\n element = DefaultWindow,\n cellElement: itemElement = \"div\",\n ...windowAttrs\n },\n _ref // TODO implement\n ): ReactElement => {\n const [verticalScrolling, setVerticalScrolling] = useState(false);\n const [horizontalScrolling, setHorizontalScrolling] = useState(false);\n // https://github.com/facebook/react/issues/25191#issuecomment-1237456448\n const [vStore, hStore, resizer, vScroller, hScroller] = useStatic(() => {\n const dummy = () => {};\n const _vs = createVirtualStore(\n rowCount,\n cellHeight,\n false,\n !!rtlProp,\n initialRowCount,\n setVerticalScrolling,\n dummy\n );\n const _hs = createVirtualStore(\n colCount,\n cellWidth,\n true,\n !!rtlProp,\n initialColCount,\n setHorizontalScrolling,\n dummy\n );\n const resizer = createGridResizer(_vs, _hs);\n return [\n _vs,\n _hs,\n resizer,\n createScroller(_vs, () => resizer._isJustResized()),\n createScroller(_hs, () => resizer._isJustResized(true)),\n ];\n });\n // The elements length and cached items length are different just after element is added/removed.\n vStore._updateCacheLength(rowCount);\n hStore._updateCacheLength(colCount);\n\n const [startRowIndex, endRowIndex] = useSyncExternalStore(\n vStore._subscribe,\n vStore._getRange\n );\n const [startColIndex, endColIndex] = useSyncExternalStore(\n hStore._subscribe,\n hStore._getRange\n );\n const verticalJump = useSyncExternalStore(\n vStore._subscribe,\n vStore._getJump\n );\n const horizontalJump = useSyncExternalStore(\n hStore._subscribe,\n hStore._getJump\n );\n const rootRef = useRef<HTMLDivElement>(null);\n\n useIsomorphicLayoutEffect(() => {\n const root = rootRef[refKey]!;\n const unobserve = resizer._observeRoot(root);\n const vCleanup = vScroller._initRoot(root);\n const hCleanup = hScroller._initRoot(root);\n return () => {\n unobserve();\n vCleanup();\n hCleanup();\n };\n }, []);\n\n useIsomorphicLayoutEffect(() => {\n if (verticalJump.length) {\n vScroller._fixScrollJump(verticalJump, startRowIndex);\n }\n }, [verticalJump]);\n useIsomorphicLayoutEffect(() => {\n if (horizontalJump.length) {\n hScroller._fixScrollJump(horizontalJump, startColIndex);\n }\n }, [horizontalJump]);\n\n const render = useMemo(() => {\n const cache = new Map<string, ReactNode>();\n return (rowIndex: number, colIndex: number) => {\n let e: ReactNode | undefined = cache.get(genKey(rowIndex, colIndex));\n if (!e) {\n cache.set(\n genKey(rowIndex, colIndex),\n (e = children({ rowIndex, colIndex }))\n );\n }\n return e;\n };\n }, [children]);\n\n const startRowIndexWithMargin = max(startRowIndex - overscan, 0);\n const endRowIndexWithMargin = min(endRowIndex + overscan, rowCount - 1);\n const startColIndexWithMargin = max(startColIndex - overscan, 0);\n const endColIndexWithMargin = min(endColIndex + overscan, colCount - 1);\n const items = useMemo(() => {\n const res: ReactElement[] = [];\n for (let i = startRowIndexWithMargin; i <= endRowIndexWithMargin; i++) {\n for (let j = startColIndexWithMargin; j <= endColIndexWithMargin; j++) {\n res.push(\n <Cell\n key={genKey(i, j)}\n _resizer={resizer}\n _verticalStore={vStore}\n _horizontalStore={hStore}\n _rowIndex={i}\n _colIndex={j}\n _element={itemElement as \"div\"}\n _children={render(i, j)}\n />\n );\n }\n }\n\n return res;\n }, [\n render,\n startRowIndexWithMargin,\n endRowIndexWithMargin,\n startColIndexWithMargin,\n endColIndexWithMargin,\n ]);\n\n return (\n <Window\n _ref={rootRef}\n _vStore={vStore}\n _hStore={hStore}\n _element={element}\n _scrolling={verticalScrolling || horizontalScrolling}\n _children={items}\n _attrs={windowAttrs}\n />\n );\n }\n);\n"],"names":["min","Math","max","now","Date","exists","v","range","length","cb","Array","from","_","i","once","fn","called","cache","args","getItemSize","index","size","_sizes","_defaultItemSize","computeOffset","isTotal","_length","_measuredOffsetIndex","_offsets","top","computeStartOffset","findIndex","distance","sum","h","findStartIndexWithOffset","offset","prevStartIndex","prevOffset","findEndIndex","resetCache","itemSize","createVirtualStore","itemCount","isHorizontal","isRtl","initialItemCount","onScrollStateChange","onScrollOffsetChange","_scrollToQueue","viewportSize","scrollOffset","jump","scrollDirection","_prevRange","subscribers","Set","_getRange","prevEndIndex","start","end","_isUnmeasuredItem","_hasUnmeasuredItemsInRange","startIndex","hasUnmeasuredItemsInRange","endIndex","_getItemOffset","_getItemSize","_getScrollOffset","_getViewportSize","_getScrollSize","computeTotalSize","_getJump","_isHorizontal","_isRtl","_getItemIndexForScrollTo","_waitForScrollDestinationItemsMeasured","Promise","resolve","reject","then","undefined","_subscribe","add","delete","_update","type","payload","mutated","updated","filter","updatedJump","forEach","push","setItemSize","_getScrollDirection","_setScrollDirection","dir","prev","_updateCacheLength","useIsomorphicLayoutEffect","window","useLayoutEffect","useEffect","useSyncExternalStore","subscibe","getSnapShot","_useSyncExternalStore","hasNegativeOffsetInRtl","scrollable","key","isNegative","createScroller","store","isJustResized","rootElement","scrollToKey","getActualScrollSize","scrollWidth","scrollHeight","normalizeRtlOffset","diff","scrollTo","scrollManually","async","getCurrentOffset","getOffset","scrollSize","e","calcTotalJump","reduce","acc","j","_initRoot","root","syncViewportToScrollPosition","resized","onScrollStopped","debounce","id","cancel","clearTimeout","debouncedFn","setTimeout","_cancel","onScroll","onWheel","throttle","time","n","ctrlKey","deltaX","deltaY","addEventListener","passive","removeEventListener","_getActualScrollSize","_scrollTo","_scrollToIndex","count","_fixScrollJump","allDiff","refKey","useStatic","init","ref","useRef","useRefWithUpdate","value","Item","memo","_children","children","_resizer","resizer","_store","_index","_element","Element","hide","_observeItem","_jsx","style","useMemo","leftOrRightKey","margin","padding","position","visibility","display","DefaultWindow","forwardRef","scrolling","horizontal","attrs","jsx","width","height","pointerEvents","Window","Window$1","_ref","_scrolling","_attrs","overflow","contain","VList","itemSizeProp","overscan","horizontalProp","rtl","rtlProp","element","itemElement","onScrollProp","onScrollStop","onScrollStopProp","onRangeChange","onRangeChangeProp","windowAttrs","elements","arr","Children","isInvalidElement","mountedIndexes","reset","useState","setScrolling","scroller","isScrolling","sizeKey","WeakMap","getResizeObserver","ResizeObserver","entries","resizes","target","contentRect","get","_observeRoot","ro","observe","disconnect","el","set","unobserve","_isJustResized","createResizer","rootRef","cleanup","useImperativeHandle","scrollToIndex","scrollBy","startIndexWithMargin","endIndexWithMargin","items","res","genKey","Cell","_verticalStore","verticalStore","_horizontalStore","horizontalStore","_rowIndex","rowIndex","_colIndex","colIndex","left","vHide","hHide","minHeight","minWidth","_vStore","vStore","_hStore","hStore","VGrid","row","rowCount","col","colCount","cellHeight","cellWidth","initialRowCount","initialColCount","cellElement","verticalScrolling","setVerticalScrolling","horizontalScrolling","setHorizontalScrolling","vScroller","hScroller","dummy","_vs","_hs","createGridResizer","heightResized","widthResized","heightKey","widthKey","maybeCachedRowIndexes","maybeCachedColIndexes","sizeCache","Map","getKey","resizedRows","resizedCols","cell","prevSize","rowResized","colResized","heightResizes","maxHeight","widthResizes","maxWidth","startRowIndex","endRowIndex","startColIndex","endColIndex","verticalJump","horizontalJump","vCleanup","hCleanup","render","startRowIndexWithMargin","endRowIndexWithMargin","startColIndexWithMargin","endColIndexWithMargin"],"mappings":"yGAAO,MAAMA,EAAMC,KAAKD,IACXE,EAAMD,KAAKC,IACXC,EAAMC,KAAKD,IAEXE,EAAaC,GAAiD,MAALA,EAEzDC,EAAQA,CAAIC,EAAgBC,IACvCC,MAAMC,KAAK,CAAEH,WAAU,CAACI,EAAGC,IAAMJ,EAAGI,KAsCzBC,EAA2CC,IACtD,IAAIC,EACAC,EAEJ,MAAQ,IAAIC,KACLF,IACHA,GAAS,EACTC,EAAQF,KAAMG,IAETD,EACR,EC1CUE,EAAcA,CAACF,EAAcG,KACxC,MAAMC,EAAOJ,EAAMK,EAAOF,GAC1B,OAZsB,IAYfC,EAAoBJ,EAAMM,EAAmBF,CAAI,EAapDG,EAAgBA,CACpBP,EACAG,EACAK,KAEA,IAAKR,EAAMS,EAAS,OAAO,EAC3B,GAAIT,EAAMU,GAAwBP,EAChC,OAAIK,EACKR,EAAMW,EAASR,GAAUD,EAAYF,EAAOG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O1D,OANK1I,GACH/G,EAAMmO,IACJa,EAAOO,EAAUE,GAChB1I,EAAI4C,EAAS,CAAE4F,WAAUE,cAGvB1I,CAAC,CACT,GACA,CAAC4C,IAEEwJ,EAA0BlU,EAAIyT,EAAgB3G,EAAU,GACxDqH,EAAwBrU,EAAI4T,EAAc5G,EAAUsE,EAAW,GAC/DgD,EAA0BpU,EAAI2T,EAAgB7G,EAAU,GACxDuH,EAAwBvU,EAAI8T,EAAc9G,EAAUwE,EAAW,GAC/DzB,EAAQxE,EAAAA,SAAQ,KACpB,MAAMyE,EAAsB,GAC5B,IAAK,IAAInP,EAAIuT,EAAyBvT,GAAKwT,EAAuBxT,IAChE,IAAK,IAAIuH,EAAIkM,EAAyBlM,GAAKmM,EAAuBnM,IAChE4H,EAAInK,KACFwF,MAAC6E,EAEC,CAAArF,EAAUC,EACVqF,GAAgBc,EAChBZ,GAAkBc,EAClBZ,GAAW1P,EACX4P,GAAWrI,EACX6C,EAAUoC,EACV1C,EAAWwJ,EAAOtT,EAAGuH,IAPhB6H,EAAOpP,EAAGuH,KAavB,OAAO4H,CAAG,GACT,CACDmE,EACAC,EACAC,EACAC,EACAC,IAGF,OACElJ,EAAAc,IAACI,EAAM,CACLE,EAAM+C,EACNwB,GAASC,EACTC,GAASC,EACTlG,EAAUmC,EACVV,EAAYoF,GAAqBE,EACjCrH,EAAWoF,EACXpD,EAAQgB,GACR"}
|
package/lib/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e}from"react/jsx-runtime";import{useLayoutEffect as t,useEffect as r,useRef as n,memo as o,useMemo as
|
|
1
|
+
import{jsx as e}from"react/jsx-runtime";import{useLayoutEffect as t,useEffect as r,useRef as n,memo as o,useMemo as i,forwardRef as l,Children as s,useState as c,useImperativeHandle as u}from"react";import{useSyncExternalStore as a}from"use-sync-external-store/shim/index.js";const d=Math.min,_=Math.max,h=Date.now,f=e=>null!=e,g=(e,t)=>Array.from({length:e},((e,r)=>t(r))),m=e=>{let t,r;return(...n)=>(t||(t=!0,r=e(...n)),r)},w=(e,t)=>{const r=e.t[t];return-1===r?e.o:r},S=(e,t,r)=>{if(!e.i)return 0;if(e.l>=t)return r?e.u[t]+w(e,t):e.u[t];let n=e.l,o=e.u[n];for(;n<=t&&(e.u[n]=o,n!==t||r);)o+=w(e,n),n++;return e.l=t,o},v=(e,t)=>S(e,t),p=(e,t,r)=>{let n=0;if(r>=0)for(;t<e.i-1;){const o=w(e,t++);if((n+=o)>=r){n-o/2>=r&&t--;break}}else for(;t>0;){const o=w(e,--t);if((n-=o)<=r){n+o/2<r&&t++;break}}return d(_(t,0),e.i-1)},z=(e,t,r,n)=>p(e,r,t-n),I=p,b=(e,t,r)=>({o:t,i:e,l:r?d(r.l,e-1):0,t:g(e,(e=>{const t=r&&r.t[e];return f(t)?t:-1})),u:g(e,(e=>{if(0===e)return 0;const t=r&&r.u[e];return f(t)?t:-1}))}),x=(e,t,r,n,o=0,i,l)=>{let s,c=t*_(o-1,0),u=0,a=[],h=b(e,t),f=0,g=[0,o];const m=new Set;return{_(){const[e,t]=g,r=v(h,e),n=z(h,u,e,r),o=I(h,n,c);return e===n&&t===o?g:g=[n,o]},h:e=>-1===h.t[e],g:e=>((e,t,r)=>{for(let n=t;n<=r;n++)if(-1===e.t[n])return!0;return!1})(h,e,I(h,e,c)),m:e=>v(h,e),S:e=>w(h,e),v:()=>u,p:()=>c,I:()=>(e=>S(e,e.i-1,!0))(h),R:()=>a,T:()=>r,M:()=>n,C:e=>z(h,e,0,0),O:()=>(s&&s[1](),new Promise(((e,t)=>{s=[()=>{Promise.resolve().then((()=>{e(),s=void 0}))},t]}))),W:e=>(m.add(e),()=>{m.delete(e)}),H(e,t){const r=(()=>{switch(e){case 1:{const e=t.filter((([e,t])=>h.t[e]!==t));if(!e.length)return!1;const r=[];return e.forEach((([e,t])=>{r.push([t-w(h,e),e]),((e,t,r)=>{e.t[t]=r,e.l=d(t,e.l)})(h,e,t)})),a=r,!0}case 2:return c!==t&&(c=t,!0);case 3:case 4:{const e=u;return(u=t)!==e}}})();r&&(m.forEach((e=>{e()})),3===e?l(u):s&&1===e&&s[0]())},k:()=>f,D(e){const t=f;f=e,0===f?i(!1):0!==t||1!==f&&2!==f||i(!0)},J(e){h.i!==e&&(h=b(e,t,h))}}},y="undefined"!=typeof window?t:r,R=(e,t)=>a(e,t,t),T=m((e=>{const t="scrollLeft",r=e[t];e[t]=1;const n=e[t]<1;return e[t]=r,n})),M=(e,t)=>{let r;const n=e.T(),o=e.M(),i=n?"scrollLeft":"scrollTop",l=()=>r?n?r.scrollWidth:r.scrollHeight:0,s=(t,n)=>T(r)||n?-t:e.I()-e.p()-t,c=(t,l)=>{r&&(n&&o&&(t=s(t,l)),l?r[i]+=t:(r[i]=t,e.D(3)))},u=async(t,r)=>{const n=()=>{let t=r();const n=l(),o=e.p();return n-(t+o)<=0&&(t=n-o),t};if(e.g(t)){do{e.H(4,n());try{await e.O()}catch(e){return}}while(e.g(t));c(n())}else{const t=n();c(t),e.H(4,t)}},a=e=>e.reduce(((e,[t])=>e+t),0);return{$(l){r=l;const c=()=>{let r=l[i];n&&o&&(r=s(r));const c=e.v();if(c===r)return;const u=e.k(),a=t();0!==u&&a||3===u||e.D(c>r?2:1),e.H(3,r)},u=(()=>{let t;const r=()=>{f(t)&&clearTimeout(t)},n=()=>{r(),t=setTimeout((()=>{t=null,c(),e.D(0)}),150)};return n.L=r,n})(),a=()=>{c(),u()},d=(()=>{let t=h()-50;return(...r)=>{const o=h();t+50<o&&(t=o,(t=>{if(0!==e.k()&&!t.ctrlKey&&(n?t.deltaX:t.deltaY)){const t=e.v();t>0&&t<e.I()-e.p()&&u()}})(...r))}})();return l.addEventListener("scroll",a),l.addEventListener("wheel",d,{passive:!0}),()=>{l.removeEventListener("scroll",a),l.removeEventListener("wheel",d),u.L()}},j:l,A(t){t=_(t,0),u(e.C(t),(()=>t))},F(t,r){t=_(d(t,r-1),0),u(t,(()=>e.m(t)))},P:(t,r)=>{const n=e.k();if(2===n){const e=a(t);e&&c(e,!0)}else if(3===n){const n=e.v();if(0===n);else{const o=a(t);if(e.I()-(n+e.p()+o)<=0)o&&c(n+o);else{const e=t.reduce(((e,[t,n])=>(n<r&&(e+=t),e)),0);e&&c(e,!0)}}}}}},C="current",O=e=>{const t=n();return t[C]||(t[C]=e())},W=e=>{const t=n(e);return y((()=>{t[C]=e}),[e]),t},E=/*#__PURE__*/o((({U:t,B:r,V:o,q:l,G:s})=>{const c=n(null),u=R(o.W,(()=>o.m(l))),a=R(o.W,(()=>o.h(l)));return y((()=>r.K(c[C],l)),[l]),e(s,{ref:c,style:i((()=>{const e=o.T(),t=o.M()?"right":"left",r={margin:0,padding:0,position:"absolute",[e?"height":"width"]:"100%",[e?"top":t]:0,[e?t:"top"]:u,visibility:a?"hidden":"visible"};return e&&(r.display="flex"),r}),[u,a]),children:t})})),H=/*#__PURE__*/l((({children:t,scrollSize:r,scrolling:n,horizontal:o,attrs:l},s)=>e("div",{ref:s,...l,children:e("div",{style:i((()=>({position:"relative",visibility:"hidden",width:o?r:"100%",height:o?"100%":r,pointerEvents:n?"none":"auto"})),[r,n]),children:t})}))),k=({U:t,N:r,V:n,G:o,X:l,Y:s})=>{const c=R(n.W,n.I),u=n.T();return e(o,{ref:r,scrollSize:c,scrolling:l,horizontal:u,attrs:i((()=>({...s,style:{overflow:u?"auto hidden":"hidden auto",contain:"strict",width:"100%",height:"100%",padding:0,margin:0,...s.style}})),[s]),children:t})},D=/*#__PURE__*/l((({children:t,itemSize:o=40,overscan:l=4,initialItemCount:a,horizontal:h,rtl:g,element:w=H,itemElement:S="div",onScroll:v,onScrollStop:p,onRangeChange:z,...I},b)=>{const T=i((()=>{const e=[];return s.forEach(t,(t=>{(e=>!f(e)||"boolean"==typeof e)(t)||e.push(t)})),e}),[t]),D=T.length,J=W(v),$=W(p),[L,j]=c(new Set),[A,F]=c(!1),[P,U,B]=O((()=>{const e=x(D,o,!!h,!!g,a,(e=>{F(e),e||(j(new Set),$[C]&&$[C]())}),(e=>{J[C]&&J[C](e)})),t=(e=>{let t,r=!1;const n=e.T()?"width":"height",o=new WeakMap,i=m((()=>new ResizeObserver((i=>{const l=[];for(const{target:r,contentRect:s}of i)if(r===t)e.H(2,s[n]);else{const e=o.get(r);f(e)&&l.push([e,s[n]])}l.length&&(e.H(1,l),r=!0)}))));return{Z(e){t=e;const r=i();return r.observe(e),()=>{r.disconnect()}},K(e,t){const r=i();return o.set(e,t),r.observe(e),()=>{o.delete(e),r.unobserve(e)}},ee(){const e=r;return r=!1,e}}})(e);return[e,t,M(e,t.ee)]}));P.J(D);const[V,q]=R(P.W,P._),G=R(P.W,P.R),K=n(null);y((()=>{const e=K[C],t=U.Z(e),r=B.$(e);return()=>{t(),r()}}),[]),y((()=>{G.length&&B.P(G,V)}),[G]),r((()=>{z&&z({start:V,end:q,count:D})}),[V,q]),u(b,(()=>({get scrollOffset(){return P.v()},get scrollSize(){return B.j()},get viewportSize(){return P.p()},scrollToIndex(e){B.F(e,D)},scrollTo:B.A,scrollBy(e){B.A(P.v()+e)}})),[D]);const N=_(V-l,0),Q=d(q+l,D-1),X=i((()=>{const t=[];for(let e=N;e<=Q;e++)L.add(e);return L.forEach((r=>{const n=T[r];f(n)&&t.push(e(E,{B:U,V:P,q:r,G:S,U:n},(null==n?void 0:n.key)||r))})),t}),[T,L,N,Q]);return e(k,{N:K,V:P,G:w,X:A,U:X,Y:I})})),J=(e,t)=>`${e}-${t}`,$=/*#__PURE__*/o((({U:t,B:r,te:o,re:l,ne:s,oe:c,G:u})=>{const a=n(null),d=R(o.W,(()=>o.m(s))),_=R(l.W,(()=>l.m(c))),h=R(o.W,(()=>o.h(s))),f=R(l.W,(()=>l.h(c))),g=R(o.W,(()=>o.S(s))),m=R(l.W,(()=>l.S(c)));return y((()=>r.K(a[C],s,c)),[c,s]),e(u,{ref:a,style:i((()=>({display:"grid",margin:0,padding:0,position:"absolute",top:d,[o.M()?"right":"left"]:_,visibility:h||f?"hidden":"visible",minHeight:g,minWidth:m})),[d,_,m,g,h,f]),children:t})})),L=/*#__PURE__*/l((({children:t,scrollWidth:r,scrollHeight:n,scrolling:o,attrs:l},s)=>e("div",{ref:s,...l,children:e("div",{style:i((()=>({position:"relative",visibility:"hidden",width:r,height:n,pointerEvents:o?"none":"auto"})),[r,n,o]),children:t})}))),j=({U:t,N:r,ie:n,le:o,G:l,X:s,Y:c})=>{const u=R(n.W,n.I),a=R(o.W,o.I);return e(l,{ref:r,scrollWidth:a,scrollHeight:u,scrolling:s,attrs:i((()=>({...c,style:{overflow:"auto",contain:"strict",width:"100%",height:"100%",padding:0,margin:0,...c.style}})),[c]),children:t})},A=/*#__PURE__*/l((({children:t,row:r,col:o,cellHeight:l=40,cellWidth:s=100,overscan:u=2,initialRowCount:a,initialColCount:h,rtl:f,element:g=L,cellElement:w="div",...S})=>{const[v,p]=c(!1),[z,I]=c(!1),[b,T,W,E,H]=O((()=>{const e=()=>{},t=x(r,l,!1,!!f,a,p,e),n=x(o,s,!0,!!f,h,I,e),i=((e,t)=>{let r,n=!1,o=!1;const i="height",l="width",s=new WeakMap,c=new Set,u=new Set,a=new Map,d=(e,t)=>`${e}-${t}`,h=m((()=>new ResizeObserver((h=>{const f=new Set,g=new Set;for(const{target:n,contentRect:o}of h)if(n===r)e.H(2,o[i]),t.H(2,o[l]);else{const e=s.get(n);if(e){const[t,r]=e,n=d(t,r),s=a.get(n),c=[o[i],o[l]];let u,_;s?(s[0]!==c[0]&&(u=!0),s[1]!==c[1]&&(_=!0)):u=_=!0,u&&f.add(t),_&&g.add(r),(u||_)&&a.set(n,c)}}if(f.size){const t=[];f.forEach((e=>{let r=0;u.forEach((t=>{const n=a.get(d(e,t));n&&(r=_(r,n[0]))})),r&&t.push([e,r])})),e.H(1,t),n=!0}if(g.size){const e=[];g.forEach((t=>{let r=0;c.forEach((e=>{const n=a.get(d(e,t));n&&(r=_(r,n[1]))})),r&&e.push([t,r])})),t.H(1,e),o=!0}}))));return{Z(e){r=e;const t=h();return t.observe(e),()=>{t.disconnect()}},K(e,t,r){const n=h();return s.set(e,[t,r]),c.add(t),u.add(r),n.observe(e),()=>{s.delete(e),n.unobserve(e)}},ee(e){const t=e?o:n;return e?o=!1:n=!1,t}}})(t,n);return[t,n,i,M(t,(()=>i.ee())),M(n,(()=>i.ee(!0)))]}));b.J(r),T.J(o);const[k,D]=R(b.W,b._),[A,F]=R(T.W,T._),P=R(b.W,b.R),U=R(T.W,T.R),B=n(null);y((()=>{const e=B[C],t=W.Z(e),r=E.$(e),n=H.$(e);return()=>{t(),r(),n()}}),[]),y((()=>{P.length&&E.P(P,k)}),[P]),y((()=>{U.length&&H.P(U,A)}),[U]);const V=i((()=>{const e=new Map;return(r,n)=>{let o=e.get(J(r,n));return o||e.set(J(r,n),o=t({rowIndex:r,colIndex:n})),o}}),[t]),q=_(k-u,0),G=d(D+u,r-1),K=_(A-u,0),N=d(F+u,o-1),Q=i((()=>{const t=[];for(let r=q;r<=G;r++)for(let n=K;n<=N;n++)t.push(e($,{B:W,te:b,re:T,ne:r,oe:n,G:w,U:V(r,n)},J(r,n)));return t}),[V,q,G,K,N]);return e(j,{N:B,ie:b,le:T,G:g,X:v||z,U:Q,Y:S})}));export{A as VGrid,D as VList};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|