Skip to content

Commit

Permalink
feat: issue JackySoft#67:添加编辑器画布拖拽能力
Browse files Browse the repository at this point in the history
  • Loading branch information
lhalou committed Nov 21, 2024
1 parent c2ae881 commit 0e81a0f
Showing 1 changed file with 57 additions and 2 deletions.
59 changes: 57 additions & 2 deletions packages/editor/src/packages/Page/Page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { useRafState } from 'ahooks';
import MarsRender from '@/packages/MarsRender/MarsRender';
import React, { useEffect } from 'react';
import { usePageStore } from '@/stores/pageStore';
import { handleActionFlow } from '@/packages/utils/action';

Expand All @@ -9,6 +10,10 @@ import { handleActionFlow } from '@/packages/utils/action';
* @returns
*/
const Page: React.FC = () => {
const [position, setPosition] = useRafState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const cache = useRef({ offset: { x: 0, y: 0 }, isDragging: false });

// 页面组件
const { config, elements } = usePageStore((state) => {
return {
Expand All @@ -17,6 +22,48 @@ const Page: React.FC = () => {
};
});

const handleMouseMove = (e: MouseEvent) => {
if (isDragging) {
setPosition({
x: e.clientX - cache.current.offset.x,
y: e.clientY - cache.current.offset.y,
});
}
};

const handleMouseUp = () => {
setIsDragging(false);
};

const handleMouseDown = (e: React.MouseEvent) => {
cache.current.offset = {
x: e.clientX - position.x,
y: e.clientY - position.y,
};
setIsDragging(true);
};

React.useEffect(() => {
const addEventListener = () => {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
};
const removeEventListener = () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};

if (isDragging) {
addEventListener();
} else {
removeEventListener();
}

return () => {
removeEventListener();
};
}, [isDragging]);

useEffect(() => {
config.events?.forEach((event) => {
if (event.actions?.length > 0) {
Expand All @@ -25,7 +72,15 @@ const Page: React.FC = () => {
});
}, [config.events]);
return (
<div style={config.style} id="page">
<div
style={{
...config.style,
transform: `translate(${position.x}px, ${position.y}px)`,
cursor: isDragging ? 'move' : 'default',
}}
id="page"
onMouseDown={handleMouseDown}
>
{<MarsRender elements={elements || []} />}
</div>
);
Expand Down

0 comments on commit 0e81a0f

Please sign in to comment.