Skip to content

Commit

Permalink
chore: use promise to enhance scroll logic
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed Jan 3, 2025
1 parent 174c2c1 commit 636c04a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
7 changes: 3 additions & 4 deletions src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,10 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
rangeRef.current.start = start;
rangeRef.current.end = end;

// When scroll up, first visible item get real height may not same as `itemHeight`,
// Which will make scroll jump.
// Let's sync scroll top to avoid jump
React.useLayoutEffect(() => {
console.log('>>>> offsetTop', offsetTop);
console.log('>>>>', scrollHeight, start, end, heights.getRecord());

const changedRecord = heights.getRecord();
if (changedRecord.size === 1) {
const recordKey = Array.from(changedRecord)[0];
Expand All @@ -283,7 +283,6 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
const realStartHeight = heights.get(recordKey);
const diffHeight = realStartHeight - itemHeight;
syncScrollTop((ori) => {
console.log('-->', diffHeight, ori);
return ori + diffHeight;
});
}
Expand Down
14 changes: 10 additions & 4 deletions src/hooks/useHeights.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
import raf from 'rc-util/lib/raf';
import * as React from 'react';
import { useEffect, useRef } from 'react';
import type { GetKey } from '../interface';
Expand All @@ -23,10 +22,11 @@ export default function useHeights<T>(
const [updatedMark, setUpdatedMark] = React.useState(0);
const instanceRef = useRef(new Map<React.Key, HTMLElement>());
const heightsRef = useRef(new CacheMap());
const collectRafRef = useRef<number>();

const promiseIdRef = useRef<number>(0);

function cancelRaf() {
raf.cancel(collectRafRef.current);
promiseIdRef.current += 1;
}

function collectHeight(sync = false) {
Expand Down Expand Up @@ -56,7 +56,13 @@ export default function useHeights<T>(
if (sync) {
doCollect();
} else {
collectRafRef.current = raf(doCollect);
promiseIdRef.current += 1;
const id = promiseIdRef.current;
Promise.resolve().then(() => {
if (id === promiseIdRef.current) {
doCollect();
}
});
}
}

Expand Down

0 comments on commit 636c04a

Please sign in to comment.