fix: keep grouped object IDs unique

This commit is contained in:
Formsmith
2026-08-03 18:54:15 +03:00
parent 9d2ec76103
commit decf33521a
5 changed files with 130 additions and 14 deletions
+13 -8
View File
@@ -51,6 +51,7 @@ import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type Ske
import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel"; import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel";
import { import {
canonicalizeShape, canonicalizeShape,
cloneWorkplaneShapeTreeWithFreshIds,
cleanNearZero, cleanNearZero,
cleanRotationDegrees, cleanRotationDegrees,
fallbackSolidColor, fallbackSolidColor,
@@ -6800,12 +6801,14 @@ export function SketchForgeEditor({
setNotice("Select a shape first"); setNotice("Select a shape first");
return; return;
} }
const duplicates = selectedShapes.map((shape) => ({ const duplicates = selectedShapes.map((shape) => {
...shape, const duplicate = cloneWorkplaneShapeTreeWithFreshIds(shape, "copy");
id: createLocalId(`${shape.id}-copy`), return {
...duplicate,
x: Math.min(110, shape.x + 8), x: Math.min(110, shape.x + 8),
z: Math.min(110, shape.z + 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([...shapes, ...duplicates], duplicates.map((shape) => shape.id), `Duplicated ${duplicates.length} shape${duplicates.length === 1 ? "" : "s"}`);
}, [commitShapes, hasSelection, selectedShapes, shapes]); }, [commitShapes, hasSelection, selectedShapes, shapes]);
@@ -6835,12 +6838,14 @@ export function SketchForgeEditor({
if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) { if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) {
setClipboard(sourceClipboard); setClipboard(sourceClipboard);
} }
const pasted = sourceClipboard.map((shape) => ({ const pasted = sourceClipboard.map((shape) => {
...shape, const pastedShape = cloneWorkplaneShapeTreeWithFreshIds(shape, "paste");
id: createLocalId(`${shape.id}-paste`), return {
...pastedShape,
x: Math.min(110, shape.x + 12), x: Math.min(110, shape.x + 12),
z: Math.min(110, shape.z + 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"}`); commitShapes([...shapesRef.current, ...pasted], pasted.map((shape) => shape.id), `Pasted ${pasted.length} shape${pasted.length === 1 ? "" : "s"}`);
}, [clipboard, commitShapes]); }, [clipboard, commitShapes]);
+50 -2
View File
@@ -365,6 +365,52 @@ function assertUniqueRuntimeObjectIds(shapes: WorkplaneShape[], stateLabel: stri
shapes.forEach(visit); shapes.forEach(visit);
} }
function repairDuplicateGroupedObjectIds(shapes: WorkplaneShape[]) {
const rootIds = new Set<string>();
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<string>();
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[][]) { function referencedSourceAssetIds(states: WorkplaneShape[][]) {
const ids = new Set<string>(); const ids = new Set<string>();
const visit = (shape: WorkplaneShape) => { const visit = (shape: WorkplaneShape) => {
@@ -642,15 +688,17 @@ function unzipAsync(bytes: Uint8Array) {
export async function exportSkfProject(input: SkfProjectExportInput) { export async function exportSkfProject(input: SkfProjectExportInput) {
const hydrated = hydrateEditorHistoryState(input.shapes, input.history, input.historyIndex); 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"); 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 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)); await builder.addSources(input.assets, referencedSourceAssetIds(stateShapes));
const sourceAssetsByArchiveId = new Map(builder.assets.filter((asset) => asset.kind === "source").map((asset) => [asset.id, asset])); const sourceAssetsByArchiveId = new Map(builder.assets.filter((asset) => asset.kind === "source").map((asset) => [asset.id, asset]));
const states: SkfStateV1[] = []; const states: SkfStateV1[] = [];
const stateIdByFingerprint = new Map<string, string>(); const stateIdByFingerprint = new Map<string, string>();
const historyEntries: SkfProjectDocumentV1["history"]["entries"] = []; const historyEntries: SkfProjectDocumentV1["history"]["entries"] = [];
for (const entry of hydrated.entries) { for (const entry of exportEntries) {
let stateId = stateIdByFingerprint.get(entry.fingerprint); let stateId = stateIdByFingerprint.get(entry.fingerprint);
if (!stateId) { if (!stateId) {
stateId = `state-${states.length + 1}`; stateId = `state-${states.length + 1}`;
+9
View File
@@ -1,3 +1,4 @@
import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge"; import type { WorkplaneShape } from "@/types/sketchforge";
export function normalizeDegrees(value: number) { export function normalizeDegrees(value: number) {
@@ -21,6 +22,14 @@ export function cleanNearZero(value: number, epsilon = 0.005) {
return Math.abs(value) < epsilon ? 0 : value; 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) { export function shapeWidth(shape: WorkplaneShape) {
return shape.width ?? shape.size; return shape.width ?? shape.size;
} }
+25
View File
@@ -224,6 +224,31 @@ describe("SketchForge .skf project packages", () => {
expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box"); 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 () => { it("preserves every silently packaged undo and redo action", async () => {
const created = shape("box", "history-box", { width: 20, depth: 20, x: 0 }); const created = shape("box", "history-box", { width: 20, depth: 20, x: 0 });
const resized = { ...created, width: 30 }; const resized = { ...created, width: 30 };
+29
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import type { WorkplaneShape } from "@/types/sketchforge"; import type { WorkplaneShape } from "@/types/sketchforge";
import { import {
canonicalizeShape, canonicalizeShape,
cloneWorkplaneShapeTreeWithFreshIds,
cleanNearZero, cleanNearZero,
cleanRotationDegrees, cleanRotationDegrees,
fallbackSolidColor, fallbackSolidColor,
@@ -98,6 +99,34 @@ describe("workplane shape helpers", () => {
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined(); 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", () => { 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 importedMesh = { positions: [0, 0, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 0, sourceFormat: "json" as const };
const first = shape({ importedMesh }); const first = shape({ importedMesh });