diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index c8b5c9c..6d2128d 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -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, diff --git a/apps/web/src/lib/editorHistory.ts b/apps/web/src/lib/editorHistory.ts index fcb1449..76776c2 100644 --- a/apps/web/src/lib/editorHistory.ts +++ b/apps/web/src/lib/editorHistory.ts @@ -22,6 +22,7 @@ type ResourceSignature = { }; const resourceSignatureCache = new WeakMap(); +const resourcesBeingSigned = new WeakSet(); const stringSignatureCache = new Map(); 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(); + 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; diff --git a/apps/web/src/lib/keyboardMovement.ts b/apps/web/src/lib/keyboardMovement.ts new file mode 100644 index 0000000..dd81318 --- /dev/null +++ b/apps/web/src/lib/keyboardMovement.ts @@ -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; + +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(); + 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, + }; +} diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts index 72b9ccc..4c96296 100644 --- a/apps/web/src/lib/skfProject.ts +++ b/apps/web/src/lib/skfProject.ts @@ -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; }; +// 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>>(); +const absentNormals: number[] = []; +const edgeEncodingCache = new WeakMap>(); +const byteEncodingCache = new WeakMap>(); +const textEncodingCaches = { brep: new Map>(), image: new Map>() }; +const MAX_CACHED_TEXT_UNITS = 8 * 1024 * 1024; +const cachedTextUnits = { brep: 0, image: 0 }; + +async function encodedResource(bytes: Uint8Array): Promise { + if (bytes.byteLength > SKF_LIMITS.assetBytes) throw new Error("Resource exceeds the per-asset size limit"); + return { bytes, sha256: await sha256Hex(bytes) }; +} + +function memoizedEncoding( + cache: WeakMap>, 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((resolve) => globalThis.setTimeout(() => { + started = performance.now(); + resolve(); + }, 0)); + }; +} + class SkfArchiveBuilder { readonly files: ArchiveFiles = {}; readonly assets: SkfAssetRecordV1[] = []; readonly sourceIdMap = new Map(); private readonly recordByKindAndHash = new Map(); private readonly derivedMeshByResource = new WeakMap>(); + private readonly textByValue = { brep: new Map>(), image: new Map>() }; + 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) { + 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) { 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) { 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, ): Promise { + 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>(); + private readonly texts = new Map(); + private readonly edges = new Map>(); + 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, @@ -1070,19 +1208,26 @@ async function restoreShapeFromNode( sourceMeshCache: Map>>, derivedMeshCache: Map>, sourceImporter: SkfSourceImporter, + resources: RestoredResourceCache, restoring = new Set(), ): Promise { + 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; + 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 & { 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 & { images?: Array & { 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[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[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>>(); const derivedMeshCache = new Map>(); const sourceImporter = options.sourceImporter ?? defaultSourceImporter; + const resources = new RestoredResourceCache(); const restoredStates = new Map(); 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 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).every((key) => next[key] === shape[key]) ? shape : next; } export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) { diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a667c7c..3d9c65b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +- Arrow-key holds (including Ctrl/Cmd+arrow elevation changes) now finish as one undo step and one save on release. Separate taps remain separate undo steps. +- Reduced autosave work after transforms by sharing CAD display edges across undo states and reusing immutable mesh, B-Rep, and image encoding. +- Added `.skf` format 2 shared display-edge assets, with continued reading of format 1 packages and legacy JSON projects. New saves require the updated reader. + ## 1.0.9 - Corrected Top and Bottom camera views so they align exactly with the vertical axis in both perspective and orthographic projection. diff --git a/docs/SKF_PROJECT_FORMAT.md b/docs/SKF_PROJECT_FORMAT.md index 92336b0..3f6e3fb 100644 --- a/docs/SKF_PROJECT_FORMAT.md +++ b/docs/SKF_PROJECT_FORMAT.md @@ -8,7 +8,7 @@ SketchForge uses a packaged container (format option B). A `.skf` file is a ZIP This was selected over pure JSON because imported STL/STEP data and exact B-Rep can be large, Base64 would add size and parsing overhead, and an archive lets SketchForge validate and hash each asset independently. The editable model is still JSON and can be inspected by opening `project.json` from the package. -## Version 1 layout +## Version 2 layout ```text project.skf @@ -17,7 +17,8 @@ project.skf ├── source/ Original imported STL, SVG, or STEP files ├── derived-mesh/ Exact caches for baked operations or legacy imports ├── brep/ Exact STEP/B-Rep payloads - └── image/ Deduplicated sketch/reference images + ├── image/ Deduplicated sketch/reference images + └── display-edges/ Shared CAD display-edge arrays (JSON) ``` `project.json` contains these top-level sections: @@ -36,6 +37,8 @@ project.skf Object nodes keep stable SketchForge object IDs. Groups refer to child node IDs instead of array positions. Fillet/chamfer history refers to explicit “before” nodes. Feature dependencies are explicit and checked for cycles. +Nodes reference display edges through `cadDisplayEdgesAssetId`; the edge version remains in the shape definition. Each distinct edge array is stored once, including references from groups and reversible edge-treatment history. Mesh coordinate arrays, B-Rep strings, and image data URLs are encoded and hashed once per immutable resource. Weak caches and a bounded text cache reuse this work on subsequent saves. Import restores shared mesh and edge objects across undo states. Long node traversals yield to the event loop between batches. + ## What is preserved - All current native shape kinds and their editable parameters @@ -59,7 +62,7 @@ Current safety limits are 512 MB compressed, 1 GB expanded, 256 MB per asset, 64 ## Compatibility and migrations -The current format is version 1. Readers refuse a higher `formatVersion` or `minimumReaderVersion` instead of partially loading it. The importer also contains an explicit migration for the documented version 0 pure-JSON prototype and preserves its object IDs and valid history. +New saves use format version 2 and minimum reader version 2. Older applications reject these files rather than dropping shared display edges. The current reader accepts version 1 packages with inline display edges, interns those resources on import, and writes version 2 on the next save. The importer also contains an explicit migration for the documented version 0 pure-JSON prototype and preserves its object IDs and valid history. Future schema changes should add a version-to-version migration, run validation after every migration, and never mutate the user's original file. diff --git a/output/playwright/keyboard-movement-check.js b/output/playwright/keyboard-movement-check.js new file mode 100644 index 0000000..5fc097d --- /dev/null +++ b/output/playwright/keyboard-movement-check.js @@ -0,0 +1,68 @@ +async (page) => { + await page.reload(); + await page.waitForTimeout(1000); + await page.keyboard.press('Control+a'); + await page.waitForTimeout(700); + await page.evaluate(() => { + window.__keyboardSaveCount = 0; + const originalPut = IDBObjectStore.prototype.put; + IDBObjectStore.prototype.put = function(value, ...args) { + if (this.name === 'projectShapes' && value.skfPackage) window.__keyboardSaveCount++; + return originalPut.call(this, value, ...args); + }; + }); + const state = async () => JSON.parse(await page.locator('[data-codex-state]').textContent()); + const before = await state(); + for (let i = 0; i < 31; i++) { + await page.keyboard.down('ArrowRight'); + await page.waitForTimeout(30); + } + const held = await state(); + const savesDuringHold = await page.evaluate(() => window.__keyboardSaveCount); + await page.keyboard.up('ArrowRight'); + await page.waitForTimeout(700); + const released = await state(); + const savesAfterRelease = await page.evaluate(() => window.__keyboardSaveCount); + await page.keyboard.press('Control+z'); + await page.waitForTimeout(200); + const undone = await state(); + await page.keyboard.press('Control+y'); + await page.waitForTimeout(200); + const redone = await state(); + if (savesDuringHold !== 0 || savesAfterRelease !== 1 || held.shapes[0].x !== before.shapes[0].x + 31 + || undone.shapes[0].x !== before.shapes[0].x || redone.shapes[0].x !== held.shapes[0].x) { + throw new Error('Held arrow movement was not one save and one reversible undo step'); + } + await page.keyboard.down('Control'); + for (let i = 0; i < 11; i++) { + await page.keyboard.down('ArrowUp'); + await page.waitForTimeout(30); + } + await page.keyboard.up('ArrowUp'); + await page.keyboard.up('Control'); + const raised = await state(); + await page.keyboard.press('Control+z'); + await page.waitForTimeout(150); + const unraised = await state(); + if (raised.shapes[0].elevation !== before.shapes[0].elevation + 11 + || unraised.shapes[0].elevation !== before.shapes[0].elevation) throw new Error('Raise hold did not undo as one action'); + for (let i = 0; i < 3; i++) await page.keyboard.press('ArrowRight'); + const tapped = await state(); + await page.keyboard.press('Control+z'); + await page.waitForTimeout(150); + const untapped = await state(); + if (untapped.shapes[0].x !== tapped.shapes[0].x - 1) throw new Error('Discrete taps were merged'); + await page.keyboard.down('ArrowLeft'); + await page.evaluate(() => window.dispatchEvent(new Event('blur'))); + await page.keyboard.down('ArrowLeft'); + await page.keyboard.up('ArrowLeft'); + await page.keyboard.press('Control+z'); + await page.waitForTimeout(150); + const unblurred = await state(); + if (unblurred.shapes[0].x !== untapped.shapes[0].x) throw new Error('Interrupted hold did not finalize correctly'); + return {savesDuringHold, savesAfterRelease, + holdX: [before, held, released, undone, redone].map((entry) => entry.shapes[0].x), + raiseY: [raised, unraised].map((entry) => entry.shapes[0].elevation), + tapX: [tapped, untapped].map((entry) => entry.shapes[0].x), + blurUndoX: unblurred.shapes[0].x}; +} diff --git a/tests/perf/skf-project.perf.ts b/tests/perf/skf-project.perf.ts new file mode 100644 index 0000000..33ea59a --- /dev/null +++ b/tests/perf/skf-project.perf.ts @@ -0,0 +1,66 @@ +import { expect, it } from "vitest"; +import { strFromU8, strToU8, unzipSync, zipSync } from "fflate"; +import { editorHistoryEntry } from "@/lib/editorHistory"; +import { exportSkfProject, importSkfProject, type SkfProjectDocumentV1, type SkfProjectExportInput } from "@/lib/skfProject"; +import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +it("benchmarks autosave after loading a large project with duplicated V1 edges", async () => { + const points = Array.from({ length: 30_006 }, (_, index) => Math.sin(index) * 20); + const shape: WorkplaneShape = { + id: "large-mesh", name: "Large mesh", kind: "mesh", color: "#123456", + x: 0, z: 0, size: 40, width: 40, depth: 40, height: 40, rotation: 0, + cadDisplayEdges: [{ points }], cadDisplayEdgesVersion: 2, + cadBrep: "Synthetic exact CAD payload\n".repeat(20_000), + importedMesh: { positions: points, baseWidth: 40, baseDepth: 40, baseHeight: 40, triangleCount: points.length / 9, sourceFormat: "json" }, + }; + const history = Array.from({ length: 80 }, (_, x) => editorHistoryEntry([{ ...shape, x }], [shape.id])); + const input: SkfProjectExportInput = { + projectName: "Large history benchmark", createdAt: 1_700_000_000_000, modifiedAt: 1_700_000_100_000, + shapes: history[79].shapes, history, historyIndex: 79, assets: [], + workspace: DEFAULT_WORKPLANE_WORKSPACE, snapGrid: DEFAULT_SNAP_GRID, placementElevation: 0, compressionLevel: 1, + }; + const files = unzipSync(await exportSkfProject(input)); + const document = JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1; + document.formatVersion = 1; + document.minimumReaderVersion = 1; + document.assets = document.assets.filter((asset) => asset.kind !== "display-edges"); + for (const state of document.states) for (const node of state.nodes) { + node.cadDisplayEdgesAssetId = undefined; + node.definition.cadDisplayEdges = shape.cadDisplayEdges; + } + files["project.json"] = strToU8(JSON.stringify(document)); + const legacyJsonBytes = files["project.json"].length; + const legacy = zipSync(files, { level: 1 }); + const rows: Array> = []; + async function measure(step: string, work: () => Promise) { + const start = performance.now(); + let lastTick = start; + let maxTaskGapMs = 0; + const tick = () => { + const now = performance.now(); + maxTaskGapMs = Math.max(maxTaskGapMs, now - lastTick); + lastTick = now; + }; + const timer = setInterval(tick, 1); + try { + const result = await work(); + tick(); + rows.push({ step, elapsedMs: Math.round(performance.now() - start), maxTaskGapMs: Math.round(maxTaskGapMs) }); + return result; + } finally { + clearInterval(timer); + } + } + const loaded = await measure("Import legacy V1", () => importSkfProject(legacy)); + const saveInput = { ...input, shapes: loaded.shapes, history: loaded.history }; + const saved = await measure("Autosave after import", () => exportSkfProject(saveInput)); + await measure("Repeated autosave", () => exportSkfProject(saveInput)); + await measure("Reopen compact V2", () => importSkfProject(saved)); + const savedFiles = unzipSync(saved); + rows.push({ step: "V1 sizes", jsonBytes: legacyJsonBytes, archiveBytes: legacy.length }); + rows.push({ step: "V2 sizes", jsonBytes: savedFiles["project.json"].length, archiveBytes: saved.length }); + console.table(rows); + expect(savedFiles["project.json"].length).toBeLessThan(legacyJsonBytes / 100); + expect(loaded.history).toHaveLength(80); +}); diff --git a/tests/unit/editorHistory.test.ts b/tests/unit/editorHistory.test.ts index 096e553..ab40b4d 100644 --- a/tests/unit/editorHistory.test.ts +++ b/tests/unit/editorHistory.test.ts @@ -113,6 +113,32 @@ describe("editor history snapshots", () => { .not.toBe(immutableResourceFingerprint(resource)); }); + it("reuses geometry signatures inside newly restored edge-treatment history wrappers", () => { + let coordinateReads = 0; + const points = new Proxy([0, 0, 0, 1, 2, 3], { + get(target, property, receiver) { + if (typeof property === "string" && /^\d+$/.test(property)) coordinateReads += 1; + return Reflect.get(target, property, receiver); + }, + }); + const before = box({ cadDisplayEdges: [{ points }] }); + const entry = { id: "fillet-before", createdAt: 123, feature: { kind: "fillet" as const, amount: 1, edgeCount: 1 }, before }; + const baseline = projectShapesFingerprint([box({ edgeTreatmentHistory: [entry] })]); + expect(coordinateReads).toBeGreaterThan(0); + coordinateReads = 0; + expect(projectShapesFingerprint([box({ edgeTreatmentHistory: [{ ...entry, before: { ...before } }] })])).toBe(baseline); + expect(coordinateReads).toBe(0); + expect(projectShapesFingerprint([box({ edgeTreatmentHistory: [{ ...entry, before: { ...before, x: 5 } }] })])).not.toBe(baseline); + }); + + it("preserves normalized reversible-history references across transform snapshots", () => { + const original = editorHistoryEntry([box({ edgeTreatmentHistory: [{ + id: "edge-before", createdAt: 123, feature: { kind: "fillet", amount: 1, edgeCount: 1 }, before: box(), + }] })], []); + const moved = editorHistoryEntry([{ ...original.shapes[0], x: 5 }], []); + expect(moved.shapes[0].edgeTreatmentHistory).toBe(original.shapes[0].edgeTreatmentHistory); + }); + it("falls back to direct field hashing when serialization exceeds the string limit", () => { const resource = { positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], diff --git a/tests/unit/keyboardMovement.test.ts b/tests/unit/keyboardMovement.test.ts new file mode 100644 index 0000000..90d1228 --- /dev/null +++ b/tests/unit/keyboardMovement.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it, vi } from "vitest"; +import { appendEditorHistorySnapshot, editorHistoryEntry } from "@/lib/editorHistory"; +import { createKeyboardMovementInteraction, moveShapesByKeyboard, type KeyboardMovementEvent } from "@/lib/keyboardMovement"; +import { horizontalPlacementWorkplane, type PlacementWorkplane } from "@/lib/placementWorkplane"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +function box(id = "box", locked = false): WorkplaneShape { + return { id, name: id, kind: "box", color: "#123456", x: 0, z: 0, elevation: 0, + size: 20, width: 20, depth: 20, height: 20, rotation: 0, locked }; +} + +function key(key: string, overrides: Partial = {}): KeyboardMovementEvent { + return { key, repeat: false, ctrlKey: false, metaKey: false, shiftKey: false, ...overrides }; +} + +function editorHarness(initial = [box()], selectedIds = ["box"]) { + let shapes = initial; + let history = [editorHistoryEntry(shapes, selectedIds)]; + let index = 0; + let busy = false; + const save = vi.fn(); + const begin = vi.fn(() => { + if (busy || !shapes.some((shape) => selectedIds.includes(shape.id) && !shape.locked)) return false; + busy = true; + return true; + }); + const movement = createKeyboardMovementInteraction({ + begin, + move: (event) => { shapes = moveShapesByKeyboard(shapes, selectedIds, event, horizontalPlacementWorkplane()); }, + end: () => { + busy = false; + const appended = appendEditorHistorySnapshot(history, index, editorHistoryEntry(shapes, selectedIds)); + history = appended.entries; + index = appended.index; + if (appended.changed) save(shapes); + }, + }); + return { + movement, save, begin, + get shapes() { return shapes; }, + get history() { return history; }, + setBusy() { busy = true; }, + undo() { shapes = history[--index].shapes; }, + redo() { shapes = history[++index].shapes; }, + }; +} + +describe("keyboard movement interactions", () => { + it.each([ + ["ArrowRight", {}, "x", 31], + ["ArrowLeft", {}, "x", -31], + ["ArrowUp", {}, "z", -31], + ["ArrowDown", {}, "z", 31], + ["ArrowUp", { ctrlKey: true }, "elevation", 31], + ["ArrowDown", { metaKey: true, shiftKey: true }, "elevation", -155], + ] as const)("batches a held %s into one undo step and save", (name, modifiers, coordinate, expected) => { + const editor = editorHarness(); + editor.movement.keyDown(key(name, modifiers)); + for (let repeat = 0; repeat < 30; repeat++) editor.movement.keyDown(key(name, { ...modifiers, repeat: true })); + expect(editor.shapes[0][coordinate]).toBe(expected); + expect(editor.history).toHaveLength(1); + expect(editor.save).not.toHaveBeenCalled(); + expect(editor.begin).toHaveBeenCalledTimes(1); + + editor.movement.keyUp(name); + expect(editor.history).toHaveLength(2); + expect(editor.save).toHaveBeenCalledTimes(1); + editor.undo(); + expect(editor.shapes[0][coordinate]).toBe(0); + editor.redo(); + expect(editor.shapes[0][coordinate]).toBe(expected); + }); + + it("keeps rapid discrete taps as separate undo steps", () => { + const editor = editorHarness(); + for (let tap = 0; tap < 3; tap++) { + editor.movement.keyDown(key("ArrowRight")); + editor.movement.keyUp("ArrowRight"); + } + expect(editor.history).toHaveLength(4); + expect(editor.save).toHaveBeenCalledTimes(3); + editor.undo(); + expect(editor.shapes[0].x).toBe(2); + editor.undo(); + expect(editor.shapes[0].x).toBe(1); + }); + + it("ends overlapping movement keys only when the last arrow is released", () => { + const editor = editorHarness(); + editor.movement.keyDown(key("ArrowRight")); + editor.movement.keyDown(key("ArrowUp")); + editor.movement.keyUp("ArrowRight"); + editor.movement.keyUp("Control"); + expect(editor.save).not.toHaveBeenCalled(); + editor.movement.keyDown(key("ArrowUp", { repeat: true, ctrlKey: true })); + editor.movement.keyUp("ArrowUp"); + expect(editor.shapes[0]).toMatchObject({ x: 1, z: -1, elevation: 1 }); + expect(editor.save).toHaveBeenCalledTimes(1); + }); + + it("finishes interrupted holds once and ignores stale repeats until a fresh press", () => { + const editor = editorHarness(); + editor.movement.keyDown(key("ArrowRight")); + editor.movement.finish(); // Focus loss, another command, navigation, or pointer input. + editor.movement.finish(); + editor.movement.keyUp("ArrowRight"); + expect(editor.movement.keyDown(key("ArrowRight", { repeat: true }))).toBe(false); + expect(editor.save).toHaveBeenCalledTimes(1); + expect(editor.shapes[0].x).toBe(1); + editor.movement.keyDown(key("ArrowRight")); + editor.movement.keyUp("ArrowRight"); + expect(editor.shapes[0].x).toBe(2); + expect(editor.save).toHaveBeenCalledTimes(2); + }); + + it("does not create an entry for a hold that returns to its starting position", () => { + const editor = editorHarness(); + editor.movement.keyDown(key("ArrowRight")); + editor.movement.keyDown(key("ArrowLeft")); + editor.movement.keyUp("ArrowRight"); + editor.movement.keyUp("ArrowLeft"); + expect(editor.history).toHaveLength(1); + expect(editor.save).not.toHaveBeenCalled(); + }); + + it("respects locked objects, empty selections, and an active pointer transform", () => { + for (const editor of [editorHarness([box("box", true)]), editorHarness([box()], [])]) { + expect(editor.movement.keyDown(key("ArrowRight"))).toBe(false); + editor.movement.keyUp("ArrowRight"); + expect(editor.history).toHaveLength(1); + expect(editor.save).not.toHaveBeenCalled(); + } + const editor = editorHarness(); + editor.setBusy(); + expect(editor.movement.keyDown(key("ArrowRight"))).toBe(false); + editor.movement.finish(); + expect(editor.save).not.toHaveBeenCalled(); + }); + + it("moves only unlocked selected objects along the active workplane axes", () => { + const shapes = [box(), box("locked", true), box("other")]; + const plane: PlacementWorkplane = { + origin: { x: 0, y: 0, z: 0 }, xAxis: { x: 0, y: 1, z: 0 }, + zAxis: { x: 1, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 1 }, + }; + const nudged = moveShapesByKeyboard(shapes, ["box", "locked"], key("ArrowRight", { shiftKey: true }), plane); + expect(nudged[0]).toMatchObject({ x: 0, z: 0, elevation: 5 }); + expect(nudged[1]).toBe(shapes[1]); + expect(nudged[2]).toBe(shapes[2]); + const raised = moveShapesByKeyboard(nudged, ["box"], key("ArrowUp", { ctrlKey: true }), plane); + expect(raised[0]).toMatchObject({ x: 0, z: 1, elevation: 5 }); + }); +}); diff --git a/tests/unit/skfProject.test.ts b/tests/unit/skfProject.test.ts index 98248e6..692a80a 100644 --- a/tests/unit/skfProject.test.ts +++ b/tests/unit/skfProject.test.ts @@ -3,6 +3,7 @@ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate"; import { editorHistoryEntry } from "@/lib/editorHistory"; import { placementWorkplaneFromSurface } from "@/lib/placementWorkplane"; import { projectAssetFromBytes } from "@/lib/projectAssets"; +import * as projectAssets from "@/lib/projectAssets"; import { canonicalizeShape } from "@/lib/workplaneShapes"; import { exportSkfProject, @@ -71,7 +72,95 @@ function mutateProject(bytes: Uint8Array, mutate: (document: SkfProjectDocumentV } describe("SketchForge .skf project packages", () => { - afterEach(() => vi.unstubAllGlobals()); + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it("encodes shared geometry once across a long transform history and subsequent saves", async () => { + const points = Array.from({ length: 30_000 }, (_, index) => Math.sin(index)); + const resource = shape("mesh", "shared-geometry", { + cadDisplayEdges: [{ points }], + cadDisplayEdgesVersion: 2, + cadBrep: "Shared regression BREP ".repeat(10_000), + importedMesh: { positions: points, baseWidth: 2, baseDepth: 2, baseHeight: 2, triangleCount: points.length / 9, sourceFormat: "json" }, + }); + const history = Array.from({ length: 40 }, (_, x) => editorHistoryEntry([{ ...resource, x }], [resource.id])); + const saveInput = input(history[20].shapes, { history, historyIndex: 20 }); + const hash = vi.spyOn(projectAssets, "sha256Hex"); + const bytes = await exportSkfProject(saveInput); + expect(hash).toHaveBeenCalledTimes(3); + hash.mockClear(); + await exportSkfProject(saveInput); + expect(hash).not.toHaveBeenCalled(); + + const { files, document } = packageDocument(bytes); + expect(document.assets.map((asset) => asset.kind).sort()).toEqual(["brep", "derived-mesh", "display-edges"]); + expect(files["project.json"].length).toBeLessThan(100_000); + expect(document.states.every((state) => state.nodes.every((node) => node.definition.cadDisplayEdges === undefined))).toBe(true); + const restored = await importSkfProject(bytes); + expect(restored.historyIndex).toBe(20); + expect(restored.history.map((entry) => entry.shapes[0].x)).toEqual(history.map((entry) => entry.shapes[0].x)); + for (const entry of restored.history) { + expect(entry.shapes[0].cadDisplayEdges).toBe(restored.shapes[0].cadDisplayEdges); + expect(entry.shapes[0].importedMesh).toBe(restored.shapes[0].importedMesh); + } + expect(restored.shapes[0].cadDisplayEdges).toEqual(resource.cadDisplayEdges); + expect(restored.shapes[0].cadBrep).toBe(resource.cadBrep); + hash.mockClear(); + await exportSkfProject(input(restored.shapes, { history: restored.history, historyIndex: restored.historyIndex })); + expect(hash).toHaveBeenCalledTimes(2); // One mesh and one edge resource, independent of state count. + }); + + it("reads V1 inline display edges and interns them before re-saving", async () => { + const original = shape("box", "legacy-edges", { cadDisplayEdges: [{ points: [0, 0, 0, 1, 2, 3] }], cadDisplayEdgesVersion: 2 }); + const moved = { ...original, x: 42 }; + const history = [editorHistoryEntry([original], []), editorHistoryEntry([moved], [moved.id])]; + const packaged = await exportSkfProject(input([moved], { history, historyIndex: 1 })); + const legacy = mutateProject(packaged, (document) => { + document.formatVersion = 1; + document.minimumReaderVersion = 1; + document.assets = document.assets.filter((asset) => asset.kind !== "display-edges"); + for (const state of document.states) for (const node of state.nodes) { + node.cadDisplayEdgesAssetId = undefined; + node.definition.cadDisplayEdges = original.cadDisplayEdges; + } + }); + const restored = await importSkfProject(legacy); + expect(restored.history).toHaveLength(2); + expect(restored.history[0].shapes[0].cadDisplayEdges).toBe(restored.shapes[0].cadDisplayEdges); + const saved = packageDocument(await exportSkfProject(input(restored.shapes, { history: restored.history, historyIndex: 1 }))); + expect(saved.document.assets.filter((asset) => asset.kind === "display-edges")).toHaveLength(1); + }); + + it("keeps replaced edge and mesh arrays distinct even when their lengths match", async () => { + const original = shape("mesh", "changed-resources", { + cadDisplayEdges: [{ points: [0, 0, 0, 1, 1, 1] }], + importedMesh: { positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 1, sourceFormat: "json" }, + }); + await exportSkfProject(input([original])); + const changed = { ...original, cadDisplayEdges: [{ points: [0, 0, 0, 2, 2, 2] }], importedMesh: { ...original.importedMesh!, normals: original.importedMesh!.positions } }; + const history = [editorHistoryEntry([original], []), editorHistoryEntry([changed], [])]; + const restored = await importSkfProject(await exportSkfProject(input([changed], { history, historyIndex: 1 }))); + expect(restored.history[0].shapes[0].cadDisplayEdges).toEqual(original.cadDisplayEdges); + expect(restored.shapes[0].cadDisplayEdges).toEqual(changed.cadDisplayEdges); + expect(restored.history[0].shapes[0].importedMesh?.normals).toBeUndefined(); + expect(restored.shapes[0].importedMesh?.normals).toEqual(changed.importedMesh.normals); + }); + + it("rejects missing and corrupt display-edge resources", async () => { + const bytes = await exportSkfProject(input([shape("box", "bad-edges", { cadDisplayEdges: [{ points: [0, 0, 0] }] })])); + await expect(importSkfProject(mutateProject(bytes, (document) => { + document.states[0].nodes[0].cadDisplayEdgesAssetId = "missing"; + }))).rejects.toThrow(/display-edge asset/); + const { files, document } = packageDocument(bytes); + const edge = document.assets.find((asset) => asset.kind === "display-edges")!; + files[edge.path] = strToU8('[{"points":["invalid",0,0]}]'); + edge.byteLength = files[edge.path].length; + edge.sha256 = await projectAssets.sha256Hex(files[edge.path]); + files["project.json"] = strToU8(JSON.stringify(document)); + await expect(importSkfProject(zipSync(files))).rejects.toThrow(/display-edge coordinates/); + }); it("round-trips every supported native shape kind and editable properties", async () => { const nativeKinds: ShapeKind[] = [ @@ -180,7 +269,8 @@ describe("SketchForge .skf project packages", () => { }); it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => { - const solid = shape("box", "solid", { x: 0 }); + const cadDisplayEdges = [{ points: [0, 0, 0, 1, 2, 3] }]; + const solid = shape("box", "solid", { x: 0, cadDisplayEdges }); const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 }); const group = shape("mesh", "group", { name: "Intersection", @@ -199,12 +289,13 @@ describe("SketchForge .skf project packages", () => { sourceFormat: "json", }, cadBrep: "BREP exact payload", + cadDisplayEdges, edgeTreatments: [{ kind: "fillet", amount: 1.25, edgeCount: 3 }], edgeTreatmentHistory: [{ id: "edge-history-1", createdAt: 1_700_000_050_000, feature: { kind: "fillet", amount: 1.25, edgeCount: 3 }, - before: shape("box", "group", { width: 30, depth: 30, height: 20 }), + before: shape("box", "group", { width: 30, depth: 30, height: 20, cadDisplayEdges }), }], }); const before = editorHistoryEntry([solid, hole], ["solid", "hole"]); @@ -215,6 +306,7 @@ describe("SketchForge .skf project packages", () => { expect(document.groups[0].operation).toBe("boolean-intersection"); expect(document.features.some((feature) => feature.type === "fillet")).toBe(true); expect(document.exactCad).toHaveLength(1); + expect(document.assets.filter((asset) => asset.kind === "display-edges")).toHaveLength(1); const restored = await importSkfProject(exported); expect(restored.history).toHaveLength(2);