Skip to content

Commit

Permalink
fix: scrollToItem width dynamic size causes infinitely loop
Browse files Browse the repository at this point in the history
  • Loading branch information
wellyshen committed Jul 7, 2021
1 parent 8a9c291 commit 41ab2a7
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/strange-readers-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-cool-virtual": patch
---

fix: `scrollToItem` width dynamic size causes infinitely loop
22 changes: 21 additions & 1 deletion src/__tests__/useVirtual.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ describe("useVirtual", () => {
expect(outer.scrollTop).toBe(425);
});

it("should work with dynamic size correctly", () => {
it("should work with dynamic size correctly (item size < outer size)", () => {
// @ts-expect-error
window.ResizeObserver = createResizeObserver({ size: 100 });
const { scrollToItem, outerRef } = render({ isDynamic: true });
Expand All @@ -380,6 +380,26 @@ describe("useVirtual", () => {
expect(outer.scrollTop).toBe(600);
expect(cb).toHaveBeenCalledTimes(1);
});

it("should work with dynamic size correctly (item size > outer size)", () => {
// @ts-expect-error
window.ResizeObserver = createResizeObserver({ size: rect.height + 100 });
const { scrollToItem, outerRef } = render({ isDynamic: true });
const { current: outer } = outerRef;

const cb = jest.fn();
scrollToItem(8, cb);
expect(outer.scrollTop).toBe(2600);
expect(cb).not.toHaveBeenCalled();
fireEvent.scroll(outer, { target: { scrollTop: 2600 } });
scrollToItem(8, cb);
expect(outer.scrollTop).toBe(3300);
expect(cb).not.toHaveBeenCalled();
fireEvent.scroll(outer, { target: { scrollTop: 3300 } });
scrollToItem(8, cb);
expect(outer.scrollTop).toBe(3300);
expect(cb).toHaveBeenCalledTimes(1);
});
});

describe("horizontal", () => {
Expand Down
8 changes: 6 additions & 2 deletions src/useVirtual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,17 @@ export default <

if (
align === Align.start ||
(align === Align.auto && scrollOffset > start)
(align === Align.auto &&
scrollOffset + outerSize > end &&
scrollOffset > start)
) {
scrollOffset =
totalSize - start <= outerSize ? totalSize - outerSize : start;
} else if (
align === Align.end ||
(align === Align.auto && scrollOffset + outerSize < end)
(align === Align.auto &&
scrollOffset + outerSize < end &&
scrollOffset < start)
) {
scrollOffset = start + size <= outerSize ? 0 : start - outerSize + size;
} else if (align === Align.center && start + size / 2 > outerSize / 2) {
Expand Down

0 comments on commit 41ab2a7

Please sign in to comment.