Skip to content

Commit

Permalink
Merge branch 'main' into number-input
Browse files Browse the repository at this point in the history
  • Loading branch information
DaryaLari authored Sep 16, 2024
2 parents fc7fce7 + d442a6a commit e86d5d6
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/hooks/private/useElementSize/useElementSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import round from 'lodash/round';
import throttle from 'lodash/throttle';

const RESIZE_THROTTLE = 16;
const ROUND_PRESICION = 2;
const ROUND_PRECISION = 2;

export interface UseElementSizeResult {
width: number;
Expand All @@ -24,10 +24,16 @@ export function useElementSize<T extends HTMLElement = HTMLDivElement>(
});

React.useLayoutEffect(() => {
if (!ref?.current) {
const element = ref?.current;
if (!element) {
return undefined;
}

setSize({
width: round(element.offsetWidth, ROUND_PRECISION),
height: round(element.offsetHeight, ROUND_PRECISION),
});

const handleResize: ResizeObserverCallback = (entries) => {
if (!Array.isArray(entries)) {
return;
Expand All @@ -42,20 +48,20 @@ export function useElementSize<T extends HTMLElement = HTMLDivElement>(
// https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html#L88

setSize({
width: round(borderBoxSize.inlineSize, ROUND_PRESICION),
height: round(borderBoxSize.blockSize, ROUND_PRESICION),
width: round(borderBoxSize.inlineSize, ROUND_PRECISION),
height: round(borderBoxSize.blockSize, ROUND_PRECISION),
});
} else {
const target = entry.target as HTMLElement;
setSize({
width: round(target.offsetWidth, ROUND_PRESICION),
height: round(target.offsetHeight, ROUND_PRESICION),
width: round(target.offsetWidth, ROUND_PRECISION),
height: round(target.offsetHeight, ROUND_PRECISION),
});
}
};

const observer = new ResizeObserver(throttle(handleResize, RESIZE_THROTTLE));
observer.observe(ref.current);
observer.observe(element);

return () => {
observer.disconnect();
Expand Down

0 comments on commit e86d5d6

Please sign in to comment.