Skip to content

fix: nest scroll should block #288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/demo/nest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: Nest
nav:
title: Demo
path: /demo
---

<code src="../../examples/nest.tsx"></code>
69 changes: 69 additions & 0 deletions examples/nest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import * as React from 'react';
import List from '../src/List';
import './basic.less';

interface Item {
id: number;
}

const data: Item[] = [];
for (let i = 0; i < 100; i += 1) {
data.push({
id: i,
});
}

const MyItem: React.ForwardRefRenderFunction<any, Item> = ({ id }, ref) => (
<div style={{ padding: 20, background: 'yellow' }} ref={ref}>
<List
data={data}
height={200}
itemHeight={20}
itemKey="id"
style={{
border: '1px solid blue',
boxSizing: 'border-box',
background: 'white',
}}
// debug={`inner_${id}`}
>
{(item, index, props) => (
<div {...(item as any)} {...props} style={{ height: 20, border: '1px solid cyan' }}>
{id}-{index}
</div>
)}
</List>
</div>
);

const ForwardMyItem = React.forwardRef(MyItem);

const onScroll: React.UIEventHandler<HTMLElement> = (e) => {
// console.log('scroll:', e.currentTarget.scrollTop);
};

const Demo = () => {
return (
<React.StrictMode>
<List
id="list"
data={data}
height={800}
itemHeight={20}
itemKey="id"
style={{
border: '1px solid red',
boxSizing: 'border-box',
}}
onScroll={onScroll}
// debug="outer"
>
{(item, _, props) => <ForwardMyItem {...item} {...props} />}
</List>
</React.StrictMode>
);
};

export default Demo;

/* eslint-enable */
3 changes: 3 additions & 0 deletions src/Context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as React from 'react';

export const WheelLockContext = React.createContext<(lock: boolean) => void>(() => {});
35 changes: 26 additions & 9 deletions src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,6 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {

const onWheelDelta: Parameters<typeof useFrameWheel>[6] = useEvent((offsetXY, fromHorizontal) => {
if (fromHorizontal) {
// Horizontal scroll no need sync virtual position

flushSync(() => {
setOffsetLeft((left) => {
const nextOffsetLeft = left + (isRTL ? -offsetXY : offsetXY);
Expand All @@ -393,6 +391,7 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
} else {
syncScrollTop((top) => {
const newTop = top + offsetXY;

return newTop;
});
}
Expand All @@ -410,17 +409,31 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
);

// Mobile touch move
useMobileTouchMove(useVirtual, componentRef, (isHorizontal, delta, smoothOffset) => {
useMobileTouchMove(useVirtual, componentRef, (isHorizontal, delta, smoothOffset, e) => {
const event = e as TouchEvent & {
_virtualHandled?: boolean;
};

if (originScroll(isHorizontal, delta, smoothOffset)) {
return false;
}

onRawWheel({
preventDefault() {},
deltaX: isHorizontal ? delta : 0,
deltaY: isHorizontal ? 0 : delta,
} as WheelEvent);
return true;
// Fix nest List trigger TouchMove event
if (!event || !event._virtualHandled) {
if (event) {
event._virtualHandled = true;
}

onRawWheel({
preventDefault() {},
deltaX: isHorizontal ? delta : 0,
deltaY: isHorizontal ? 0 : delta,
} as WheelEvent);

return true;
}

return false;
});

useLayoutEffect(() => {
Expand Down Expand Up @@ -548,6 +561,10 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
containerProps.dir = 'rtl';
}

if (process.env.NODE_ENV !== 'production') {
containerProps['data-dev-offset-top'] = offsetTop;
}

return (
<div
ref={containerRef}
Expand Down
22 changes: 16 additions & 6 deletions src/hooks/useFrameWheel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default function useFrameWheel(
/***
* Return `true` when you need to prevent default event
*/
onWheelDelta: (offset: number, horizontal?: boolean) => void,
onWheelDelta: (offset: number, horizontal: boolean) => void,
): [(e: WheelEvent) => void, (e: FireFoxDOMMouseScrollEvent) => void] {
const offsetRef = useRef(0);
const nextFrameRef = useRef<number>(null);
Expand All @@ -35,15 +35,25 @@ export default function useFrameWheel(
isScrollAtRight,
);

function onWheelY(event: WheelEvent, deltaY: number) {
function onWheelY(e: WheelEvent, deltaY: number) {
raf.cancel(nextFrameRef.current);

offsetRef.current += deltaY;
wheelValueRef.current = deltaY;

// Do nothing when scroll at the edge, Skip check when is in scroll
if (originScroll(false, deltaY)) return;

// Skip if nest List has handled this event
const event = e as WheelEvent & {
_virtualHandled?: boolean;
};
if (!event._virtualHandled) {
event._virtualHandled = true;
} else {
return;
}

offsetRef.current += deltaY;
wheelValueRef.current = deltaY;

// Proxy of scroll events
if (!isFF) {
event.preventDefault();
Expand All @@ -53,7 +63,7 @@ export default function useFrameWheel(
// Patch a multiple for Firefox to fix wheel number too small
// ref: https://github.com/ant-design/ant-design/issues/26372#issuecomment-679460266
const patchMultiple = isMouseScrollRef.current ? 10 : 1;
onWheelDelta(offsetRef.current * patchMultiple);
onWheelDelta(offsetRef.current * patchMultiple, false);
offsetRef.current = 0;
});
}
Expand Down
36 changes: 23 additions & 13 deletions src/hooks/useMobileTouchMove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ const SMOOTH_PTG = 14 / 15;
export default function useMobileTouchMove(
inVirtual: boolean,
listRef: React.RefObject<HTMLDivElement>,
callback: (isHorizontal: boolean, offset: number, smoothOffset?: boolean) => boolean,
callback: (
isHorizontal: boolean,
offset: number,
smoothOffset: boolean,
e?: TouchEvent,
) => boolean,
) {
const touchedRef = useRef(false);
const touchXRef = useRef(0);
Expand All @@ -34,22 +39,27 @@ export default function useMobileTouchMove(
touchYRef.current = currentY;
}

if (callback(isHorizontal, isHorizontal ? offsetX : offsetY)) {
const scrollHandled = callback(isHorizontal, isHorizontal ? offsetX : offsetY, false, e);
if (scrollHandled) {
e.preventDefault();
}

// Smooth interval
clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
if (isHorizontal) {
offsetX *= SMOOTH_PTG;
} else {
offsetY *= SMOOTH_PTG;
}
const offset = Math.floor(isHorizontal ? offsetX : offsetY);
if (!callback(isHorizontal, offset, true) || Math.abs(offset) <= 0.1) {
clearInterval(intervalRef.current);
}
}, 16);

if (scrollHandled) {
intervalRef.current = setInterval(() => {
if (isHorizontal) {
offsetX *= SMOOTH_PTG;
} else {
offsetY *= SMOOTH_PTG;
}
const offset = Math.floor(isHorizontal ? offsetX : offsetY);
if (!callback(isHorizontal, offset, true) || Math.abs(offset) <= 0.1) {
clearInterval(intervalRef.current);
}
}, 16);
}
}
};

Expand Down
54 changes: 47 additions & 7 deletions tests/scroll.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import '@testing-library/jest-dom';
import { createEvent, fireEvent, render } from '@testing-library/react';
import { act, createEvent, fireEvent, render } from '@testing-library/react';
import { mount } from 'enzyme';
import { _rs as onLibResize } from 'rc-resize-observer/lib/utils/observerUtil';
import { resetWarned } from 'rc-util/lib/warning';
import React from 'react';
import { act } from 'react-dom/test-utils';
import List from '../src';
import { spyElementPrototypes } from './utils/domHook';

Expand Down Expand Up @@ -51,11 +50,13 @@ describe('List.Scroll', () => {
});

function genList(props, func = mount) {
let node = (
<List component="ul" itemKey="id" {...props}>
{({ id }) => <li>{id}</li>}
</List>
);
const mergedProps = {
component: 'ul',
itemKey: 'id',
children: ({ id }) => <li>{id}</li>,
...props,
};
let node = <List {...mergedProps} />;

if (props.ref) {
node = <div>{node}</div>;
Expand Down Expand Up @@ -494,4 +495,43 @@ describe('List.Scroll', () => {

expect(container.querySelector('.rc-virtual-list-scrollbar-thumb')).toBeVisible();
});

it('nest scroll', async () => {
const { container } = genList(
{
itemHeight: 20,
height: 100,
data: genData(100),
children: ({ id }) =>
id === '0' ? (
<li>
<List component="ul" itemKey="id" itemHeight={20} height={100} data={genData(100)}>
{({ id }) => <li>{id}</li>}
</List>
</li>
) : (
<li />
),
},
render,
);

fireEvent.wheel(container.querySelector('ul ul li'), {
deltaY: 10,
});

await act(async () => {
jest.advanceTimersByTime(1000000);
await Promise.resolve();
});

expect(container.querySelectorAll('[data-dev-offset-top]')[0]).toHaveAttribute(
'data-dev-offset-top',
'0',
);
expect(container.querySelectorAll('[data-dev-offset-top]')[1]).toHaveAttribute(
'data-dev-offset-top',
'10',
);
});
});
57 changes: 51 additions & 6 deletions tests/touch.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from 'react';
import { act, fireEvent, render } from '@testing-library/react';
import { mount } from 'enzyme';
import { spyElementPrototypes } from './utils/domHook';
import React from 'react';
import List from '../src';
import { spyElementPrototypes } from './utils/domHook';

function genData(count) {
return new Array(count).fill(null).map((_, index) => ({ id: String(index) }));
Expand Down Expand Up @@ -123,11 +124,55 @@ describe('List.Touch', () => {

const touchEvent = new Event('touchstart');
touchEvent.preventDefault = preventDefault;
wrapper
.find('.rc-virtual-list-scrollbar')
.instance()
.dispatchEvent(touchEvent);
wrapper.find('.rc-virtual-list-scrollbar').instance().dispatchEvent(touchEvent);

expect(preventDefault).toHaveBeenCalled();
});

it('nest touch', async () => {
const { container } = render(
<List component="ul" itemHeight={20} height={100} data={genData(100)}>
{({ id }) =>
id === '0' ? (
<li>
<List component="ul" itemKey="id" itemHeight={20} height={100} data={genData(100)}>
{({ id }) => <li>{id}</li>}
</List>
</li>
) : (
<li />
)
}
</List>,
);

const targetLi = container.querySelector('ul ul li');

fireEvent.touchStart(targetLi, {
touches: [{ pageY: 0 }],
});

fireEvent.touchMove(targetLi, {
touches: [{ pageY: -1 }],
});

await act(async () => {
jest.advanceTimersByTime(1000000);
await Promise.resolve();
});

expect(container.querySelectorAll('[data-dev-offset-top]')[0]).toHaveAttribute(
'data-dev-offset-top',
'0',
);

// inner not to be 0
expect(container.querySelectorAll('[data-dev-offset-top]')[1]).toHaveAttribute(
'data-dev-offset-top',
);
expect(container.querySelectorAll('[data-dev-offset-top]')[1]).not.toHaveAttribute(
'data-dev-offset-top',
'0',
);
});
});
Loading