mirror of
https://github.com/trafficlunar/blockmatic.git
synced 2026-06-28 06:34:13 +00:00
refactor: move clipboard util script into custom hook
This commit is contained in:
parent
14c026b81a
commit
4687330f02
4 changed files with 52 additions and 48 deletions
38
src/hooks/useClipboard.ts
Normal file
38
src/hooks/useClipboard.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { useContext } from "react";
|
||||
|
||||
import { CanvasContext } from "@/context/Canvas";
|
||||
import { SelectionContext } from "@/context/Selection";
|
||||
import { ToolContext } from "@/context/Tool";
|
||||
|
||||
export function useClipboard() {
|
||||
const { blocks } = useContext(CanvasContext);
|
||||
const { selectionCoords, setSelectionCoords, setSelectionLayerBlocks } = useContext(SelectionContext);
|
||||
const { setTool } = useContext(ToolContext);
|
||||
|
||||
function copy() {
|
||||
const selectorBlocks = selectionCoords.map(([x, y]) => blocks.find((block) => block.x === x && block.y === y)).filter(Boolean);
|
||||
navigator.clipboard.writeText(JSON.stringify(selectorBlocks));
|
||||
}
|
||||
|
||||
async function paste() {
|
||||
try {
|
||||
const clipboardText = await navigator.clipboard.readText();
|
||||
const clipboardBlocks = JSON.parse(clipboardText);
|
||||
|
||||
// Check if pasted object is of type Block[]
|
||||
if (
|
||||
!Array.isArray(clipboardBlocks) ||
|
||||
!clipboardBlocks.every((block) => typeof block.x === "number" && typeof block.y === "number" && typeof block.name === "string")
|
||||
)
|
||||
return;
|
||||
|
||||
setSelectionLayerBlocks(clipboardBlocks);
|
||||
setSelectionCoords(clipboardBlocks.map(({ x, y }) => [x, y]));
|
||||
setTool("move");
|
||||
} catch (error) {
|
||||
console.error("Failed to read/parse clipboard:", error);
|
||||
}
|
||||
}
|
||||
|
||||
return { copy, paste };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue