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): add 'callback' options and 'target' support array #2061

Merged
merged 20 commits into from
Jul 12, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 34 additions & 4 deletions packages/hooks/src/useInViewport/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { act, renderHook } from '@testing-library/react';
import useInViewport from '../index';
import { renderHook, act } from '@testing-library/react';

const targetEl = document.createElement('div');
document.body.appendChild(targetEl);

const observe = jest.fn();
const disconnect = jest.fn();

const mockIntersectionObserver = jest.fn().mockReturnValue({
observe: () => null,
disconnect: () => null,
observe,
disconnect,
});

window.IntersectionObserver = mockIntersectionObserver;
Expand All @@ -32,14 +35,41 @@ describe('useInViewport', () => {
expect(ratio).toBe(0.5);
});

it('should work when target array is in viewport and has a callback', async () => {
const targetEls: HTMLDivElement[] = [];
const callback = jest.fn();
for (let i = 0; i < 2; i++) {
const target = document.createElement('div');
document.body.appendChild(target);
targetEls.push(target);
}

const getValue = (isIntersecting, intersectionRatio) => ({ isIntersecting, intersectionRatio });

const { result } = renderHook(() => useInViewport(targetEls, { callback }));
const calls = mockIntersectionObserver.mock.calls;
const [observerCallback] = calls[calls.length - 1];

const target = getValue(false, 0);
act(() => observerCallback([target]));
expect(callback).toHaveBeenCalledWith(target);
expect(result.current[0]).toBe(false);
expect(result.current[1]).toBe(0);

const target1 = getValue(true, 0.5);
act(() => observerCallback([target1]));
expect(callback).toHaveBeenCalledWith(target1);
expect(result.current[0]).toBe(true);
expect(result.current[1]).toBe(0.5);
});

it('should not work when target is null', async () => {
renderHook(() => useInViewport(null));
const calls = mockIntersectionObserver.mock.calls;
expect(calls[calls.length - 1]).toBeUndefined();
});

it('should disconnect when unmount', async () => {
const disconnect = jest.fn();
mockIntersectionObserver.mockReturnValue({
observe: () => null,
disconnect,
Expand Down
92 changes: 92 additions & 0 deletions packages/hooks/src/useInViewport/demo/demo3.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* title: Listening content scrolling selection menu
* desc: Pass the `callback` that is triggered when the callback of `IntersectionObserver` is called, so you can do some customization.
*
* title.zh-CN: 监听内容滚动选中菜单
* desc.zh-CN: 传入 `callback`, 使得 `IntersectionObserver` 的回调被调用时,用户可以做一些自定义操作。
*/
import { useInViewport, useMemoizedFn } from 'ahooks';
import React, { useRef, useState } from 'react';

const menus = ['menu-1', 'menu-2', 'menu-3'];
const content = {
'menu-1': 'Content for menus 1',
'menu-2': 'Content for menus 2',
'menu-3': 'Content for menus 3',
};

export default () => {
const menuRef = useRef<HTMLDivElement[]>([]);

const [activeMenu, setActiveMenu] = useState(menus[0]);

const callback = useMemoizedFn((entry) => {
coderluojz marked this conversation as resolved.
Show resolved Hide resolved
if (entry.isIntersecting) {
const active = entry.target.getAttribute('id') || '';
setActiveMenu(active);
}
});

const handleMenuClick = (index) => {
const contentEl = document.getElementById('content-scroll');
const top = menuRef.current[index]?.offsetTop;

contentEl?.scrollTo({
top,
behavior: 'smooth',
});
};

useInViewport(menuRef.current, {
callback,
root: () => document.getElementById('parent-scroll'),
rootMargin: '-50% 0px -50% 0px',
});

return (
<div
id="parent-scroll"
style={{ width: 300, height: 300, border: '1px solid', display: 'flex', overflow: 'hidden' }}
>
<div style={{ width: '30%', backgroundColor: '#f0f0f0' }}>
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
{menus.map((menu, index) => (
<li
key={menu}
onClick={() => handleMenuClick(index)}
style={{
padding: '10px',
cursor: 'pointer',
textAlign: 'center',
transition: 'background-color 0.2s ease-in-out',
backgroundColor: activeMenu === menu ? '#e0e0e0' : '',
}}
>
{menu}
</li>
))}
</ul>
</div>
<div id="content-scroll" style={{ flex: 1, overflowY: 'scroll', position: 'relative' }}>
{menus.map((menu, index) => (
<div
ref={(el: HTMLDivElement) => {
menuRef.current[index] = el;
}}
key={menu}
id={menu}
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
fontSize: 16,
}}
>
{content[menu]}
</div>
))}
</div>
</div>
);
};
17 changes: 12 additions & 5 deletions packages/hooks/src/useInViewport/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,27 @@ Observe whether the element is in the visible area, and the visible area ratio o

<code src="./demo/demo2.tsx" />

### Listening content scrolling selection menu

<code src="./demo/demo3.tsx" />

## API

```typescript
type Target = Element | (() => Element) | React.MutableRefObject<Element>;

const [inViewport, ratio] = useInViewport(
target,
target: Target | Target[],
options?: Options
);
```

### Params

| Property | Description | Type | Default |
| -------- | ------------------ | ----------------------------------------------------------- | ------- |
| target | DOM element or ref | `Element` \| `() => Element` \| `MutableRefObject<Element>` | - |
| options | Setting | `Options` | - |
| Property | Description | Type | Default |
| -------- | ---------------------------------- | ---------------------- | ------- |
| target | DOM elements or Ref, support array | `Target` \| `Target[]` | - |
| options | Setting | `Options` | - |

### Options

Expand All @@ -42,6 +48,7 @@ More information refer to [Intersection Observer API](https://developer.mozilla.
| threshold | Either a single number or an array of numbers which indicate at what percentage of the target's visibility the ratio should be executed | `number` \| `number[]` | - |
| rootMargin | Margin around the root | `string` | - |
| root | The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null. | `Element` \| `Document` \| `() => (Element/Document)` \| `MutableRefObject<Element>` | - |
| callback | Triggered when the callback of `IntersectionObserver` is called | `(entry: IntersectionObserverEntry) => void` | - |

### Result

Expand Down
24 changes: 18 additions & 6 deletions packages/hooks/src/useInViewport/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@ import type { BasicTarget } from '../utils/domTarget';
import { getTargetElement } from '../utils/domTarget';
import useEffectWithTarget from '../utils/useEffectWithTarget';

type CallbackType = (entry: IntersectionObserverEntry) => void;

export interface Options {
rootMargin?: string;
threshold?: number | number[];
root?: BasicTarget<Element>;
callback?: CallbackType;
}

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

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

useEffectWithTarget(
() => {
const el = getTargetElement(target);
if (!el) {
const targets = Array.isArray(target) ? target : [target];
coderluojz marked this conversation as resolved.
Show resolved Hide resolved
const els = targets.map((element) => getTargetElement(element)).filter(Boolean);
coderluojz marked this conversation as resolved.
Show resolved Hide resolved

coderluojz marked this conversation as resolved.
Show resolved Hide resolved
if (!els.length) {
return;
}

Expand All @@ -26,21 +33,26 @@ function useInViewport(target: BasicTarget, options?: Options) {
for (const entry of entries) {
setRatio(entry.intersectionRatio);
setState(entry.isIntersecting);
callback?.(entry);
}
},
{
...options,
...option,
root: getTargetElement(options?.root),
},
);

observer.observe(el);
els.forEach((el) => {
if (el) {
observer.observe(el);
}
});

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

Expand Down
17 changes: 12 additions & 5 deletions packages/hooks/src/useInViewport/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,27 @@ nav:

<code src="./demo/demo2.tsx" />

### 监听内容滚动选中菜单

<code src="./demo/demo3.tsx" />

## API

```typescript
type Target = Element | (() => Element) | React.MutableRefObject<Element>;

const [inViewport, ratio] = useInViewport(
target,
target: Target | Target[],
options?: Options
);
```

### Params

| 参数 | 说明 | 类型 | 默认值 |
| ------- | ---------------- | ----------------------------------------------------------- | ------ |
| target | DOM 节点或者 ref | `Element` \| `() => Element` \| `MutableRefObject<Element>` | - |
| options | 设置 | `Options` | - |
| 参数 | 说明 | 类型 | 默认值 |
| ------- | -------------------------- | ---------------------- | ------ |
| target | DOM 节点或者 Ref,支持数组 | `Target` \| `Target[]` | - |
| options | 设置 | `Options` | - |

coderluojz marked this conversation as resolved.
Show resolved Hide resolved
### Options

Expand All @@ -42,6 +48,7 @@ const [inViewport, ratio] = useInViewport(
| threshold | 可以是单一的 number 也可以是 number 数组,target 元素和 root 元素相交程度达到该值的时候 ratio 会被更新 | `number` \| `number[]` | - |
| rootMargin | 根(root)元素的外边距 | `string` | - |
| root | 指定根(root)元素,用于检查目标的可见性。必须是目标元素的父级元素,如果未指定或者为 null,则默认为浏览器视窗。 | `Element` \| `Document` \| `() => (Element/Document)` \| `MutableRefObject<Element>` | - |
| callback | `IntersectionObserver` 的回调被调用时触发 | `(entry: IntersectionObserverEntry) => void` | - |

### Result

Expand Down