/* Auto scales an element to fit the container vertically. The maximum scale is 1. The width of the element is also adjusted to have full width when scaled down. Fixes DIS-400 */ import {useState, useEffect} from 'react'; import range from 'lodash.range'; import CSS from 'csstype'; import {isClientSide} from 'shared/utils/common'; import useWindowSize from './use_window_size'; interface ScaleHeight { scale: number; height: number; } const getScaleToHeightMap = (node: HTMLElement): ScaleHeight[] => { const baseWidth = node.getBoundingClientRect().width; const clonedNode: any = node.cloneNode(true); clonedNode.style.position = 'fixed'; clonedNode.style.visibility = 'hidden'; document.body.appendChild(clonedNode); const scales = range(0.5, 1.01, 0.05).map(scale => { const width = 1 / scale; clonedNode.style.width = `${Math.round(baseWidth * width)}px`; clonedNode.style.transform = `scale(${scale})`; const rect = clonedNode.getBoundingClientRect(); return { scale, height: rect.height }; }); document.body.removeChild(clonedNode); return scales.reverse(); }; const getInnerHeight = (node?: HTMLElement): number => node ? node.getBoundingClientRect().height - (parseInt(node.style.paddingTop) || 0) - (parseInt(node.style.paddingBottom) || 0) : 0; const getScale = (node?: HTMLElement, container?: HTMLElement): number => { if (!node || !container || !isClientSide()) return 1; const height = getInnerHeight(container); if (height === 0) return 1; const scales = getScaleToHeightMap(node); const largestScaleThatFits = scales.find(scale => scale.height <= height) || scales[scales.length - 1]; return largestScaleThatFits.scale; }; const useAutoScale = ({ container, node, enabled = true }: { container?: HTMLElement; node?: HTMLElement; enabled?: boolean; }): CSS.Properties => { const windowSize = useWindowSize(); const [scale, setScale] = useState(0); const containerHeight = getInnerHeight(container); useEffect(() => { setScale(enabled ? getScale(node, container) : 0); }, [windowSize.width, setScale, container, node, enabled]); if (!enabled) return {}; return scale === 0 ? {visibility: 'hidden'} : { transform: `scale(${scale}) translate(-50%, -50%)`, transformOrigin: '0 0', width: `${100 / scale}%`, position: 'relative', top: `${containerHeight / 2}px`, left: '50%' }; }; export default useAutoScale;