xuchang-screen/src/components/工具组件/Ruler.jsx
2023-11-07 14:21:47 +08:00

107 lines
2.1 KiB
JavaScript

import { useCallback, useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
function Ruler(props) {
const ruler = useRef(null);
const [left, setLeft] = useState(props.left || '100px');
const [dragging, setDragging] = useState(false);
const handleUp = useCallback(() => {
setDragging(false);
}, []);
const handleMove = useCallback(
(e) => {
if (!dragging) return;
const x = e.clientX;
setLeft(x + 'px');
},
[dragging],
);
useEffect(() => {
document.addEventListener('mouseup', handleUp);
document.addEventListener('mousemove', handleMove);
return () => {
document.removeEventListener('mouseup', handleUp);
document.removeEventListener('mousemove', handleMove);
};
}, [dragging]);
function handleMouseDown() {
setDragging(true);
}
return (
<motion.div
ref={ruler}
className="ruler-line"
style={{
position: 'relative',
top: 0,
left: left,
overflow: 'visible',
height: '100vh',
width: '1px',
cursor: 'pointer',
userSelect: 'none',
background: props.background || '#ccc',
}}
onMouseDown={handleMouseDown}
>
<div
className="ruler-tooltip"
style={{
position: 'absolute',
top: '200px',
right: '-132px',
width: '128px',
border: '1px solid #0008',
padding: '0 12px',
background: '#ecc100',
color: '#0008',
}}
>
left: <b>{left}</b>
</div>
</motion.div>
);
}
function RulerContainer(props) {
const [rulers, setRulers] = useState([]);
const rulerCfg = {
width: '2px',
height: '100vh',
background: '#ccc',
};
// 监听事件
useEffect(() => {
let fn = (e) => {
if (e.shiftKey && e.key === 'R') {
setRulers((rulers) => [...rulers, rulerCfg]);
}
if (e.shiftKey && e.key === 'Q') {
setRulers((rulers) => []);
}
};
document.addEventListener('keydown', fn);
}, []);
return (
<div
id="ruler-container"
style={{ position: 'fixed', top: 0, left: 0, width: 0, height: 0 }}
>
{rulers.map((ruler) => (
<Ruler key={Math.random()} {...ruler} />
))}
</div>
);
}
export default RulerContainer;