import React, { Component } from 'react';
import { Stage, Layer, Rect, Text } from 'react-konva';
const App = () => {
const [position, setPosition] = React.useState({ x: 20, y: 20 });
const history = React.useRef([{ x: 20, y: 20 }]);
const historyStep = React.useRef(0);
const handleUndo = () => {
if (historyStep.current === 0) {
return;
}
historyStep.current -= 1;
const previous = history.current[historyStep.current];
setPosition(previous);
};
const handleRedo = () => {
if (historyStep.current === history.current.length - 1) {
return;
}
historyStep.current += 1;
const next = history.current[historyStep.current];
setPosition(next);
};
const handleDragEnd = (e) => {
history.current = history.current.slice(0, historyStep.current + 1);
const pos = {
x: e.target.x(),
y: e.target.y(),
};
history.current = history.current.concat([pos]);
historyStep.current += 1;
setPosition(pos);
};
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text text="undo" onClick={handleUndo} />
<Text text="redo" x={40} onClick={handleRedo} />
<Rect
x={position.x}
y={position.y}
width={50}
height={50}
fill="black"
draggable
onDragEnd={handleDragEnd}
/>
</Layer>
</Stage>
);
};
export default App;