import { useRef, useState } from 'react';
import { Stage, Layer, Rect, Text } from 'react-konva';
const initialRectangle = {
id: 'rectangle-1',
x: 80,
y: 100,
width: 170,
height: 110,
fill: '#4dabf7',
};
const App = () => {
const history = useRef([initialRectangle]);
const historyIndex = useRef(0);
const [rectangle, setRectangle] = useState(initialRectangle);
const commit = (nextRectangle) => {
const previousSnapshots = history.current.slice(0, historyIndex.current + 1);
history.current = [...previousSnapshots, nextRectangle];
historyIndex.current = history.current.length - 1;
setRectangle(nextRectangle);
};
const undo = () => {
if (historyIndex.current === 0) {
return;
}
historyIndex.current -= 1;
setRectangle(history.current[historyIndex.current]);
};
const redo = () => {
if (historyIndex.current === history.current.length - 1) {
return;
}
historyIndex.current += 1;
setRectangle(history.current[historyIndex.current]);
};
return (
<>
<button onClick={undo} disabled={historyIndex.current === 0}>
Undo
</button>
<button
onClick={redo}
disabled={historyIndex.current === history.current.length - 1}
>
Redo
</button>
<Stage width={window.innerWidth} height={380}>
<Layer>
<Text x={20} y={20} text="Drag the rectangle" fontSize={18} />
<Rect
{...rectangle}
stroke="#1e3a5f"
strokeWidth={3}
cornerRadius={10}
draggable
onDragEnd={(event) => {
commit({
...rectangle,
x: event.target.x(),
y: event.target.y(),
});
}}
/>
</Layer>
</Stage>
</>
);
};
export default App;