silphius/app/react/components/dom/dom.jsx

46 lines
1.0 KiB
React
Raw Normal View History

2024-06-10 22:42:30 -05:00
import {useEffect, useRef, useState} from 'react';
import {RESOLUTION} from '@/constants.js';
2024-07-20 04:32:33 -05:00
import DomContext from '@/react/context/dom-scale.js';
2024-06-10 22:42:30 -05:00
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();
2024-06-11 02:24:45 -05:00
setScale(width / RESOLUTION.x);
2024-06-10 22:42:30 -05:00
}
window.addEventListener('resize', onResize);
onResize();
return () => {
window.removeEventListener('resize', onResize);
}
2024-06-23 07:35:56 -05:00
});
2024-06-10 22:42:30 -05:00
return (
<div className={styles.dom} ref={ref}>
{scale > 0 && (
2024-06-13 15:46:56 -05:00
<style>{`
.${styles.dom}{
--scale: ${scale};
--unit: calc(${RESOLUTION.x} / 1000);
}
`}</style>
2024-06-10 22:42:30 -05:00
)}
2024-07-12 00:00:48 -05:00
<DomContext.Provider value={scale}>
{children}
</DomContext.Provider>
2024-06-10 22:42:30 -05:00
</div>
);
}