// main.js import { initRepo, addCircle, addTriangle, moveShape } from "./docManager.js" import { createOrUpdateShapes } from "./canvasManager.js" let isDragging = false; let selectedShapeId = null; let offsetX = 0; let offsetY = 0; const container = document.getElementById("shapesCanvas"); // Add throttle function at the top function throttle(func, limit) { let inThrottle; return function(...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } } } // Initialize the document const handle = await initRepo() // draw current state createOrUpdateShapes(container, handle.docSync().shapes) // 2. Subscribe so we can re-render whenever doc changes handle.on("change", (change) => { createOrUpdateShapes(container, change.doc.shapes, change.patches); }); // 3. Buttons holen const addCircleButton = document.getElementById("addCircleButton"); const addTriangleButton = document.getElementById("addTriangleButton"); // 4. Event Listener für Buttons addCircleButton.addEventListener("click", () => { // z. B. zufällige Position/Radius addCircle(100, 100, 30); }); addTriangleButton.addEventListener("click", () => { // z. B. zufällige Koordinaten addTriangle( 200, 200, 220, 220, 180, 220); }); // Mousedown: Prüfen, ob wir auf ein Shape klicken container.addEventListener("mousedown", (e) => { const clickedElement = e.target; if (clickedElement.tagName === 'circle' || clickedElement.tagName === 'polygon') { isDragging = true; selectedShapeId = clickedElement.id; } }); // Throttled version of moveShape const throttledMoveShape = throttle((shapeId, x, y) => { moveShape(shapeId, x, y); }, 16); // 50ms throttle time (20 updates per second) // Mousemove: Shape verschieben, sofern dragging aktiv ist container.addEventListener("mousemove", (e) => { if (!isDragging || selectedShapeId === null) return; const pt = container.createSVGPoint(); pt.x = e.clientX; pt.y = e.clientY; const svgP = pt.matrixTransform(container.getScreenCTM().inverse()); const newX = svgP.x - offsetX; const newY = svgP.y - offsetY; throttledMoveShape(selectedShapeId, newX, newY); }); // Mouseup: Dragging beenden container.addEventListener("mouseup", () => { isDragging = false; selectedShapeId = null; });