Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
fix: reduce autosave work and batch keyboard movement history
This commit is contained in:
@@ -87,6 +87,7 @@ import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatment
|
||||
import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryExportLimit, type EditorHistoryState } from "@/lib/editorHistory";
|
||||
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
|
||||
import { geometryRotationDegreesForShortcut, geometryRotationDelta, rotatedGeometryShapePatch } from "@/lib/geometryRotation";
|
||||
import { createKeyboardMovementInteraction, isMovementKey, moveShapesByKeyboard } from "@/lib/keyboardMovement";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { projectExportFileName } from "@/lib/exportNames";
|
||||
import { exportMeshesToObj } from "@/lib/objExport";
|
||||
@@ -6050,12 +6051,12 @@ export function SketchForgeEditor({
|
||||
}, [alignAnchorId, selectedIds, selectedShapes.length]);
|
||||
|
||||
const syncProjectShapes = useCallback(
|
||||
(nextShapes: WorkplaneShape[], force = false) => {
|
||||
(nextShapes: WorkplaneShape[], force = false, immediate = false) => {
|
||||
if (!projectId || !onProjectShapesChange) {
|
||||
return;
|
||||
}
|
||||
if (projectInteractionActiveRef.current) {
|
||||
pendingProjectShapesRef.current = nextShapes.map(canonicalizeShape);
|
||||
pendingProjectShapesRef.current = nextShapes;
|
||||
if (projectSyncTimerRef.current !== null) {
|
||||
window.clearTimeout(projectSyncTimerRef.current);
|
||||
projectSyncTimerRef.current = null;
|
||||
@@ -6070,7 +6071,8 @@ export function SketchForgeEditor({
|
||||
if (projectSyncTimerRef.current !== null) {
|
||||
window.clearTimeout(projectSyncTimerRef.current);
|
||||
}
|
||||
projectSyncTimerRef.current = window.setTimeout(() => {
|
||||
const publish = () => {
|
||||
projectSyncTimerRef.current = null;
|
||||
lastProjectShapesSyncRef.current = serialized;
|
||||
lastProjectShapesEchoRef.current = serialized;
|
||||
onProjectShapesChange({
|
||||
@@ -6087,8 +6089,9 @@ export function SketchForgeEditor({
|
||||
placementWorkplane: placementWorkplaneRef.current,
|
||||
sketchPlacementWorkplane: placementWorkplaneRef.current,
|
||||
});
|
||||
projectSyncTimerRef.current = null;
|
||||
}, 120);
|
||||
};
|
||||
if (immediate) publish();
|
||||
else projectSyncTimerRef.current = window.setTimeout(publish, 120);
|
||||
},
|
||||
[onProjectShapesChange, projectId],
|
||||
);
|
||||
@@ -6161,6 +6164,11 @@ export function SketchForgeEditor({
|
||||
const updateProjectInteractionActive = useCallback(
|
||||
(active: boolean) => {
|
||||
if (active) {
|
||||
if (projectSyncTimerRef.current !== null) {
|
||||
window.clearTimeout(projectSyncTimerRef.current);
|
||||
projectSyncTimerRef.current = null;
|
||||
pendingProjectShapesRef.current = shapesRef.current;
|
||||
}
|
||||
if (interactionHistoryTimerRef.current !== null) {
|
||||
window.clearTimeout(interactionHistoryTimerRef.current);
|
||||
interactionHistoryTimerRef.current = null;
|
||||
@@ -6188,6 +6196,59 @@ export function SketchForgeEditor({
|
||||
[finalizeInteractionHistory],
|
||||
);
|
||||
|
||||
const keyboardMovement = useMemo(() => createKeyboardMovementInteraction({
|
||||
begin: () => {
|
||||
if (projectInteractionActiveRef.current) return false;
|
||||
const selected = new Set(selectedIdsRef.current);
|
||||
if (!shapesRef.current.some((shape) => selected.has(shape.id) && !shape.locked)) return false;
|
||||
updateProjectInteractionActive(true);
|
||||
return true;
|
||||
},
|
||||
move: (event) => {
|
||||
const next = moveShapesByKeyboard(shapesRef.current, selectedIdsRef.current, event, placementWorkplaneRef.current);
|
||||
if (next === shapesRef.current) return;
|
||||
interactionHistoryChangedRef.current = true;
|
||||
shapesRef.current = next;
|
||||
pendingProjectShapesRef.current = next;
|
||||
setShapes(next);
|
||||
setNotice("Moved selection");
|
||||
},
|
||||
end: () => {
|
||||
updateProjectInteractionActive(false);
|
||||
if (interactionHistoryTimerRef.current !== null) {
|
||||
window.clearTimeout(interactionHistoryTimerRef.current);
|
||||
interactionHistoryTimerRef.current = null;
|
||||
}
|
||||
// Unlike pointer updates, keyboard moves update shapesRef synchronously.
|
||||
// Commit before another tap/shortcut or navigation can observe the scene.
|
||||
finalizeInteractionHistory();
|
||||
pendingProjectShapesRef.current = null;
|
||||
syncProjectShapes(shapesRef.current, false, true);
|
||||
},
|
||||
}), [finalizeInteractionHistory, syncProjectShapes, updateProjectInteractionActive]);
|
||||
|
||||
useEffect(() => {
|
||||
const keyUp = (event: KeyboardEvent) => keyboardMovement.keyUp(event.key);
|
||||
const visibilityChange = () => {
|
||||
if (document.visibilityState === "hidden") keyboardMovement.finish();
|
||||
};
|
||||
window.addEventListener("keyup", keyUp);
|
||||
window.addEventListener("blur", keyboardMovement.finish);
|
||||
window.addEventListener("pagehide", keyboardMovement.finish);
|
||||
window.addEventListener("pointerdown", keyboardMovement.finish, true);
|
||||
window.addEventListener("focusin", keyboardMovement.finish);
|
||||
document.addEventListener("visibilitychange", visibilityChange);
|
||||
return () => {
|
||||
window.removeEventListener("keyup", keyUp);
|
||||
window.removeEventListener("blur", keyboardMovement.finish);
|
||||
window.removeEventListener("pagehide", keyboardMovement.finish);
|
||||
window.removeEventListener("pointerdown", keyboardMovement.finish, true);
|
||||
window.removeEventListener("focusin", keyboardMovement.finish);
|
||||
document.removeEventListener("visibilitychange", visibilityChange);
|
||||
keyboardMovement.finish();
|
||||
};
|
||||
}, [keyboardMovement]);
|
||||
|
||||
const updateProjectWorkspaceSettings = useCallback(
|
||||
(settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
|
||||
const nextWorkspace = normalizeWorkspaceSettings(settings.workspace);
|
||||
@@ -7749,31 +7810,6 @@ export function SketchForgeEditor({
|
||||
);
|
||||
}, [commitShapes, hasSelection, selectedIds, selectedShapes, shapes]);
|
||||
|
||||
const raiseSelected = useCallback(
|
||||
(delta: number) => {
|
||||
if (!hasSelection) {
|
||||
return;
|
||||
}
|
||||
const selected = new Set(selectedIds);
|
||||
const normal = placementWorkplane.normal;
|
||||
commitShapes(
|
||||
shapes.map((shape) =>
|
||||
selected.has(shape.id) && !shape.locked
|
||||
? {
|
||||
...shape,
|
||||
x: cleanNearZero(shape.x + normal.x * delta),
|
||||
z: cleanNearZero(shape.z + normal.z * delta),
|
||||
elevation: cleanNearZero((shape.elevation ?? 0) + normal.y * delta),
|
||||
}
|
||||
: shape,
|
||||
),
|
||||
selectedIds,
|
||||
delta > 0 ? "Moved selection up" : "Moved selection down",
|
||||
);
|
||||
},
|
||||
[commitShapes, hasSelection, placementWorkplane, selectedIds, shapes],
|
||||
);
|
||||
|
||||
const dropSelectedToWorkplane = useCallback(() => {
|
||||
if (!hasSelection) {
|
||||
setNotice("Select a shape first");
|
||||
@@ -8840,35 +8876,6 @@ export function SketchForgeEditor({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const nudgeSelected = useCallback(
|
||||
(deltaX: number, deltaZ: number) => {
|
||||
if (!hasSelection) {
|
||||
return;
|
||||
}
|
||||
const selected = new Set(selectedIds);
|
||||
const translation = {
|
||||
x: placementWorkplane.xAxis.x * deltaX + placementWorkplane.zAxis.x * deltaZ,
|
||||
y: placementWorkplane.xAxis.y * deltaX + placementWorkplane.zAxis.y * deltaZ,
|
||||
z: placementWorkplane.xAxis.z * deltaX + placementWorkplane.zAxis.z * deltaZ,
|
||||
};
|
||||
commitShapes(
|
||||
shapes.map((shape) =>
|
||||
selected.has(shape.id) && !shape.locked
|
||||
? {
|
||||
...shape,
|
||||
x: cleanNearZero(shape.x + translation.x),
|
||||
z: cleanNearZero(shape.z + translation.z),
|
||||
elevation: cleanNearZero((shape.elevation ?? 0) + translation.y),
|
||||
}
|
||||
: shape,
|
||||
),
|
||||
selectedIds,
|
||||
`Moved ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"}`,
|
||||
);
|
||||
},
|
||||
[commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes.length, shapes],
|
||||
);
|
||||
|
||||
const rotateSelectedBy = useCallback((angleDegrees: number) => {
|
||||
if (!hasSelection) {
|
||||
return;
|
||||
@@ -8915,13 +8922,19 @@ export function SketchForgeEditor({
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (isTypingTarget(event.target)) {
|
||||
keyboardMovement.finish();
|
||||
return;
|
||||
}
|
||||
|
||||
const key = event.key.toLowerCase();
|
||||
const shortcut = event.ctrlKey || event.metaKey;
|
||||
|
||||
if (!isMovementKey(event.key) && !["Shift", "Control", "Meta", "Alt"].includes(event.key)) {
|
||||
keyboardMovement.finish();
|
||||
}
|
||||
|
||||
if (sketchActive && toolbarMode === "sketch") {
|
||||
keyboardMovement.finish();
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
setSketchActivePointId(null);
|
||||
@@ -9041,25 +9054,9 @@ export function SketchForgeEditor({
|
||||
return;
|
||||
}
|
||||
|
||||
const step = event.shiftKey ? 5 : 1;
|
||||
if (shortcut && event.key === "ArrowUp") {
|
||||
if (isMovementKey(event.key)) {
|
||||
event.preventDefault();
|
||||
raiseSelected(step);
|
||||
} else if (shortcut && event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
raiseSelected(-step);
|
||||
} else if (event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
nudgeSelected(-step, 0);
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
nudgeSelected(step, 0);
|
||||
} else if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
nudgeSelected(0, -step);
|
||||
} else if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
nudgeSelected(0, step);
|
||||
keyboardMovement.keyDown(event);
|
||||
} else if (key === "d" && hasSelection) {
|
||||
event.preventDefault();
|
||||
dropSelectedToWorkplane();
|
||||
@@ -9088,9 +9085,8 @@ export function SketchForgeEditor({
|
||||
dropSelectedToWorkplane,
|
||||
groupSelected,
|
||||
hasSelection,
|
||||
nudgeSelected,
|
||||
keyboardMovement,
|
||||
pasteShape,
|
||||
raiseSelected,
|
||||
redo,
|
||||
rotateSelectedBy,
|
||||
rotateSelectedClosedSketch45,
|
||||
|
||||
@@ -22,6 +22,7 @@ type ResourceSignature = {
|
||||
};
|
||||
|
||||
const resourceSignatureCache = new WeakMap<object, ResourceSignature>();
|
||||
const resourcesBeingSigned = new WeakSet<object>();
|
||||
const stringSignatureCache = new Map<string, ResourceSignature>();
|
||||
const MAX_CACHED_STRING_SIGNATURES = 64;
|
||||
const STREAMED_NUMERIC_ARRAY_LENGTH = 10_000;
|
||||
@@ -159,7 +160,22 @@ function signatureFromStreamedValue(resource: object) {
|
||||
|
||||
function signatureWithStreamedNumericArrays(resource: object) {
|
||||
let streamedBytes = 0;
|
||||
const serialized = JSON.stringify(resource, (_key, value: unknown) => {
|
||||
const countedResources = new Set<object | string>();
|
||||
const serialized = JSON.stringify(resource, (key, value: unknown) => {
|
||||
// A reversible operation embeds a before-shape, which can itself contain
|
||||
// large immutable geometry. Reuse those signatures across history wrappers.
|
||||
const nestedSignature = key && COMPACT_RESOURCE_KEYS.has(key) && value !== null && typeof value === "object"
|
||||
? objectResourceSignature(value)
|
||||
: COMPACT_STRING_KEYS.has(key) && typeof value === "string" && value.length > 0
|
||||
? stringResourceSignature(value)
|
||||
: undefined;
|
||||
if (nestedSignature) {
|
||||
if (!countedResources.has(value as object | string)) {
|
||||
countedResources.add(value as object | string);
|
||||
streamedBytes += nestedSignature.estimatedBytes;
|
||||
}
|
||||
return { $resource: key, fingerprint: nestedSignature.fingerprint };
|
||||
}
|
||||
const signature = largeNumericArraySignature(value);
|
||||
if (!signature) return value;
|
||||
streamedBytes += signature.estimatedBytes;
|
||||
@@ -172,12 +188,16 @@ function signatureWithStreamedNumericArrays(resource: object) {
|
||||
function objectResourceSignature(resource: object) {
|
||||
const cached = resourceSignatureCache.get(resource);
|
||||
if (cached) return cached;
|
||||
if (resourcesBeingSigned.has(resource)) throw new TypeError("Cannot fingerprint a circular resource");
|
||||
resourcesBeingSigned.add(resource);
|
||||
let signature: ResourceSignature;
|
||||
try {
|
||||
signature = signatureWithStreamedNumericArrays(resource);
|
||||
} catch (error) {
|
||||
if (!(error instanceof RangeError) || !/string length/i.test(error.message)) throw error;
|
||||
signature = signatureFromStreamedValue(resource);
|
||||
} finally {
|
||||
resourcesBeingSigned.delete(resource);
|
||||
}
|
||||
resourceSignatureCache.set(resource, signature);
|
||||
return signature;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { PlacementWorkplane } from "@/lib/placementWorkplane";
|
||||
import { cleanNearZero } from "@/lib/workplaneShapes";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
export type KeyboardMovementEvent = Pick<KeyboardEvent, "key" | "repeat" | "ctrlKey" | "metaKey" | "shiftKey">;
|
||||
|
||||
export function isMovementKey(key: string) {
|
||||
return ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(key);
|
||||
}
|
||||
|
||||
export function moveShapesByKeyboard(
|
||||
shapes: WorkplaneShape[], selectedIds: string[], event: KeyboardMovementEvent, workplane: PlacementWorkplane,
|
||||
) {
|
||||
if (!isMovementKey(event.key)) return shapes;
|
||||
const step = event.shiftKey ? 5 : 1;
|
||||
const vertical = (event.ctrlKey || event.metaKey) && (event.key === "ArrowUp" || event.key === "ArrowDown");
|
||||
const axis = vertical ? workplane.normal
|
||||
: event.key === "ArrowLeft" || event.key === "ArrowRight" ? workplane.xAxis : workplane.zAxis;
|
||||
const sign = vertical ? (event.key === "ArrowUp" ? 1 : -1)
|
||||
: event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 1;
|
||||
const delta = step * sign;
|
||||
const selected = new Set(selectedIds);
|
||||
let changed = false;
|
||||
const next = shapes.map((shape) => {
|
||||
if (!selected.has(shape.id) || shape.locked) return shape;
|
||||
const x = cleanNearZero(shape.x + axis.x * delta);
|
||||
const z = cleanNearZero(shape.z + axis.z * delta);
|
||||
const elevation = cleanNearZero((shape.elevation ?? 0) + axis.y * delta);
|
||||
if (x === shape.x && z === shape.z && elevation === (shape.elevation ?? 0)) return shape;
|
||||
changed = true;
|
||||
return { ...shape, x, z, elevation };
|
||||
});
|
||||
return changed ? next : shapes;
|
||||
}
|
||||
|
||||
// Keep this controller independent of render closures: every repeat must move
|
||||
// the latest scene, and rerenders must not end the press-to-release interaction.
|
||||
export function createKeyboardMovementInteraction(callbacks: {
|
||||
begin: () => boolean;
|
||||
move: (event: KeyboardMovementEvent) => void;
|
||||
end: () => void;
|
||||
}) {
|
||||
const pressed = new Set<string>();
|
||||
const finish = () => {
|
||||
if (pressed.size === 0) return;
|
||||
pressed.clear();
|
||||
callbacks.end();
|
||||
};
|
||||
return {
|
||||
keyDown(event: KeyboardMovementEvent) {
|
||||
if (!isMovementKey(event.key)) return false;
|
||||
// A repeat after focus loss or interruption cannot start a new gesture.
|
||||
if (pressed.size === 0 && (event.repeat || !callbacks.begin())) return false;
|
||||
pressed.add(event.key);
|
||||
callbacks.move(event);
|
||||
return true;
|
||||
},
|
||||
keyUp(key: string) {
|
||||
if (!pressed.has(key)) return;
|
||||
if (pressed.size === 1) finish();
|
||||
else pressed.delete(key);
|
||||
},
|
||||
finish,
|
||||
};
|
||||
}
|
||||
+179
-28
@@ -10,8 +10,8 @@ import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSe
|
||||
import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, SketchRevolveSettings, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
export const SKF_SCHEMA_ID = "com.sketchforge.project";
|
||||
export const SKF_FORMAT_VERSION = 1;
|
||||
export const SKF_MINIMUM_READER_VERSION = 1;
|
||||
export const SKF_FORMAT_VERSION = 2;
|
||||
export const SKF_MINIMUM_READER_VERSION = 2;
|
||||
export const SKF_CREATED_WITH_VERSION = "1.0.9";
|
||||
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
|
||||
|
||||
@@ -36,7 +36,7 @@ const FEATURE_TYPES = new Set([
|
||||
"group", "boolean-subtraction", "boolean-intersection", "mirror", "sketch-extrusion", "sketch-revolve", "fillet", "chamfer",
|
||||
]);
|
||||
|
||||
type SkfAssetKind = "source" | "derived-mesh" | "brep" | "image";
|
||||
type SkfAssetKind = "source" | "derived-mesh" | "brep" | "image" | "display-edges";
|
||||
|
||||
export type SkfAssetRecordV1 = {
|
||||
id: string;
|
||||
@@ -76,6 +76,7 @@ export type SkfShapeNodeV1 = {
|
||||
beforeNodeId: string;
|
||||
}>;
|
||||
cadBrepAssetId?: string;
|
||||
cadDisplayEdgesAssetId?: string;
|
||||
};
|
||||
|
||||
export type SkfStateV1 = {
|
||||
@@ -93,9 +94,11 @@ export type SkfFeatureV1 = {
|
||||
parameters?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
// The packaged graph layout is shared by V1 and V2. V2 moves display edges
|
||||
// from inline definitions to assets; keep the exported type name for callers.
|
||||
export type SkfProjectDocumentV1 = {
|
||||
schema: typeof SKF_SCHEMA_ID;
|
||||
formatVersion: 1;
|
||||
formatVersion: 1 | 2;
|
||||
minimumReaderVersion: number;
|
||||
createdWithVersion: string;
|
||||
metadata: {
|
||||
@@ -216,6 +219,7 @@ function safeArchivePath(path: string) {
|
||||
function extensionForAsset(kind: SkfAssetKind, mediaType: string, sourceFormat?: ProjectAssetSourceFormat) {
|
||||
if (kind === "source" && sourceFormat) return sourceFormat === "step" ? "step" : sourceFormat;
|
||||
if (kind === "derived-mesh") return "skfmesh";
|
||||
if (kind === "display-edges") return "json";
|
||||
if (kind === "brep") return "brep";
|
||||
if (mediaType.includes("png")) return "png";
|
||||
if (mediaType.includes("jpeg")) return "jpg";
|
||||
@@ -296,12 +300,55 @@ function bytesToDataUrl(bytes: Uint8Array, mediaType: string) {
|
||||
return `data:${mediaType};base64,${globalThis.btoa(binary)}`;
|
||||
}
|
||||
|
||||
// Editor geometry is immutable. Cache by the arrays themselves: restored mesh
|
||||
// wrappers may differ while their coordinate buffers are shared across history.
|
||||
type EncodedResource = { bytes: Uint8Array; sha256: string };
|
||||
const meshEncodingCache = new WeakMap<number[], WeakMap<number[], Promise<EncodedResource>>>();
|
||||
const absentNormals: number[] = [];
|
||||
const edgeEncodingCache = new WeakMap<object, Promise<EncodedResource>>();
|
||||
const byteEncodingCache = new WeakMap<Uint8Array, Promise<EncodedResource>>();
|
||||
const textEncodingCaches = { brep: new Map<string, Promise<EncodedResource>>(), image: new Map<string, Promise<EncodedResource>>() };
|
||||
const MAX_CACHED_TEXT_UNITS = 8 * 1024 * 1024;
|
||||
const cachedTextUnits = { brep: 0, image: 0 };
|
||||
|
||||
async function encodedResource(bytes: Uint8Array): Promise<EncodedResource> {
|
||||
if (bytes.byteLength > SKF_LIMITS.assetBytes) throw new Error("Resource exceeds the per-asset size limit");
|
||||
return { bytes, sha256: await sha256Hex(bytes) };
|
||||
}
|
||||
|
||||
function memoizedEncoding<K extends object>(
|
||||
cache: WeakMap<K, Promise<EncodedResource>>, key: K, encode: () => Uint8Array,
|
||||
) {
|
||||
let pending = cache.get(key);
|
||||
if (!pending) {
|
||||
pending = encodedResource(encode());
|
||||
cache.set(key, pending);
|
||||
void pending.catch(() => cache.delete(key));
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
// An await of an already-resolved resource only yields to microtasks. Use a
|
||||
// timed task boundary to let input and paint run during long history exports.
|
||||
function workBudget() {
|
||||
let started = performance.now();
|
||||
return () => {
|
||||
if (performance.now() - started < 8) return undefined;
|
||||
return new Promise<void>((resolve) => globalThis.setTimeout(() => {
|
||||
started = performance.now();
|
||||
resolve();
|
||||
}, 0));
|
||||
};
|
||||
}
|
||||
|
||||
class SkfArchiveBuilder {
|
||||
readonly files: ArchiveFiles = {};
|
||||
readonly assets: SkfAssetRecordV1[] = [];
|
||||
readonly sourceIdMap = new Map<string, string>();
|
||||
private readonly recordByKindAndHash = new Map<string, SkfAssetRecordV1>();
|
||||
private readonly derivedMeshByResource = new WeakMap<object, Promise<SkfAssetRecordV1>>();
|
||||
private readonly textByValue = { brep: new Map<string, Promise<EncodedResource>>(), image: new Map<string, Promise<EncodedResource>>() };
|
||||
readonly yieldIfNeeded = workBudget();
|
||||
|
||||
async addAsset(
|
||||
kind: SkfAssetKind,
|
||||
@@ -309,8 +356,15 @@ class SkfArchiveBuilder {
|
||||
mediaType: string,
|
||||
options: { fileName?: string; sourceFormat?: ProjectAssetSourceFormat } = {},
|
||||
) {
|
||||
if (bytes.byteLength > SKF_LIMITS.assetBytes) throw new Error(`${options.fileName ?? kind} exceeds the per-asset size limit`);
|
||||
const sha256 = await sha256Hex(bytes);
|
||||
return this.addEncodedAsset(kind, await memoizedEncoding(byteEncodingCache, bytes, () => bytes), mediaType, options);
|
||||
}
|
||||
|
||||
private addEncodedAsset(
|
||||
kind: SkfAssetKind,
|
||||
{ bytes, sha256 }: EncodedResource,
|
||||
mediaType: string,
|
||||
options: { fileName?: string; sourceFormat?: ProjectAssetSourceFormat } = {},
|
||||
) {
|
||||
const key = `${kind}:${sha256}`;
|
||||
const existing = this.recordByKindAndHash.get(key);
|
||||
if (existing) return existing;
|
||||
@@ -333,10 +387,44 @@ class SkfArchiveBuilder {
|
||||
return record;
|
||||
}
|
||||
|
||||
async addText(kind: "brep" | "image", value: string, mediaType: string, fileName?: string) {
|
||||
// Keep all text used in this save; retain only a bounded working set between saves.
|
||||
const key = value;
|
||||
const textEncodingCache = textEncodingCaches[kind];
|
||||
let pending = this.textByValue[kind].get(key) ?? textEncodingCache.get(key);
|
||||
if (!pending) {
|
||||
pending = encodedResource(kind === "image" ? decodeDataUrl(value).bytes : strToU8(value));
|
||||
if (key.length <= MAX_CACHED_TEXT_UNITS) {
|
||||
while (cachedTextUnits[kind] + key.length > MAX_CACHED_TEXT_UNITS) {
|
||||
const oldest = textEncodingCache.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
cachedTextUnits[kind] -= oldest.length;
|
||||
textEncodingCache.delete(oldest);
|
||||
}
|
||||
textEncodingCache.set(key, pending);
|
||||
cachedTextUnits[kind] += key.length;
|
||||
void pending.catch(() => {
|
||||
if (textEncodingCache.get(key) === pending) {
|
||||
textEncodingCache.delete(key);
|
||||
cachedTextUnits[kind] -= key.length;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
this.textByValue[kind].set(key, pending);
|
||||
if (kind === "image") mediaType = value.match(/^data:([^;,]+)/)?.[1] ?? "application/octet-stream";
|
||||
return this.addEncodedAsset(kind, await pending, mediaType, { fileName });
|
||||
}
|
||||
|
||||
async addDisplayEdges(edges: NonNullable<WorkplaneShape["cadDisplayEdges"]>) {
|
||||
return this.addEncodedAsset("display-edges", await memoizedEncoding(edgeEncodingCache, edges,
|
||||
() => strToU8(JSON.stringify(edges))), "application/vnd.sketchforge.display-edges+json");
|
||||
}
|
||||
|
||||
async addSources(assets: ProjectAsset[], referencedIds: Set<string>) {
|
||||
const normalized = assets
|
||||
.filter((asset) => referencedIds.has(asset.id))
|
||||
.map(normalizeProjectAsset)
|
||||
.map((asset) => asset.bytes instanceof Uint8Array ? asset : normalizeProjectAsset(asset))
|
||||
.sort((a, b) => a.id.localeCompare(b.id));
|
||||
for (const asset of normalized) {
|
||||
const record = await this.addAsset("source", asset.bytes, asset.mediaType, {
|
||||
@@ -350,7 +438,13 @@ class SkfArchiveBuilder {
|
||||
addDerivedMesh(mesh: NonNullable<WorkplaneShape["importedMesh"]>) {
|
||||
const cached = this.derivedMeshByResource.get(mesh);
|
||||
if (cached) return cached;
|
||||
const pending = this.addAsset("derived-mesh", encodeMeshCache(mesh), "application/vnd.sketchforge.mesh");
|
||||
let byNormals = meshEncodingCache.get(mesh.positions);
|
||||
if (!byNormals) {
|
||||
byNormals = new WeakMap();
|
||||
meshEncodingCache.set(mesh.positions, byNormals);
|
||||
}
|
||||
const encoded = memoizedEncoding(byNormals, mesh.normals ?? absentNormals, () => encodeMeshCache(mesh));
|
||||
const pending = encoded.then((resource) => this.addEncodedAsset("derived-mesh", resource, "application/vnd.sketchforge.mesh"));
|
||||
this.derivedMeshByResource.set(mesh, pending);
|
||||
return pending;
|
||||
}
|
||||
@@ -405,11 +499,12 @@ function repairDuplicateGroupedObjectIds(shapes: WorkplaneShape[]) {
|
||||
return { ...shape, id, ...(groupedShapes ? { groupedShapes } : {}) };
|
||||
};
|
||||
|
||||
return shapes.map((shape) => {
|
||||
const repaired = 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;
|
||||
});
|
||||
return repaired.every((shape, index) => shape === shapes[index]) ? shapes : repaired;
|
||||
}
|
||||
|
||||
function referencedSourceAssetIds(states: WorkplaneShape[][]) {
|
||||
@@ -419,7 +514,7 @@ function referencedSourceAssetIds(states: WorkplaneShape[][]) {
|
||||
shape.groupedShapes?.forEach(visit);
|
||||
shape.edgeTreatmentHistory?.forEach((entry) => visit(entry.before));
|
||||
};
|
||||
states.flat().forEach(visit);
|
||||
states.forEach((shapes) => shapes.forEach(visit));
|
||||
return ids;
|
||||
}
|
||||
|
||||
@@ -430,11 +525,13 @@ async function serializeShapeNode(
|
||||
builder: SkfArchiveBuilder,
|
||||
sourceAssetsByArchiveId: Map<string, SkfAssetRecordV1>,
|
||||
): Promise<string> {
|
||||
await builder.yieldIfNeeded();
|
||||
const {
|
||||
importedMesh,
|
||||
groupedShapes,
|
||||
edgeTreatmentHistory,
|
||||
cadBrep,
|
||||
cadDisplayEdges,
|
||||
imagePlate,
|
||||
sketchProfile,
|
||||
...baseDefinition
|
||||
@@ -443,16 +540,14 @@ async function serializeShapeNode(
|
||||
|
||||
if (imagePlate) {
|
||||
const { dataUrl, ...plateDefinition } = imagePlate;
|
||||
const decoded = decodeDataUrl(dataUrl);
|
||||
const asset = await builder.addAsset("image", decoded.bytes, decoded.mediaType, { fileName: `${shape.name}-image` });
|
||||
const asset = await builder.addText("image", dataUrl, "", `${shape.name}-image`);
|
||||
definition.imagePlate = { ...plateDefinition, assetId: asset.id };
|
||||
}
|
||||
|
||||
if (sketchProfile) {
|
||||
const images = await Promise.all((sketchProfile.images ?? []).map(async (image) => {
|
||||
const { dataUrl, ...imageDefinition } = image;
|
||||
const decoded = decodeDataUrl(dataUrl);
|
||||
const asset = await builder.addAsset("image", decoded.bytes, decoded.mediaType, { fileName: image.name });
|
||||
const asset = await builder.addText("image", dataUrl, "", image.name);
|
||||
return { ...imageDefinition, assetId: asset.id };
|
||||
}));
|
||||
definition.sketchProfile = {
|
||||
@@ -476,7 +571,7 @@ async function serializeShapeNode(
|
||||
if (!canRegenerate) {
|
||||
meshAssetId = (await builder.addDerivedMesh(importedMesh)).id;
|
||||
if (importedMesh.brepStep) {
|
||||
brepStepAssetId = (await builder.addAsset("brep", strToU8(importedMesh.brepStep), "application/step")).id;
|
||||
brepStepAssetId = (await builder.addText("brep", importedMesh.brepStep, "application/step")).id;
|
||||
}
|
||||
}
|
||||
importedReference = {
|
||||
@@ -492,7 +587,8 @@ async function serializeShapeNode(
|
||||
}
|
||||
|
||||
let cadBrepAssetId: string | undefined;
|
||||
if (cadBrep) cadBrepAssetId = (await builder.addAsset("brep", strToU8(cadBrep), "application/vnd.sketchforge.brep")).id;
|
||||
if (cadBrep) cadBrepAssetId = (await builder.addText("brep", cadBrep, "application/vnd.sketchforge.brep")).id;
|
||||
const cadDisplayEdgesAssetId = cadDisplayEdges ? (await builder.addDisplayEdges(cadDisplayEdges)).id : undefined;
|
||||
|
||||
const groupedShapeNodeIds: string[] = [];
|
||||
for (const child of groupedShapes ?? []) {
|
||||
@@ -532,6 +628,7 @@ async function serializeShapeNode(
|
||||
...(groupedShapeNodeIds.length ? { groupedShapeNodeIds } : {}),
|
||||
...(serializedEdgeHistory.length ? { edgeTreatmentHistory: serializedEdgeHistory } : {}),
|
||||
...(cadBrepAssetId ? { cadBrepAssetId } : {}),
|
||||
...(cadDisplayEdgesAssetId ? { cadDisplayEdgesAssetId } : {}),
|
||||
});
|
||||
return nodeId;
|
||||
}
|
||||
@@ -689,8 +786,10 @@ 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 exportEntries = hydrated.entries.map((entry) => {
|
||||
const shapes = repairDuplicateGroupedObjectIds(entry.shapes);
|
||||
return shapes === entry.shapes ? entry : editorHistoryEntry(shapes, entry.selectedIds);
|
||||
});
|
||||
const builder = new SkfArchiveBuilder();
|
||||
const stateShapes = exportEntries.map((entry) => entry.shapes);
|
||||
await builder.addSources(input.assets, referencedSourceAssetIds(stateShapes));
|
||||
@@ -944,7 +1043,7 @@ async function validateDocumentAndAssets(raw: unknown, files: ArchiveFiles) {
|
||||
if (document.formatVersion > SKF_FORMAT_VERSION) {
|
||||
throw new Error(`This project uses .skf format ${document.formatVersion}, which requires a newer SketchForge version`);
|
||||
}
|
||||
if (document.formatVersion < SKF_FORMAT_VERSION) throw new Error(`Packaged .skf format ${document.formatVersion} requires migration support that is not available`);
|
||||
if (document.formatVersion < 1) throw new Error(`Packaged .skf format ${document.formatVersion} requires migration support that is not available`);
|
||||
if (!Number.isInteger(document.minimumReaderVersion) || document.minimumReaderVersion > SKF_FORMAT_VERSION) {
|
||||
throw new Error("This project requires a newer SketchForge reader and was not opened");
|
||||
}
|
||||
@@ -963,7 +1062,7 @@ async function validateDocumentAndAssets(raw: unknown, files: ArchiveFiles) {
|
||||
const asset = document.assets[index];
|
||||
const id = stringValue(asset?.id, `assets[${index}].id`);
|
||||
if (assetById.has(id)) throw new Error(`Duplicate asset ID '${id}'`);
|
||||
if (!asset || !["source", "derived-mesh", "brep", "image"].includes(asset.kind)) throw new Error(`Asset '${id}' has an unknown type`);
|
||||
if (!asset || !["source", "derived-mesh", "brep", "image", "display-edges"].includes(asset.kind)) throw new Error(`Asset '${id}' has an unknown type`);
|
||||
if (!safeArchivePath(asset.path) || assetPaths.has(asset.path)) throw new Error(`Asset '${id}' has an unsafe or duplicate path`);
|
||||
assetPaths.add(asset.path);
|
||||
const bytes = files[asset.path];
|
||||
@@ -1000,6 +1099,7 @@ async function validateDocumentAndAssets(raw: unknown, files: ArchiveFiles) {
|
||||
["baseWidth", "baseDepth", "baseHeight", "triangleCount"].forEach((field) => finiteNumber(node.importedMesh?.[field as keyof SkfImportedMeshReferenceV1], `object '${objectId}'.${field}`));
|
||||
}
|
||||
if (node.cadBrepAssetId && assetById.get(node.cadBrepAssetId)?.kind !== "brep") throw new Error(`Object '${objectId}' has a missing exact B-Rep asset`);
|
||||
if (node.cadDisplayEdgesAssetId && assetById.get(node.cadDisplayEdgesAssetId)?.kind !== "display-edges") throw new Error(`Object '${objectId}' has a missing display-edge asset`);
|
||||
nodeById.set(nodeId, node);
|
||||
});
|
||||
const roots = stringArray(state.rootNodeIds, `state '${stateId}'.rootNodeIds`);
|
||||
@@ -1061,6 +1161,44 @@ async function defaultSourceImporter(asset: ProjectAsset) {
|
||||
throw new Error("SketchForge cannot reconstruct this source asset format");
|
||||
}
|
||||
|
||||
class RestoredResourceCache {
|
||||
readonly meshes = new Map<string, NonNullable<WorkplaneShape["importedMesh"]>>();
|
||||
private readonly texts = new Map<string, string>();
|
||||
private readonly edges = new Map<string, NonNullable<WorkplaneShape["cadDisplayEdges"]>>();
|
||||
readonly yieldIfNeeded = workBudget();
|
||||
|
||||
text(record: SkfAssetRecordV1, files: ArchiveFiles) {
|
||||
let value = this.texts.get(record.id);
|
||||
if (value === undefined) {
|
||||
value = record.kind === "image" ? bytesToDataUrl(files[record.path], record.mediaType) : strFromU8(files[record.path]);
|
||||
this.texts.set(record.id, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
displayEdges(record: SkfAssetRecordV1 | undefined, inline: unknown, files: ArchiveFiles) {
|
||||
// V1 stored a fresh copy in each node. Intern those copies during migration
|
||||
// so later fingerprints and exports see the same immutable resource.
|
||||
const key = record ? record.id : JSON.stringify(inline);
|
||||
let edges = this.edges.get(key);
|
||||
if (!edges) {
|
||||
const value: unknown = record ? JSON.parse(this.text(record, files)) : inline;
|
||||
if (!Array.isArray(value) || value.length > SKF_LIMITS.meshNumbers) throw new Error("Invalid display-edge resource");
|
||||
let coordinates = 0;
|
||||
for (const edge of value) {
|
||||
if (!edge || !Array.isArray(edge.points) || edge.points.length % 3 !== 0) throw new Error("Invalid display-edge points");
|
||||
coordinates += edge.points.length;
|
||||
if (coordinates > SKF_LIMITS.meshNumbers || edge.points.some((point: unknown) => typeof point !== "number" || !Number.isFinite(point))) {
|
||||
throw new Error("Invalid display-edge coordinates");
|
||||
}
|
||||
}
|
||||
edges = value;
|
||||
this.edges.set(key, edges);
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreShapeFromNode(
|
||||
nodeId: string,
|
||||
nodeById: Map<string, SkfShapeNodeV1>,
|
||||
@@ -1070,19 +1208,26 @@ async function restoreShapeFromNode(
|
||||
sourceMeshCache: Map<string, Promise<NonNullable<WorkplaneShape["importedMesh"]>>>,
|
||||
derivedMeshCache: Map<string, ReturnType<typeof decodeMeshCache>>,
|
||||
sourceImporter: SkfSourceImporter,
|
||||
resources: RestoredResourceCache,
|
||||
restoring = new Set<string>(),
|
||||
): Promise<WorkplaneShape> {
|
||||
await resources.yieldIfNeeded();
|
||||
if (restoring.has(nodeId)) throw new Error(`Cyclic shape dependency detected at '${nodeId}'`);
|
||||
const node = nodeById.get(nodeId);
|
||||
if (!node) throw new Error(`Missing shape node '${nodeId}'`);
|
||||
restoring.add(nodeId);
|
||||
const definition = { ...node.definition } as Record<string, unknown>;
|
||||
if (node.cadDisplayEdgesAssetId || definition.cadDisplayEdges !== undefined) {
|
||||
definition.cadDisplayEdges = resources.displayEdges(
|
||||
node.cadDisplayEdgesAssetId ? assetById.get(node.cadDisplayEdgesAssetId) : undefined, definition.cadDisplayEdges, files,
|
||||
);
|
||||
}
|
||||
const serializedPlate = definition.imagePlate as (Record<string, unknown> & { assetId?: string }) | undefined;
|
||||
if (serializedPlate?.assetId) {
|
||||
const record = assetById.get(serializedPlate.assetId);
|
||||
if (!record || record.kind !== "image") throw new Error(`Object '${node.objectId}' has a missing image asset`);
|
||||
const { assetId: _assetId, ...plate } = serializedPlate;
|
||||
definition.imagePlate = { ...plate, dataUrl: bytesToDataUrl(files[record.path], record.mediaType) };
|
||||
definition.imagePlate = { ...plate, dataUrl: resources.text(record, files) };
|
||||
}
|
||||
const serializedProfile = definition.sketchProfile as (Record<string, unknown> & { images?: Array<Record<string, unknown> & { assetId?: string }> }) | undefined;
|
||||
if (serializedProfile?.images) {
|
||||
@@ -1092,13 +1237,16 @@ async function restoreShapeFromNode(
|
||||
const record = image.assetId ? assetById.get(image.assetId) : undefined;
|
||||
if (!record || record.kind !== "image") throw new Error(`Sketch '${node.objectId}' has a missing image asset`);
|
||||
const { assetId: _assetId, ...rest } = image;
|
||||
return { ...rest, dataUrl: bytesToDataUrl(files[record.path], record.mediaType) };
|
||||
return { ...rest, dataUrl: resources.text(record, files) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
let importedMesh: WorkplaneShape["importedMesh"];
|
||||
if (node.importedMesh?.sourceAssetId) {
|
||||
const meshKey = node.importedMesh ? JSON.stringify(node.importedMesh) : undefined;
|
||||
if (meshKey && resources.meshes.has(meshKey)) {
|
||||
importedMesh = resources.meshes.get(meshKey);
|
||||
} else if (node.importedMesh?.sourceAssetId) {
|
||||
const sourceAsset = runtimeAssetByArchiveId.get(node.importedMesh.sourceAssetId);
|
||||
if (!sourceAsset) throw new Error(`Object '${node.objectId}' is missing its imported source asset`);
|
||||
let promise = sourceMeshCache.get(sourceAsset.id);
|
||||
@@ -1107,7 +1255,7 @@ async function restoreShapeFromNode(
|
||||
sourceMeshCache.set(sourceAsset.id, promise);
|
||||
}
|
||||
const regenerated = await promise;
|
||||
importedMesh = { ...regenerated, assetId: sourceAsset.id };
|
||||
importedMesh = resources.meshes.get(meshKey!) ?? { ...regenerated, assetId: sourceAsset.id };
|
||||
} else if (node.importedMesh?.meshAssetId) {
|
||||
const meshRecord = assetById.get(node.importedMesh.meshAssetId);
|
||||
if (!meshRecord) throw new Error(`Object '${node.objectId}' is missing its derived mesh`);
|
||||
@@ -1124,19 +1272,20 @@ async function restoreShapeFromNode(
|
||||
baseHeight: node.importedMesh.baseHeight,
|
||||
triangleCount: node.importedMesh.triangleCount,
|
||||
sourceFormat: node.importedMesh.sourceFormat,
|
||||
...(brepRecord ? { brepStep: strFromU8(files[brepRecord.path]) } : {}),
|
||||
...(brepRecord ? { brepStep: resources.text(brepRecord, files) } : {}),
|
||||
};
|
||||
}
|
||||
if (meshKey && importedMesh) resources.meshes.set(meshKey, importedMesh);
|
||||
|
||||
const groupedShapes = node.groupedShapeNodeIds?.length
|
||||
? await Promise.all(node.groupedShapeNodeIds.map((childId) => restoreShapeFromNode(childId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, derivedMeshCache, sourceImporter, new Set(restoring))))
|
||||
? await Promise.all(node.groupedShapeNodeIds.map((childId) => restoreShapeFromNode(childId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, derivedMeshCache, sourceImporter, resources, new Set(restoring))))
|
||||
: undefined;
|
||||
const edgeTreatmentHistory = node.edgeTreatmentHistory?.length
|
||||
? await Promise.all(node.edgeTreatmentHistory.map(async (entry) => ({
|
||||
id: entry.id,
|
||||
createdAt: entry.createdAt,
|
||||
feature: entry.feature as NonNullable<WorkplaneShape["edgeTreatmentHistory"]>[number]["feature"],
|
||||
before: await restoreShapeFromNode(entry.beforeNodeId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, derivedMeshCache, sourceImporter, new Set(restoring)),
|
||||
before: await restoreShapeFromNode(entry.beforeNodeId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, derivedMeshCache, sourceImporter, resources, new Set(restoring)),
|
||||
...(entry.appliedFrame ? { appliedFrame: entry.appliedFrame as NonNullable<WorkplaneShape["edgeTreatmentHistory"]>[number]["appliedFrame"] } : {}),
|
||||
})))
|
||||
: undefined;
|
||||
@@ -1147,7 +1296,7 @@ async function restoreShapeFromNode(
|
||||
...(importedMesh ? { importedMesh } : {}),
|
||||
...(groupedShapes ? { groupedShapes } : {}),
|
||||
...(edgeTreatmentHistory ? { edgeTreatmentHistory } : {}),
|
||||
...(cadBrepRecord ? { cadBrep: strFromU8(files[cadBrepRecord.path]) } : {}),
|
||||
...(cadBrepRecord ? { cadBrep: resources.text(cadBrepRecord, files) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1169,6 +1318,7 @@ async function restoreV1(document: SkfProjectDocumentV1, assetById: Map<string,
|
||||
const sourceMeshCache = new Map<string, Promise<NonNullable<WorkplaneShape["importedMesh"]>>>();
|
||||
const derivedMeshCache = new Map<string, ReturnType<typeof decodeMeshCache>>();
|
||||
const sourceImporter = options.sourceImporter ?? defaultSourceImporter;
|
||||
const resources = new RestoredResourceCache();
|
||||
const restoredStates = new Map<string, WorkplaneShape[]>();
|
||||
for (const state of document.states) {
|
||||
const nodeById = new Map(state.nodes.map((node) => [node.nodeId, node]));
|
||||
@@ -1181,6 +1331,7 @@ async function restoreV1(document: SkfProjectDocumentV1, assetById: Map<string,
|
||||
sourceMeshCache,
|
||||
derivedMeshCache,
|
||||
sourceImporter,
|
||||
resources,
|
||||
)));
|
||||
restoredStates.set(state.id, shapes);
|
||||
}
|
||||
|
||||
@@ -215,7 +215,8 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
mirrorZ: shape.mirrorZ || undefined,
|
||||
};
|
||||
if (shape.groupedShapes) {
|
||||
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
||||
const children = shape.groupedShapes.map(canonicalizeShape);
|
||||
next.groupedShapes = children.every((child, index) => child === shape.groupedShapes![index]) ? shape.groupedShapes : children;
|
||||
}
|
||||
if (shape.sketchRevolve) {
|
||||
next.sketchRevolve = {
|
||||
@@ -224,14 +225,17 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
sides: shape.sketchRevolve.sides,
|
||||
quality: shape.sketchRevolve.quality,
|
||||
};
|
||||
if (Object.keys(shape.sketchRevolve).every((key) => key in next.sketchRevolve!)) next.sketchRevolve = shape.sketchRevolve;
|
||||
}
|
||||
if (shape.edgeTreatmentHistory) {
|
||||
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
|
||||
...entry,
|
||||
before: canonicalizeShape(entry.before),
|
||||
}));
|
||||
const history = shape.edgeTreatmentHistory.map((entry) => {
|
||||
const before = canonicalizeShape(entry.before);
|
||||
return before === entry.before ? entry : { ...entry, before };
|
||||
});
|
||||
next.edgeTreatmentHistory = history.every((entry, index) => entry === shape.edgeTreatmentHistory![index]) ? shape.edgeTreatmentHistory : history;
|
||||
}
|
||||
return next;
|
||||
// Preserve immutable resource identity when normalization has nothing to do.
|
||||
return (Object.keys(next) as Array<keyof WorkplaneShape>).every((key) => next[key] === shape[key]) ? shape : next;
|
||||
}
|
||||
|
||||
export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
|
||||
|
||||
Reference in New Issue
Block a user