diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index b05530f..5cfe602 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -51,6 +51,7 @@ import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type Ske import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel"; import { canonicalizeShape, + cloneWorkplaneShapeTreeWithFreshIds, cleanNearZero, cleanRotationDegrees, fallbackSolidColor, @@ -6800,12 +6801,14 @@ export function SketchForgeEditor({ setNotice("Select a shape first"); return; } - const duplicates = selectedShapes.map((shape) => ({ - ...shape, - id: createLocalId(`${shape.id}-copy`), - x: Math.min(110, shape.x + 8), - z: Math.min(110, shape.z + 8), - })); + const duplicates = selectedShapes.map((shape) => { + const duplicate = cloneWorkplaneShapeTreeWithFreshIds(shape, "copy"); + return { + ...duplicate, + x: Math.min(110, shape.x + 8), + z: Math.min(110, shape.z + 8), + }; + }); commitShapes([...shapes, ...duplicates], duplicates.map((shape) => shape.id), `Duplicated ${duplicates.length} shape${duplicates.length === 1 ? "" : "s"}`); }, [commitShapes, hasSelection, selectedShapes, shapes]); @@ -6835,12 +6838,14 @@ export function SketchForgeEditor({ if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) { setClipboard(sourceClipboard); } - const pasted = sourceClipboard.map((shape) => ({ - ...shape, - id: createLocalId(`${shape.id}-paste`), - x: Math.min(110, shape.x + 12), - z: Math.min(110, shape.z + 12), - })); + const pasted = sourceClipboard.map((shape) => { + const pastedShape = cloneWorkplaneShapeTreeWithFreshIds(shape, "paste"); + return { + ...pastedShape, + x: Math.min(110, shape.x + 12), + z: Math.min(110, shape.z + 12), + }; + }); commitShapes([...shapesRef.current, ...pasted], pasted.map((shape) => shape.id), `Pasted ${pasted.length} shape${pasted.length === 1 ? "" : "s"}`); }, [clipboard, commitShapes]); diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts index cc211f8..8f6495e 100644 --- a/apps/web/src/lib/skfProject.ts +++ b/apps/web/src/lib/skfProject.ts @@ -365,6 +365,52 @@ function assertUniqueRuntimeObjectIds(shapes: WorkplaneShape[], stateLabel: stri shapes.forEach(visit); } +function repairDuplicateGroupedObjectIds(shapes: WorkplaneShape[]) { + const rootIds = new Set(); + for (const shape of shapes) { + if (!shape.id || rootIds.has(shape.id)) { + throw new Error(`Project state contains duplicate root object ID '${shape.id || "(empty)"}'`); + } + rootIds.add(shape.id); + } + + const reservedIds = new Set(); + const collectIds = (shape: WorkplaneShape) => { + if (shape.id) reservedIds.add(shape.id); + shape.groupedShapes?.forEach(collectIds); + }; + shapes.forEach(collectIds); + + const seenIds = new Set(rootIds); + let repairedIndex = 0; + const freshRepairId = (shape: WorkplaneShape) => { + let candidate = ""; + do { + repairedIndex += 1; + candidate = `${shape.kind || "object"}-repaired-${repairedIndex}`; + } while (reservedIds.has(candidate) || seenIds.has(candidate)); + reservedIds.add(candidate); + return candidate; + }; + + const repairChild = (shape: WorkplaneShape): WorkplaneShape => { + const id = shape.id && !seenIds.has(shape.id) ? shape.id : freshRepairId(shape); + seenIds.add(id); + const groupedShapes = shape.groupedShapes?.map(repairChild); + const childrenChanged = groupedShapes?.some((child, index) => child !== shape.groupedShapes?.[index]) ?? false; + if (id === shape.id && !childrenChanged) { + return shape; + } + return { ...shape, id, ...(groupedShapes ? { groupedShapes } : {}) }; + }; + + return shapes.map((shape) => { + const groupedShapes = shape.groupedShapes?.map(repairChild); + const childrenChanged = groupedShapes?.some((child, index) => child !== shape.groupedShapes?.[index]) ?? false; + return childrenChanged ? { ...shape, groupedShapes } : shape; + }); +} + function referencedSourceAssetIds(states: WorkplaneShape[][]) { const ids = new Set(); const visit = (shape: WorkplaneShape) => { @@ -642,15 +688,17 @@ function unzipAsync(bytes: Uint8Array) { export async function exportSkfProject(input: SkfProjectExportInput) { const hydrated = hydrateEditorHistoryState(input.shapes, input.history, input.historyIndex); if (hydrated.entries.length > SKF_LIMITS.states) throw new Error("Project has too many undo states for the .skf format"); + const exportEntries = hydrated.entries.map((entry) => + editorHistoryEntry(repairDuplicateGroupedObjectIds(entry.shapes), entry.selectedIds)); const builder = new SkfArchiveBuilder(); - const stateShapes = hydrated.entries.map((entry) => entry.shapes); + const stateShapes = exportEntries.map((entry) => entry.shapes); await builder.addSources(input.assets, referencedSourceAssetIds(stateShapes)); const sourceAssetsByArchiveId = new Map(builder.assets.filter((asset) => asset.kind === "source").map((asset) => [asset.id, asset])); const states: SkfStateV1[] = []; const stateIdByFingerprint = new Map(); const historyEntries: SkfProjectDocumentV1["history"]["entries"] = []; - for (const entry of hydrated.entries) { + for (const entry of exportEntries) { let stateId = stateIdByFingerprint.get(entry.fingerprint); if (!stateId) { stateId = `state-${states.length + 1}`; diff --git a/apps/web/src/lib/workplaneShapes.ts b/apps/web/src/lib/workplaneShapes.ts index e909366..58c2cfb 100644 --- a/apps/web/src/lib/workplaneShapes.ts +++ b/apps/web/src/lib/workplaneShapes.ts @@ -1,3 +1,4 @@ +import { createLocalId } from "@/lib/localIds"; import type { WorkplaneShape } from "@/types/sketchforge"; export function normalizeDegrees(value: number) { @@ -21,6 +22,14 @@ export function cleanNearZero(value: number, epsilon = 0.005) { return Math.abs(value) < epsilon ? 0 : value; } +export function cloneWorkplaneShapeTreeWithFreshIds(shape: WorkplaneShape, suffix: string): WorkplaneShape { + return { + ...shape, + id: createLocalId(`${shape.id}-${suffix}`), + groupedShapes: shape.groupedShapes?.map((child) => cloneWorkplaneShapeTreeWithFreshIds(child, suffix)), + }; +} + export function shapeWidth(shape: WorkplaneShape) { return shape.width ?? shape.size; } diff --git a/tests/unit/skfProject.test.ts b/tests/unit/skfProject.test.ts index f768dc8..acf8cb1 100644 --- a/tests/unit/skfProject.test.ts +++ b/tests/unit/skfProject.test.ts @@ -224,6 +224,31 @@ describe("SketchForge .skf project packages", () => { expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box"); }); + it("repairs duplicate descendant IDs from legacy shallow-copied groups during export", async () => { + const roof = shape("roundRoof", "round-roof-shared-child"); + const box = shape("box", "box-shared-child"); + const original = shape("mesh", "group-original", { groupedShapes: [roof, box] }); + const duplicate = { ...original, id: "group-copy", x: 30 }; + const history = [ + editorHistoryEntry([original], [original.id]), + editorHistoryEntry([original, duplicate], [duplicate.id]), + ]; + + const exported = await exportSkfProject(input([original, duplicate], { history, historyIndex: 1 })); + const restored = await importSkfProject(exported); + const collectIds = (entry: WorkplaneShape): string[] => [ + entry.id, + ...(entry.groupedShapes ?? []).flatMap(collectIds), + ]; + const restoredIds = restored.shapes.flatMap(collectIds); + + expect(original.groupedShapes?.[0].id).toBe(duplicate.groupedShapes?.[0].id); + expect(restored.shapes.map((entry) => entry.id)).toEqual(["group-original", "group-copy"]); + expect(new Set(restoredIds).size).toBe(restoredIds.length); + expect(restored.history).toHaveLength(2); + expect(restored.historyIndex).toBe(1); + }); + it("preserves every silently packaged undo and redo action", async () => { const created = shape("box", "history-box", { width: 20, depth: 20, x: 0 }); const resized = { ...created, width: 30 }; diff --git a/tests/unit/workplaneShapes.test.ts b/tests/unit/workplaneShapes.test.ts index 32d36a1..6004949 100644 --- a/tests/unit/workplaneShapes.test.ts +++ b/tests/unit/workplaneShapes.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import type { WorkplaneShape } from "@/types/sketchforge"; import { canonicalizeShape, + cloneWorkplaneShapeTreeWithFreshIds, cleanNearZero, cleanRotationDegrees, fallbackSolidColor, @@ -98,6 +99,34 @@ describe("workplane shape helpers", () => { expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined(); }); + it("assigns fresh object IDs throughout duplicated group trees", () => { + const original = shape({ + id: "outer-group", + kind: "mesh", + groupedShapes: [ + shape({ id: "round-roof-child", kind: "roundRoof" }), + shape({ + id: "nested-group", + kind: "mesh", + groupedShapes: [shape({ id: "nested-box" })], + }), + ], + }); + + const duplicate = cloneWorkplaneShapeTreeWithFreshIds(original, "copy"); + const collectIds = (entry: WorkplaneShape): string[] => [ + entry.id, + ...(entry.groupedShapes ?? []).flatMap(collectIds), + ]; + const originalIds = collectIds(original); + const duplicateIds = collectIds(duplicate); + + expect(new Set(duplicateIds).size).toBe(duplicateIds.length); + expect(duplicateIds.every((id) => !originalIds.includes(id))).toBe(true); + expect(original.groupedShapes?.[0].id).toBe("round-roof-child"); + expect(duplicate.groupedShapes?.[0].kind).toBe("roundRoof"); + }); + it("keeps shallow equality strict for shape payload references", () => { const importedMesh = { positions: [0, 0, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 0, sourceFormat: "json" as const }; const first = shape({ importedMesh });