"use client"; import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react"; import { SnapGridControl } from "@/components/workplane/ShapeInspector"; import { SketchRevolvePreview } from "@/components/SketchRevolvePreview"; import { parseMeasurementInput } from "@/lib/measurementUnits"; import { WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid"; import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import type { GridSize, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure"; export type SketchSelection = | { kind: "point"; id: string } | { kind: "segment"; id: string } | { kind: "image"; id: string } | { kind: "multiple"; pointIds: string[]; segmentIds: string[]; imageIds?: string[] } | null; export type SketchMeasurement = { start: SketchPoint; end: SketchPoint } | null; type SketchWorkspaceProps = { profile: SketchProfile; operation?: SketchOperation; revolvePreviewPositions?: number[] | null; referenceShapes: WorkplaneShape[]; tool: SketchTool; activePointId: string | null; selected: SketchSelection; measurement: SketchMeasurement; pendingMeasurementStart: SketchPoint | null; initialSnap?: GridSize; initialWorkspace?: WorkplaneWorkspaceSettings; onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void; onPointPress: (id: string) => void; onSelectSegment: (id: string) => void; onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void; onSelectImage: (id: string) => void; onUpdateImage: (id: string, patch: Partial, message?: string) => void; onDeleteImage: (id: string) => void; onDeletePoint: (id: string) => void; onDeleteSegment: (id: string) => void; onMovePoint: (id: string, point: { x: number; z: number }) => void; onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void; onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void; onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void; onClearMeasurement: () => void; }; type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint }; type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean }; type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null }; type PointerAction = | { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } | { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } } | { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } } | { kind: "pan"; pointerId: number; clientX: number; clientY: number } | { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } | { kind: "move-image"; pointerId: number; imageId: string; origin: { x: number; z: number }; current: { x: number; z: number }; start: SketchImage } | { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage }; type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; function snapStep(size: GridSize) { if (size === "Off") return 0; if (size === "Brick") return 8; return Number.parseFloat(size) || 1; } function snapValue(value: number, step: number) { return step > 0 ? Math.round(value / step) * step : value; } function clamp(value: number, min: number, max: number) { return Math.min(max, Math.max(min, value)); } function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x: number; z: number }): Partial { const minimum = 0.5; const startsWest = handle.includes("w"); const startsEast = handle.includes("e"); const startsNorth = handle.includes("n"); const startsSouth = handle.includes("s"); const minX = start.x - start.width / 2; const maxX = start.x + start.width / 2; const minZ = start.z - start.depth / 2; const maxZ = start.z + start.depth / 2; const aspect = start.width / Math.max(minimum, start.depth); if (start.lockAspect !== false) { if ((startsWest || startsEast) && (startsNorth || startsSouth)) { const fixedX = startsWest ? maxX : minX; const fixedZ = startsNorth ? maxZ : minZ; const widthScale = Math.abs(point.x - fixedX) / Math.max(minimum, start.width); const depthScale = Math.abs(point.z - fixedZ) / Math.max(minimum, start.depth); const scale = Math.max(minimum / Math.min(start.width, start.depth), widthScale, depthScale); const width = Math.max(minimum, start.width * scale); const depth = Math.max(minimum, start.depth * scale); const xDirection = startsWest ? -1 : 1; const zDirection = startsNorth ? -1 : 1; return { width, depth, x: fixedX + xDirection * width / 2, z: fixedZ + zDirection * depth / 2 }; } if (startsWest || startsEast) { const fixedX = startsWest ? maxX : minX; const width = Math.max(minimum, Math.abs(point.x - fixedX)); return { width, depth: Math.max(minimum, width / aspect), x: fixedX + (startsWest ? -1 : 1) * width / 2 }; } const fixedZ = startsNorth ? maxZ : minZ; const depth = Math.max(minimum, Math.abs(point.z - fixedZ)); return { depth, width: Math.max(minimum, depth * aspect), z: fixedZ + (startsNorth ? -1 : 1) * depth / 2 }; } let nextMinX = minX; let nextMaxX = maxX; let nextMinZ = minZ; let nextMaxZ = maxZ; if (startsWest) nextMinX = Math.min(point.x, maxX - minimum); if (startsEast) nextMaxX = Math.max(point.x, minX + minimum); if (startsNorth) nextMinZ = Math.min(point.z, maxZ - minimum); if (startsSouth) nextMaxZ = Math.max(point.z, minZ + minimum); return { x: (nextMinX + nextMaxX) / 2, z: (nextMinZ + nextMaxZ) / 2, width: nextMaxX - nextMinX, depth: nextMaxZ - nextMinZ, }; } function formatDimension(value: number, accuracy: 1 | 2 | 3) { const threshold = 0.5 * 10 ** -accuracy; return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy); } function dimensionPillSize(label: string, screenUnit: number, extra = 24) { return { width: Math.max(48, label.length * 7.5 + extra) * screenUnit, height: 26 * screenUnit, radius: 5 * screenUnit, }; } function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) { const inverse = 1 - amount; return { x: inverse ** 3 * start.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * end.x, z: inverse ** 3 * start.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * end.z, }; } function segmentDimension(segment: SketchSegment, pointById: Map) { const start = pointById.get(segment.startId); const end = pointById.get(segment.endId); if (!start || !end) return null; const first = start.handleOut; const second = end.handleIn; if (segment.kind === "line" || !first || !second) { return { length: Math.hypot(end.x - start.x, end.z - start.z), midpoint: { x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 }, }; } let length = 0; let previous = start; for (let index = 1; index <= 32; index += 1) { const point = cubicPoint(start, first, second, end, index / 32); length += Math.hypot(point.x - previous.x, point.z - previous.z); previous = { ...point, id: "curve-sample" }; } return { length, midpoint: cubicPoint(start, first, second, end, 0.5) }; } function orderedPaths(profile: SketchProfile): DisplayPath[] { const pointById = new Map(profile.points.map((point) => [point.id, point])); const adjacency = new Map>(); profile.points.forEach((point) => adjacency.set(point.id, [])); const valid = profile.segments.filter((segment) => { if (!pointById.has(segment.startId) || !pointById.has(segment.endId)) return false; adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment }); adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment }); return true; }); const unvisited = new Set(valid.map((segment) => segment.id)); const paths: DisplayPath[] = []; while (unvisited.size > 0) { const seedId = unvisited.values().next().value as string; const seed = valid.find((segment) => segment.id === seedId); if (!seed) break; const component = new Set(); const queue = [seed.startId, seed.endId]; while (queue.length) { const id = queue.pop(); if (!id || component.has(id)) continue; component.add(id); adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId)); } const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId; const first = pointById.get(startId); if (!first) break; const points = [first]; const steps: PathStep[] = []; let currentId = startId; for (let guard = 0; guard <= valid.length; guard += 1) { const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id)); if (!edge) break; const from = pointById.get(currentId); const to = pointById.get(edge.pointId); if (!from || !to) break; unvisited.delete(edge.segment.id); steps.push({ segment: edge.segment, from, to }); currentId = to.id; if (currentId === startId) break; points.push(to); } paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 }); } return paths; } function curveControls(step: PathStep) { const forward = step.segment.startId === step.from.id; return { first: forward ? step.from.handleOut : step.from.handleIn, second: forward ? step.to.handleIn : step.to.handleOut, }; } function pathData(path: DisplayPath) { const first = path.points[0]; if (!first) return ""; const commands = [`M ${first.x} ${first.z}`]; path.steps.forEach((step) => { const controls = curveControls(step); if (step.segment.kind !== "line" && controls.first && controls.second) { commands.push(`C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${step.to.x} ${step.to.z}`); } else { commands.push(`L ${step.to.x} ${step.to.z}`); } }); if (path.closed) commands.push("Z"); return commands.join(" "); } function segmentData(segment: SketchSegment, pointById: Map) { const from = pointById.get(segment.startId); const to = pointById.get(segment.endId); if (!from || !to) return ""; const step = { segment, from, to }; const controls = curveControls(step); return segment.kind !== "line" && controls.first && controls.second ? `M ${from.x} ${from.z} C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${to.x} ${to.z}` : `M ${from.x} ${from.z} L ${to.x} ${to.z}`; } function isRoundReference(shape: WorkplaneShape) { return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind); } function sketchReferencePoint(shape: WorkplaneShape, x: number, z: number) { return { x: shape.x + x * mirrorSign(shape.mirrorX), z: shape.z + z * mirrorSign(shape.mirrorZ), }; } function pointKey(point: { x: number; z: number }, tolerance: number) { return `${Math.round(point.x / tolerance)},${Math.round(point.z / tolerance)}`; } function triangleArea2d(a: { x: number; z: number }, b: { x: number; z: number }, c: { x: number; z: number }) { return Math.abs((b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z)) / 2; } function trianglePath(points: Array<{ x: number; z: number }>) { return `M ${points[0].x} ${points[0].z} L ${points[1].x} ${points[1].z} L ${points[2].x} ${points[2].z} Z`; } function convexHull(points: Array<{ x: number; z: number }>) { const unique = new Map(); points.forEach((point) => unique.set(pointKey(point, 0.001), point)); const sorted = [...unique.values()].sort((a, b) => a.x === b.x ? a.z - b.z : a.x - b.x); if (sorted.length <= 2) return sorted; const cross = (origin: { x: number; z: number }, a: { x: number; z: number }, b: { x: number; z: number }) => (a.x - origin.x) * (b.z - origin.z) - (a.z - origin.z) * (b.x - origin.x); const lower: Array<{ x: number; z: number }> = []; sorted.forEach((point) => { while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0) lower.pop(); lower.push(point); }); const upper: Array<{ x: number; z: number }> = []; [...sorted].reverse().forEach((point) => { while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0) upper.pop(); upper.push(point); }); lower.pop(); upper.pop(); return [...lower, ...upper]; } function boundaryPath(points: Array<{ x: number; z: number }>, triangles: number[][], tolerance: number) { const pointByKey = new Map(); const edgeCounts = new Map(); const addEdge = (aIndex: number, bIndex: number) => { const a = points[aIndex]; const b = points[bIndex]; const aKey = pointKey(a, tolerance); const bKey = pointKey(b, tolerance); pointByKey.set(aKey, a); pointByKey.set(bKey, b); const key = aKey < bKey ? `${aKey}|${bKey}` : `${bKey}|${aKey}`; const current = edgeCounts.get(key); edgeCounts.set(key, current ? { ...current, count: current.count + 1 } : { count: 1, a: aKey, b: bKey }); }; triangles.forEach(([a, b, c]) => { addEdge(a, b); addEdge(b, c); addEdge(c, a); }); const boundaryEdges = [...edgeCounts.values()].filter((edge) => edge.count === 1); if (boundaryEdges.length === 0) return null; const adjacency = new Map(); boundaryEdges.forEach(({ a, b }) => { adjacency.set(a, [...(adjacency.get(a) ?? []), b]); adjacency.set(b, [...(adjacency.get(b) ?? []), a]); }); const unused = new Set(boundaryEdges.map(({ a, b }) => (a < b ? `${a}|${b}` : `${b}|${a}`))); const takeEdge = (a: string, b: string) => unused.delete(a < b ? `${a}|${b}` : `${b}|${a}`); const hasEdge = (a: string, b: string) => unused.has(a < b ? `${a}|${b}` : `${b}|${a}`); const commands: string[] = []; while (unused.size > 0) { const firstKey = unused.values().next().value as string; const [start, firstNext] = firstKey.split("|"); const chain = [start, firstNext]; takeEdge(start, firstNext); while (chain.length <= boundaryEdges.length + 1) { const current = chain[chain.length - 1]; const previous = chain[chain.length - 2]; const next = (adjacency.get(current) ?? []).find((candidate) => candidate !== previous && hasEdge(current, candidate)) ?? (adjacency.get(current) ?? []).find((candidate) => hasEdge(current, candidate)); if (!next) break; takeEdge(current, next); chain.push(next); if (next === start) break; } const startPoint = pointByKey.get(chain[0]); if (!startPoint) continue; const pointsD = chain .slice(1) .map((key) => pointByKey.get(key)) .filter((point): point is { x: number; z: number } => Boolean(point)) .map((point) => `L ${point.x} ${point.z}`); commands.push(`M ${startPoint.x} ${startPoint.z} ${pointsD.join(" ")}${chain[chain.length - 1] === chain[0] ? " Z" : ""}`); } return commands.join(" "); } function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint | null { if (!shape.importedMesh) return null; const positions = resizedImportedMeshPositions(shape); if (positions.length < 9) return null; let minY = Number.POSITIVE_INFINITY; for (let index = 1; index < positions.length; index += 3) { minY = Math.min(minY, positions[index]); } if (!Number.isFinite(minY)) return null; const tolerance = Math.max(0.001, Math.max(shape.width, shape.depth, shape.height) / 100000); const bottomTolerance = Math.max(0.025, shape.height * 0.003); const points: Array<{ x: number; z: number }> = []; const triangles: number[][] = []; const allProjected: Array<{ x: number; z: number }> = []; for (let index = 0; index + 8 < positions.length; index += 9) { const ys = [positions[index + 1], positions[index + 4], positions[index + 7]]; const projected = [ sketchReferencePoint(shape, positions[index], positions[index + 2]), sketchReferencePoint(shape, positions[index + 3], positions[index + 5]), sketchReferencePoint(shape, positions[index + 6], positions[index + 8]), ]; allProjected.push(...projected); if (!ys.every((value) => value <= minY + bottomTolerance) || triangleArea2d(projected[0], projected[1], projected[2]) <= tolerance) { continue; } const offset = points.length; points.push(...projected); triangles.push([offset, offset + 1, offset + 2]); } if (triangles.length > 0) { return { fillD: triangles.length <= 5000 ? triangles.map((triangle) => trianglePath(triangle.map((index) => points[index]))).join(" ") : null, outlineD: boundaryPath(points, triangles, tolerance), }; } const hull = convexHull(allProjected); if (hull.length < 3) return null; const d = `M ${hull[0].x} ${hull[0].z} ${hull.slice(1).map((point) => `L ${point.x} ${point.z}`).join(" ")} Z`; return { fillD: d, outlineD: d }; } export function SketchWorkspace({ profile, operation = "extrude", revolvePreviewPositions = null, referenceShapes, tool, activePointId, selected, measurement, pendingMeasurementStart, initialSnap, initialWorkspace, onPlanePoint, onPointPress, onSelectSegment, onSelectMany, onSelectImage, onUpdateImage, onDeleteImage, onDeletePoint, onDeleteSegment, onMovePoint, onMoveHandle, onInsertPoint, onSetPointMode, onClearMeasurement, }: SketchWorkspaceProps) { const workspace = useMemo(() => normalizeWorkspaceSettings(initialWorkspace, DEFAULT_WORKPLANE_WORKSPACE), [initialWorkspace]); const [snap, setSnap] = useState(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID)); const [snapOpen, setSnapOpen] = useState(false); const [zoom, setZoom] = useState(1); const [pan, setPan] = useState({ x: 0, z: 0 }); const [hover, setHover] = useState<{ x: number; z: number } | null>(null); const [pointerAction, setPointerAction] = useState(null); const [svgSize, setSvgSize] = useState({ width: 0, height: 0 }); const svgRef = useRef(null); const width = workspace.width / zoom; const depth = workspace.depth / zoom; const screenUnit = useMemo(() => { const fittedScale = Math.min( svgSize.width > 0 ? svgSize.width / width : 0, svgSize.height > 0 ? svgSize.height / depth : 0, ); return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720; }, [depth, svgSize.height, svgSize.width, width]); const displayProfile = useMemo(() => { if (pointerAction?.kind === "move-point") { const source = profile.points.find((point) => point.id === pointerAction.pointId); if (!source) return profile; const deltaX = pointerAction.current.x - source.x; const deltaZ = pointerAction.current.z - source.z; return { ...profile, points: profile.points.map((point) => point.id === source.id ? { ...point, ...pointerAction.current, handleIn: point.handleIn ? { x: point.handleIn.x + deltaX, z: point.handleIn.z + deltaZ } : undefined, handleOut: point.handleOut ? { x: point.handleOut.x + deltaX, z: point.handleOut.z + deltaZ } : undefined, } : point), }; } if (pointerAction?.kind === "move-handle") { return { ...profile, points: profile.points.map((point) => { if (point.id !== pointerAction.pointId) return point; const next = { ...point, handleIn: point.handleIn ? { ...point.handleIn } : undefined, handleOut: point.handleOut ? { ...point.handleOut } : undefined }; if (pointerAction.handle === "in") next.handleIn = { ...pointerAction.current }; else next.handleOut = { ...pointerAction.current }; if (point.mode === "smooth") { const opposite = { x: point.x * 2 - pointerAction.current.x, z: point.z * 2 - pointerAction.current.z }; if (pointerAction.handle === "in") next.handleOut = opposite; else next.handleIn = opposite; } return next; }), }; } return profile; }, [pointerAction, profile]); const displayImages = useMemo(() => { const images = profile.images ?? []; if (pointerAction?.kind === "move-image") { const deltaX = pointerAction.current.x - pointerAction.origin.x; const deltaZ = pointerAction.current.z - pointerAction.origin.z; return images.map((image) => image.id === pointerAction.imageId ? { ...image, x: pointerAction.start.x + deltaX, z: pointerAction.start.z + deltaZ } : image); } if (pointerAction?.kind === "resize-image") { return images.map((image) => image.id === pointerAction.imageId ? { ...image, ...resizeSketchImage(pointerAction.start, pointerAction.handle, pointerAction.current) } : image); } return images; }, [pointerAction, profile.images]); const pointById = useMemo(() => new Map(displayProfile.points.map((point) => [point.id, point])), [displayProfile.points]); const paths = useMemo(() => orderedPaths(displayProfile), [displayProfile]); const activePoint = activePointId ? pointById.get(activePointId) ?? null : null; const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null; const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null; const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false; const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false; const gridStep = clamp(workspace.gridBlockSize, 1, 200); const verticalLines = useMemo(() => { const lines: number[] = []; const start = Math.ceil((-workspace.width / 2) / gridStep) * gridStep; for (let x = start; x <= workspace.width / 2 + 0.0001; x += gridStep) lines.push(Number(x.toFixed(6))); return lines; }, [gridStep, workspace.width]); const horizontalLines = useMemo(() => { const lines: number[] = []; const start = Math.ceil((-workspace.depth / 2) / gridStep) * gridStep; for (let z = start; z <= workspace.depth / 2 + 0.0001; z += gridStep) lines.push(Number(z.toFixed(6))); return lines; }, [gridStep, workspace.depth]); const pointFromEvent = (event: { clientX: number; clientY: number }) => { const svg = svgRef.current; const matrix = svg?.getScreenCTM(); if (!svg || !matrix) return null; const screenPoint = svg.createSVGPoint(); screenPoint.x = event.clientX; screenPoint.y = event.clientY; const local = screenPoint.matrixTransform(matrix.inverse()); const step = snapStep(snap); return { x: clamp(snapValue(local.x, step), -workspace.width / 2, workspace.width / 2), z: clamp(snapValue(local.y, step), -workspace.depth / 2, workspace.depth / 2), }; }; useEffect(() => { const svg = svgRef.current; if (!svg) return; const updateSize = () => { const bounds = svg.getBoundingClientRect(); setSvgSize({ width: bounds.width, height: bounds.height }); }; updateSize(); const observer = new ResizeObserver(updateSize); observer.observe(svg); return () => observer.disconnect(); }, []); const beginPan = (event: ReactPointerEvent) => { event.preventDefault(); event.stopPropagation(); svgRef.current?.setPointerCapture(event.pointerId); setPointerAction({ kind: "pan", pointerId: event.pointerId, clientX: event.clientX, clientY: event.clientY }); }; const handlePlanePointerDown = (event: ReactPointerEvent) => { if (event.button === 1) { beginPan(event); return; } if (event.button !== 0 || (event.target !== event.currentTarget && (event.target as Element).closest("[data-sketch-entity]"))) return; const point = pointFromEvent(event); if (!point) return; event.preventDefault(); if (tool === "bezier") { event.currentTarget.setPointerCapture(event.pointerId); setPointerAction({ kind: "bezier", pointerId: event.pointerId, origin: point, current: point }); } else if (tool === "select") { event.currentTarget.setPointerCapture(event.pointerId); setPointerAction({ kind: "marquee", pointerId: event.pointerId, origin: point, current: point }); } else if (tool === "line" || tool === "smooth" || tool === "measure") { onPlanePoint(point); } }; const handlePointerMove = (event: ReactPointerEvent) => { if (pointerAction?.kind === "pan") { const matrix = svgRef.current?.getScreenCTM(); const scaleX = matrix ? Math.max(0.0001, Math.hypot(matrix.a, matrix.b)) : 1; const scaleY = matrix ? Math.max(0.0001, Math.hypot(matrix.c, matrix.d)) : 1; const deltaX = event.clientX - pointerAction.clientX; const deltaY = event.clientY - pointerAction.clientY; setPan((current) => ({ x: clamp(current.x - deltaX / scaleX, -workspace.width / 2, workspace.width / 2), z: clamp(current.z - deltaY / scaleY, -workspace.depth / 2, workspace.depth / 2), })); setPointerAction({ ...pointerAction, clientX: event.clientX, clientY: event.clientY }); return; } const point = pointFromEvent(event); setHover(point); if (point && pointerAction) setPointerAction({ ...pointerAction, current: point }); }; const finishPointerAction = (event: ReactPointerEvent) => { const action = pointerAction; if (!action || action.pointerId !== event.pointerId) return; if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); if (action.kind === "pan") { setPointerAction(null); return; } if (action.kind === "marquee") { const minX = Math.min(action.origin.x, action.current.x); const maxX = Math.max(action.origin.x, action.current.x); const minZ = Math.min(action.origin.z, action.current.z); const maxZ = Math.max(action.origin.z, action.current.z); const contains = (point: { x: number; z: number }) => point.x >= minX && point.x <= maxX && point.z >= minZ && point.z <= maxZ; const pointIds = profile.points.filter(contains).map((point) => point.id); const segmentIds = profile.segments.filter((segment) => { const start = pointById.get(segment.startId); const end = pointById.get(segment.endId); return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 }))); }).map((segment) => segment.id); onSelectMany(pointIds, segmentIds, []); setPointerAction(null); return; } if (action.kind === "bezier") { const dx = action.current.x - action.origin.x; const dz = action.current.z - action.origin.z; onPlanePoint(action.origin, { handleIn: { x: action.origin.x - dx, z: action.origin.z - dz }, handleOut: { x: action.origin.x + dx, z: action.origin.z + dz }, }); } else if (action.kind === "move-point") { onMovePoint(action.pointId, action.current); } else if (action.kind === "move-handle") { onMoveHandle(action.pointId, action.handle, action.current); } else if (action.kind === "move-image") { onUpdateImage(action.imageId, { x: action.start.x + action.current.x - action.origin.x, z: action.start.z + action.current.z - action.origin.z, }, "Sketch image moved"); } else if (action.kind === "resize-image") { onUpdateImage(action.imageId, resizeSketchImage(action.start, action.handle, action.current), "Sketch image resized"); } setPointerAction(null); }; const handleWheel = (event: ReactWheelEvent) => { event.preventDefault(); setZoom((current) => clamp(current * (event.deltaY > 0 ? 0.88 : 1.14), 0.75, 6)); }; const beginEntityDrag = (event: ReactPointerEvent, action: PointerAction) => { if (event.button !== 0) return; event.preventDefault(); event.stopPropagation(); svgRef.current?.setPointerCapture(event.pointerId); setPointerAction(action); }; const measurementLength = measurement ? Math.hypot(measurement.end.x - measurement.start.x, measurement.end.z - measurement.start.z) : 0; const measurementLabel = formatDimension(measurementLength, workspace.accuracy); const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0; const previewLabel = formatDimension(previewLength, workspace.accuracy); const labelOffset = 22 * screenUnit; const pointRadius = 5 * screenUnit; const controlPointRadius = 6 * screenUnit; const hoverPointRadius = 5 * screenUnit; const handleSize = 12 * screenUnit; const handleRadius = 2 * screenUnit; const selectedImageBounds = selectedImage ? { minX: selectedImage.x - selectedImage.width / 2, maxX: selectedImage.x + selectedImage.width / 2, minZ: selectedImage.z - selectedImage.depth / 2, maxZ: selectedImage.z + selectedImage.depth / 2, } : null; const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds ? [ { id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ }, { id: "n", x: selectedImage.x, z: selectedImageBounds.minZ }, { id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ }, { id: "e", x: selectedImageBounds.maxX, z: selectedImage.z }, { id: "se", x: selectedImageBounds.maxX, z: selectedImageBounds.maxZ }, { id: "s", x: selectedImage.x, z: selectedImageBounds.maxZ }, { id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ }, { id: "w", x: selectedImageBounds.minX, z: selectedImage.z }, ] : []; const referenceFootprints = useMemo( () => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])), [referenceShapes], ); return (
{operation === "revolve" ? "Revolve sketch" : "Sketch view"}
{operation === "revolve" ? : null}
setPointerAction(null)} onPointerLeave={() => !pointerAction && setHover(null)} onWheel={handleWheel} > {workspace.showGrid ? ( {verticalLines.map((x, index) => )} {horizontalLines.map((z, index) => )} ) : null} {operation === "revolve" ? ( REVOLVE AXIS ) : null} {displayImages.map((image) => ( { event.preventDefault(); event.stopPropagation(); if (event.button === 1) { beginPan(event); return; } if (event.button !== 0 || tool !== "select") return; const point = pointFromEvent(event); if (!point) return; beginEntityDrag(event, { kind: "move-image", pointerId: event.pointerId, imageId: image.id, origin: point, current: point, start: { ...image }, }); }} /> ))} {referenceShapes.filter((shape) => !shape.hidden).map((shape) => { const footprint = referenceFootprints.get(shape.id); return ( {footprint?.fillD || footprint?.outlineD ? ( <> {footprint.fillD ? : null} {footprint.outlineD ? : null} ) : isRoundReference(shape) ? ( ) : ( )} ); })} {pointerAction?.kind === "marquee" ? ( ) : null} {paths.some((path) => path.closed) ? path.closed).map(pathData).join(" ")} /> : null} {displayProfile.segments.map((segment) => ( { const point = pointFromEvent(event); event.preventDefault(); event.stopPropagation(); if (event.button === 1) beginPan(event); else if (tool === "erase") onDeleteSegment(segment.id); else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point); else if (event.button === 0) onSelectSegment(segment.id); }} /> ))} {displayProfile.segments.map((segment) => { const dimension = segmentDimension(segment, pointById); if (!dimension) return null; const label = formatDimension(dimension.length, workspace.accuracy); const pill = dimensionPillSize(label, screenUnit, 18); return ( {label} ); })} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? : null} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? ( {(() => { const pill = dimensionPillSize(previewLabel, screenUnit, 18); return ( <> {previewLabel} ); })()} ) : null} {pointerAction?.kind === "bezier" ? ( ) : null} {measurement ? ( { event.preventDefault(); event.stopPropagation(); onClearMeasurement(); }} > {measurementLabel} x ) : null} {pendingMeasurementStart ? ( {hover ? : null} {hover ? : null} ) : null} {selectedPoint && tool === "select" ? ( {selectedPoint.handleIn ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /> : null} {selectedPoint.handleOut ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /> : null} ) : null} {displayProfile.points.map((point) => ( { event.preventDefault(); event.stopPropagation(); if (event.button === 1) { beginPan(event); } else if (tool === "erase" || tool === "refine") { onDeletePoint(point.id); } else if (event.button === 0 && tool === "select") { onPointPress(point.id); beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } }); } else if (event.button === 0) { onPointPress(point.id); } }} /> ))} {selectedImage && selectedImageBounds && tool === "select" ? ( {(() => { const label = formatDimension(selectedImage.width, workspace.accuracy); const pill = dimensionPillSize(label, screenUnit, 18); return ( <> {label} ); })()} {(() => { const label = formatDimension(selectedImage.depth, workspace.accuracy); const pill = dimensionPillSize(label, screenUnit, 18); return ( <> {label} ); })()} {imageResizeHandles.map((handle) => ( { if (event.button === 1) { beginPan(event); return; } if (event.button !== 0) return; const point = pointFromEvent(event); if (!point) return; beginEntityDrag(event, { kind: "resize-image", pointerId: event.pointerId, imageId: selectedImage.id, handle: handle.id, current: point, start: { ...selectedImage }, }); }} /> ))} ) : null} {hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? : null}
{selectedImage && tool === "select" ? ( onSelectMany([], [], [])} onUpdate={(patch, message) => onUpdateImage(selectedImage.id, patch, message)} onDelete={() => onDeleteImage(selectedImage.id)} /> ) : null} {selectedPoint && tool === "select" ? (
) : null}
); } function SketchImageInspector({ image, accuracy, onClose, onUpdate, onDelete, }: { image: SketchImage; accuracy: 1 | 2 | 3; onClose: () => void; onUpdate: (patch: Partial, message?: string) => void; onDelete: () => void; }) { const aspect = image.width / Math.max(0.5, image.depth); const updateWidth = (width: number) => onUpdate({ width, ...(image.lockAspect !== false ? { depth: Math.max(0.5, width / aspect) } : {}), }, "Sketch image width updated"); const updateDepth = (depth: number) => onUpdate({ depth, ...(image.lockAspect !== false ? { width: Math.max(0.5, depth * aspect) } : {}), }, "Sketch image height updated"); return ( ); } function SketchImageRange({ label, value, min, max, accuracy, suffix = "mm", onChange, }: { label: string; value: number; min: number; max: number; accuracy: 1 | 2 | 3; suffix?: string; onChange: (value: number) => void; }) { const safeValue = clamp(Number.isFinite(value) ? value : min, min, max); const [draft, setDraft] = useState(formatDimension(safeValue, accuracy)); useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]); const commit = () => { const parsed = parseMeasurementInput(draft); onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max)); }; const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100; return ( ); } function SketchImagePositionField({ label, value, accuracy, onChange, }: { label: string; value: number; accuracy: 1 | 2 | 3; onChange: (value: number) => void; }) { const formatted = formatDimension(value, accuracy); const [draft, setDraft] = useState(formatted); useEffect(() => setDraft(formatted), [formatted]); const commit = () => { const parsed = parseMeasurementInput(draft); const next = Number.isFinite(parsed) ? parsed : value; onChange(next); setDraft(formatDimension(next, accuracy)); }; return ( ); }