Skip to content

feat(useMeasure): support custom measurers in order to support border-box and others #1603

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
49 changes: 49 additions & 0 deletions src/useMeasure/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs'
import { Example } from './example.stories'
import { ImportPath } from '../../__docs__/ImportPath'

<Meta title="Sensor/useMeasure" />

# useMeasure

Uses ResizeObserver to track element dimensions and re-render component when they change.

- Its ResizeObserver callback uses RAF debouncing, therefore it is pretty performant.
- SSR friendly, returns `undefined` on initial mount.
- Automatically creates ref for you, that you can easily pass to needed element.
- Allows to dynamically enable and disable observation.
- Allows to define the measures by custom `ResizeObserverEntry` matcher

#### Example

<Canvas isColumn>
<Story name="Example" story={Example} />
</Canvas>

## Reference

```ts
interface Measures {
width: number;
height: number;
}

function useMeasure<T extends Element>(enabled = true, observerEntryMatcher?: (entry: ResizeObserverEntry) => Measures | null): [Measures | undefined, React.RefObject<T>];
```

#### Importing

<ImportPath />

#### Arguments

- **enabled** _`boolean`_ _(default: `true`)_ - Whether resize observer is enabled or not.
- **observerEntryMatcher** _`((entry: ResizeObserverEntry) => Measures | null) | undefined`_ _(default: `undefined`)_ - A custom matcher function to define the measures.
- If returns `null` - default `contentRect` measures are applied

#### Return

Array of two elements:

- **0** _`Measures | undefined`_ - Width and height of the tracked element's `contentRect`
- **1** _`RefObject<T>`_ - Ref object that should be passed to tracked element
47 changes: 47 additions & 0 deletions src/useMeasure/index.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,51 @@ describe('useMeasure', () => {
expect(result.current[1]).toStrictEqual({current: div});
expect(result.current[0]).toStrictEqual(measures);
});

it('should set state by observerEntryMatcher parameter', () => {
const div = document.createElement('div');
const {result} = renderHook(() => {
const measure = useMeasure<HTMLDivElement>(true, (entry) => {
if (!entry.borderBoxSize?.length) {
return null;
}

return {
height: entry.borderBoxSize[0].blockSize,
width: entry.borderBoxSize[0].inlineSize,
};
});

useEffect(() => {
measure[1].current = div;
});

return measure;
});

const measures = {
width: 9,
height: 9,
};

const entry = {
target: div,
contentRect: {width: 5, height: 5},
borderBoxSize: [{
blockSize: 9,
inlineSize: 9,
}],
contentBoxSize: {},
} as unknown as ResizeObserverEntry;

ResizeObserverSpy.mock.calls[0][0]([entry]);
expect(result.current[0]).toBeUndefined();

act(() => {
vi.advanceTimersByTime(1);
});

expect(result.current[1]).toStrictEqual({current: div});
expect(result.current[0]).toStrictEqual(measures);
});
});
16 changes: 15 additions & 1 deletion src/useMeasure/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ export type Measures = {
* Uses ResizeObserver to track element dimensions and re-render component when they change.
*
* @param enabled Whether resize observer is enabled or not.
* @param observerEntryMatcher A custom matcher function to define the measures. If returns `null` - default `contentRect` measures are applied
*/
export function useMeasure<T extends Element>(
enabled = true,
observerEntryMatcher?: (entry: ResizeObserverEntry) => Measures | null,
): [Measures | undefined, MutableRefObject<T | null>] {
const [element, setElement] = useState<T | null>(null);
const elementRef = useHookableRef<T | null>(null, (v) => {
Expand All @@ -25,7 +27,19 @@ export function useMeasure<T extends Element>(

const [measures, setMeasures] = useState<Measures>();
const [observerHandler] = useRafCallback<UseResizeObserverCallback>((entry) => {
setMeasures({width: entry.contentRect.width, height: entry.contentRect.height});
const defaultMeasures: Measures = {
width: entry.contentRect.width,
height: entry.contentRect.height,
};

if (observerEntryMatcher) {
const matcherMeasures = observerEntryMatcher(entry);

setMeasures(matcherMeasures ?? defaultMeasures);
return;
}

setMeasures(defaultMeasures);
});

useResizeObserver(element, observerHandler, enabled);
Expand Down