Skip to content

Commit

Permalink
Pr/26 (#36)
Browse files Browse the repository at this point in the history
* change useEffect second argument to allow for comparrison

* fix hook bug

Co-authored-by: Cameron Loughman <cameron@zignallabs.com>
  • Loading branch information
chrisrzhou and Cameron Loughman authored Mar 7, 2020
1 parent f36e109 commit 26c49f1
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export function useResponsiveSVGSelection<T>(
const elementRef = useRef<HTMLDivElement>();
const [size, setSize] = useState(initialSize);
const [selection, setSelection] = useState(null);
const [minWidth, minHeight] = minSize;
const [initialWidth, initialHeight] = initialSize
? initialSize
: [null, null];

useEffect(() => {
const element = elementRef.current;
Expand All @@ -30,24 +34,26 @@ export function useResponsiveSVGSelection<T>(

let width = 0;
let height = 0;
if (initialSize !== undefined) {
// Use initialSize if it is provided
[width, height] = initialSize;
const isInitialSizeUndefined =
initialWidth == null || initialHeight == null;
if (isInitialSizeUndefined) {
width = initialWidth;
height = initialHeight;
} else {
// Use parentNode size if resized has not updated
width = element.parentElement.offsetWidth;
height = element.parentElement.offsetHeight;
}
width = Math.max(width, minSize[0]);
height = Math.max(height, minSize[1]);
width = Math.max(width, minWidth);
height = Math.max(height, minHeight);
updateSize(width, height);

// update resize using a resize observer
const resizeObserver = new ResizeObserver((entries): void => {
if (!entries || !entries.length) {
return;
}
if (initialSize === undefined) {
if (isInitialSizeUndefined) {
const { width, height } = entries[0].contentRect;
updateSize(width, height);
}
Expand All @@ -61,7 +67,7 @@ export function useResponsiveSVGSelection<T>(
.selectAll('*')
.remove();
};
}, [initialSize, minSize]);
}, [initialHeight, initialWidth, minHeight, minWidth]);

return [elementRef, selection, size];
}

0 comments on commit 26c49f1

Please sign in to comment.