silphius/app/react-components/dom.jsx
2024-06-23 07:35:56 -05:00

43 lines
945 B
JavaScript

import {useEffect, useRef, useState} from 'react';
import {RESOLUTION} from '@/constants.js';
import styles from './dom.module.css';
/**
* Dom autoscales with resolution.
*/
export default function Dom({children}) {
const ref = useRef();
const [scale, setScale] = useState(0);
useEffect(() => {
if (!ref.current) {
return;
}
function onResize() {
const {parentNode} = ref.current;
const {width} = parentNode.getBoundingClientRect();
setScale(width / RESOLUTION.x);
}
window.addEventListener('resize', onResize);
onResize();
return () => {
window.removeEventListener('resize', onResize);
}
});
return (
<div className={styles.dom} ref={ref}>
{scale > 0 && (
<style>{`
.${styles.dom}{
--scale: ${scale};
--unit: calc(${RESOLUTION.x} / 1000);
}
`}</style>
)}
{children}
</div>
);
}