Skip to content

Commit

Permalink
Merge pull request #76 from h2t0327/feature-enhancement-issues-67
Browse files Browse the repository at this point in the history
feat: issue #67:添加编辑器画布拖拽能力
  • Loading branch information
JackySoft authored Nov 22, 2024
2 parents 15959c6 + 0e81a0f commit ac742bf
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 ac742bf

Please sign in to comment.