Skip to content
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

feat: useInviewport result support disconnect #2539

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions packages/hooks/src/useInViewport/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,24 @@ describe('useInViewport', () => {
unmount();
expect(disconnect).toBeCalled();
});

it('should disconnect when disconnect is called', async () => {
const { result } = renderHook(() => useInViewport(targetEl));
const calls = mockIntersectionObserver.mock.calls;
const [onChange] = calls[calls.length - 1];

act(() => {
onChange([{ targetEl, isIntersecting: true, intersectionRatio: 0.5 }]);
});
const [inViewport, ratio, disconnect] = result.current;
expect(inViewport).toBeTruthy();
expect(ratio).toBe(0.5);
disconnect();

act(() => {
onChange([{ targetEl, isIntersecting: false, intersectionRatio: 0 }]);
});
expect(inViewport).toBeTruthy();
expect(ratio).toBe(0.5);
});
});
1 change: 1 addition & 0 deletions packages/hooks/src/useInViewport/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,4 @@ More information refer to [Intersection Observer API](https://developer.mozilla.
| ---------- | ---------------------------------------------------------------------------------------- | ------------------------ |
| inViewport | Is visible | `boolean` \| `undefined` |
| ratio | Current visible ratio, updated every time the node set by `options.threshold` is reached | `number` \| `undefined` |
| disconnect | cancel watch subscription | `() => void` |
32 changes: 24 additions & 8 deletions packages/hooks/src/useInViewport/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'intersection-observer';
import { useState } from 'react';
import { useCallback, useRef, useState } from 'react';
import type { BasicTarget } from '../utils/domTarget';
import { getTargetElement } from '../utils/domTarget';
import useEffectWithTarget from '../utils/useEffectWithTarget';
Expand All @@ -13,11 +13,22 @@ export interface Options {
callback?: CallbackType;
}

export type Result = [boolean | undefined, number | undefined, () => void] & {
inViewport?: boolean;
ratio?: number;
disconnect: () => void;
};

function useInViewport(target: BasicTarget | BasicTarget[], options?: Options) {
const { callback, ...option } = options || {};

const [state, setState] = useState<boolean>();
const [ratio, setRatio] = useState<number>();
const ref = useRef<IntersectionObserver>();

const disconnect = useCallback(() => {
ref.current?.disconnect();
}, []);

useEffectWithTarget(
() => {
Expand All @@ -28,7 +39,7 @@ function useInViewport(target: BasicTarget | BasicTarget[], options?: Options) {
return;
}

const observer = new IntersectionObserver(
ref.current = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
setRatio(entry.intersectionRatio);
Expand All @@ -42,17 +53,22 @@ function useInViewport(target: BasicTarget | BasicTarget[], options?: Options) {
},
);

els.forEach((el) => observer.observe(el!));
els.forEach((el) => ref.current?.observe(el!));

return () => {
observer.disconnect();
};
return disconnect;
},
[options?.rootMargin, options?.threshold, callback],
[options?.rootMargin, options?.threshold, callback, disconnect],
target,
);

return [state, ratio] as const;
const result = [state, ratio, disconnect] as Result;

// Support object destructuring, by adding the specific values.
result.inViewport = result[0];
result.ratio = result[1];
result.disconnect = result[2];

return result;
}

export default useInViewport;
1 change: 1 addition & 0 deletions packages/hooks/src/useInViewport/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,4 @@ const [inViewport, ratio] = useInViewport(
| ---------- | ----------------------------------------------------------- | ------------------------ |
| inViewport | 是否可见 | `boolean` \| `undefined` |
| ratio | 当前可见比例,在每次到达 `options.threshold` 设置节点时更新 | `number` \| `undefined` |
| disconnect | 取消观察 | `() => void` |