fix: reduce autosave work and batch keyboard movement history

This commit is contained in:
Formsmith746
2026-09-18 12:12:41 +03:00
parent 6b3e0e642d
commit e9cb8e8681
12 changed files with 770 additions and 120 deletions
+26
View File
@@ -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],
+153
View File
@@ -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> = {}): 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 });
});
});
+95 -3
View File
@@ -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);