Skip to content

Commit

Permalink
feat(ui/hooks): useSize hook 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
sukvvon committed Aug 12, 2024
1 parent f91fbb2 commit 3cb50e9
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/ui/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export { useLayoutEffect } from './use-layout-effect';
export { usePosition, type Placement } from './use-position';
export { usePrevious } from './use-previous';
export { useScroll } from './use-scroll';
export { useSize } from './use-size';
export { useWindowDimension } from './use-window-dimension';
55 changes: 55 additions & 0 deletions packages/ui/src/hooks/use-size.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useState } from 'react';
import { useLayoutEffect } from './use-layout-effect';

export function useSize(element: HTMLElement | null) {
const [size, setSize] = useState<
{ width: number; height: number } | undefined
>();

useLayoutEffect(() => {
if (element) {
setSize({ width: element.offsetWidth, height: element.offsetHeight });

const resizeObserver = new ResizeObserver((entries) => {
if (!Array.isArray(entries)) {
return;
}

if (!entries.length) {
return;
}

const entry = entries[0] as ResizeObserverEntry;
let width: number;
let height: number;

if ('borderBoxSize' in entry) {
const borderBoxSizeEntry = entry.borderBoxSize;
const borderSize = (
Array.isArray(borderBoxSizeEntry)
? borderBoxSizeEntry[0]
: borderBoxSizeEntry
) as ResizeObserverSize;

width = borderSize.inlineSize;
height = borderSize.blockSize;
} else {
width = element.offsetWidth;
height = element.offsetHeight;
}

setSize({ width, height });
});

resizeObserver.observe(element);

return () => {
resizeObserver.unobserve(element);
};
} else {
setSize(undefined);
}
}, [element]);

return size;
}

0 comments on commit 3cb50e9

Please sign in to comment.