Skip to content

Commit

Permalink
Merge pull request #196 from inokawa/refactor-range
Browse files Browse the repository at this point in the history
Refactor range computation
  • Loading branch information
inokawa authored Oct 1, 2023
2 parents 2e7b2e8 + 305233c commit 04f25cc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
15 changes: 15 additions & 0 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,21 @@ export const findStartIndexWithOffset = (
);
};

export const computeRange = (
cache: Cache,
scrollOffset: number,
prevStartIndex: number,
viewportSize: number
): [number, number] => {
const start = findStartIndexWithOffset(
cache as Writeable<Cache>,
scrollOffset,
// Clamp because prevStartIndex may exceed the limit when children decreased a lot after scrolling
min(prevStartIndex, cache._length - 1)
);
return [start, findIndex(cache, start, viewportSize)];
};

export const hasUnmeasuredItemsInRange = (
cache: Cache,
startIndex: number,
Expand Down
24 changes: 10 additions & 14 deletions src/core/store.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import {
findStartIndexWithOffset,
initCache,
getItemSize,
computeTotalSize,
findIndex as findEndIndex,
computeOffset as computeStartOffset,
Cache,
UNCACHED,
setItemSize,
hasUnmeasuredItemsInRange,
estimateDefaultItemSize,
updateCacheLength,
computeRange,
} from "./cache";
import type { CacheSnapshot, Writeable } from "./types";
import { abs, clamp, max, min } from "./utils";
Expand Down Expand Up @@ -132,13 +131,12 @@ export const createVirtualStore = (
},
_getRange() {
const [prevStartIndex, prevEndIndex] = _prevRange;
const start = findStartIndexWithOffset(
cache as Writeable<Cache>,
const [start, end] = computeRange(
cache,
scrollOffset,
// Clamp because prevStartIndex may exceed the limit when children decreased a lot after scrolling
min(prevStartIndex, cache._length - 1)
prevStartIndex,
viewportSize
);
const end = findEndIndex(cache, start, viewportSize);
if (prevStartIndex === start && prevEndIndex === end) {
return _prevRange;
}
Expand All @@ -148,18 +146,16 @@ export const createVirtualStore = (
return cache._sizes[index] === UNCACHED;
},
_hasUnmeasuredItemsInTargetViewport(offset) {
const startIndex = findStartIndexWithOffset(
cache as Writeable<Cache>,
const [startIndex, endIndex] = computeRange(
cache,
offset,
_prevRange[0] // TODO binary search may be better here
_prevRange[0], // TODO binary search may be better here
viewportSize
);
return hasUnmeasuredItemsInRange(
cache,
max(0, startIndex - 1),
min(
cache._length - 1,
findEndIndex(cache, startIndex, viewportSize) + 1
)
min(cache._length - 1, endIndex + 1)
);
},
_getItemOffset(index) {
Expand Down

0 comments on commit 04f25cc

Please sign in to comment.