Skip to content

Commit

Permalink
Merge pull request #21174 from jrencz/story-resize-safari
Browse files Browse the repository at this point in the history
Fix height adjustment in ZoomElement in Safari
  • Loading branch information
JReinhold authored Feb 28, 2023
2 parents fca8e25 + fa4b80c commit 7815aa0
Showing 1 changed file with 13 additions and 37 deletions.
50 changes: 13 additions & 37 deletions code/ui/components/src/Zoom/ZoomElement.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* global MutationObserver */
import type { ReactElement, RefObject } from 'react';
import type { ReactElement } from 'react';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import useResizeObserver from 'use-resize-observer';
import { styled } from '@storybook/theming';
import { browserSupportsCssZoom } from './browserSupportsCssZoom';

Expand All @@ -21,34 +21,6 @@ const ZoomElementWrapper = styled.div<{ scale: number; elementHeight: number }>(
}
);

const useMutationObserver = ({
element,
options = {},
callback,
}: {
element: RefObject<Element>;
options: MutationObserverInit;
callback: MutationCallback;
}): void => {
const observer = useRef<MutationObserver>();

useEffect(() => {
if (!observer.current) {
observer.current = new MutationObserver((mutationRecord, mutationObserver) => {
callback(mutationRecord, mutationObserver);
});
}

if (element?.current) {
observer.current.observe(element.current, options);
}

return () => observer.current.disconnect();
}, [callback, element, observer, options]);
};

const mutationObserverOptions = { subtree: true, childList: true };

type ZoomProps = {
scale: number;
children: ReactElement | ReactElement[];
Expand All @@ -58,20 +30,24 @@ export function ZoomElement({ scale, children }: ZoomProps) {
const componentWrapperRef = useRef<HTMLDivElement>(null);
const [elementHeight, setElementHeight] = useState(0);

const handleMutations = useCallback(() => {
setElementHeight(componentWrapperRef.current.getBoundingClientRect().height);
}, []);
const onResize = useCallback(
({ height }) => {
if (height) {
setElementHeight(height / scale);
}
},
[scale]
);

useEffect(() => {
if (componentWrapperRef.current) {
setElementHeight(componentWrapperRef.current.getBoundingClientRect().height);
}
}, [scale]);

useMutationObserver({
element: componentWrapperRef,
options: mutationObserverOptions,
callback: handleMutations,
useResizeObserver({
ref: componentWrapperRef,
onResize,
});

return (
Expand Down

0 comments on commit 7815aa0

Please sign in to comment.