[K4][6][8] Aktionen erzeugen Ops direkt statt Projekt → Projekt + diffToOps

- Store `applyChange(ops | (p) => ops, coalesceKey?)` geht ohne Differenz an den Kern;
  `setProject` erkennt `opsMutation`-Funktionen und nimmt deren Ops.
- Umgestellt: Griffe (moveGripOf/moveElementByOf/moveEdgeOf, Decke/Dach/Treppe/Raum),
  Objekt-Info (updateWall/-Ceiling/-Opening/-Roof/-Stair/-Room/-Drawing2D, Farbe, Füllung,
  Vorder-/Hintergrund, Resize, Wand-/Deckendicke, Polylinien-Punkte), Auswahl verschieben/
  kopieren/drehen (`transformOps`), Löschen der Auswahl (+ Schnittlinien, eine Gruppe),
  Ebenen/Sichtbarkeit/Kategorien, Text-Tippen, Panel-Zeichnungs-Eigenschaften und die
  Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle
  2D-Zeichenbefehle, move/copy/mirror/rotate/scale/array). Gruppen-Zuordnung beim Zeichnen
  in einer Gruppe über `activeGroupOps`.
- Griff-Zug mit mitgeführten Ecken: je Mausschritt eine Gruppe mit Schlüssel → ein
  Undo-Schritt für den ganzen Zug; aufgeschobene Commits beim Loslassen als Gruppe.
- Tests: Store-Zufallsfolgen (Leseansicht = Kern, Aktion = applyOps(vorher, ihre Ops),
  Undo bis Anfang/Redo bis Ende exakt), activeGroupOps = addNewElementsToActiveGroup;
  beim Umbau zusätzlich 2400 Zufallsschritte gegen die alte setProject-Fassung und 400
  Transformationen gegen das alte commitTransform geprüft (gleiches Projekt bis auf
  erzeugte ids und fehlend/leere Listen).
- Messung (vitest, 3000 Wände): Griff ziehen 3,3 → 0,2–0,3 ms/Schritt, Auswahl (300 Wände)
  verschieben 30 → 6–7 ms, Eigenschaft tippen 3 → 0,03 ms.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 22:02:40 +00:00
1 parent b33f336bf0
commit a24cfbb3d7
49 files changed
+1001 -750

No files matched your search

+49 -32
View File
@@ -156,7 +156,8 @@ import { useGripEditing } from "./state/useGripEditing";
import { usePanelHostBase } from "./state/usePanelHostBase";
import { useDockDragState } from "./state/useDockDragState";
import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers";
import { addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
import { isOpsMutation, opsMutation, removeItems } from "./core";
import type { GroupMembership, MemberKind } from "./state/groupActions";
import { isLocked, setLockedForMembers } from "./state/objectLock";
import { useProjectFileActions } from "./state/useProjectFileActions";
@@ -352,6 +353,7 @@ export default function App() {
// Endlosschleife). Actions leben ebenfalls im Zustand und sind referenzstabil.
const project = useStore((s) => s.project);
const setProject = useStore((s) => s.setProject);
const groupChanges = useStore((s) => s.groupChanges);
const notify = useStore((s) => s.notify);
const undo = useStore((s) => s.undo);
const redo = useStore((s) => s.redo);
@@ -937,10 +939,21 @@ export default function App() {
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe") — s.
// state/groupActions.ts::addNewElementsToActiveGroup (Diff vor/nach
// Commit über alle Elementarten, additiv zur eigentlichen Mutation).
commit: (mutate) =>
cmdLatest.current.setProject((p) =>
addNewElementsToActiveGroup(p, mutate(p), cmdLatest.current.groupPath),
),
// [K4] S3: Befehle mit mitgeführten Ops (`opsMutation`) gehen ohne Projekt-Differenz an den
// Kern; die Gruppen-Zuordnung kommt dann als weitere Ops dazu (`activeGroupOps`).
commit: (mutate) => {
const groupPath = cmdLatest.current.groupPath;
if (isOpsMutation(mutate)) {
cmdLatest.current.setProject(
opsMutation((p) => {
const ops = mutate.toOps(p);
return [...ops, ...activeGroupOps(p, ops, groupPath)];
}),
);
} else {
cmdLatest.current.setProject((p) => addNewElementsToActiveGroup(p, mutate(p), groupPath));
}
},
isFloor: () => cmdLatest.current.activeLevel.kind === "floor",
// Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren
// (kein Lookup nötig — der Commit hat es bereits angehängt, s. engine.ts
@@ -1223,6 +1236,21 @@ export default function App() {
// Löscht die AKTUELLE Auswahl (alle Kanäle) — geteilte Logik zwischen dem
// Entf-Tastatur-Handler und dem Menüpunkt „Bearbeiten > Löschen".
const deleteSelection = () => {
// Ein Undo-Schritt für alles (Schnittlinien + Elemente), [K4] S3.
groupChanges(() => deleteSelectionChanges());
setSelectedDrawingIds([]);
setSelectedWallIds([]);
setSelectedCeilingIds([]);
setSelectedOpeningIds([]);
setSelectedStairIds([]);
setSelectedRoomIds([]);
setSelectedExtrudedSolidIds([]);
setSelectedColumnIds([]);
setSelectedRoofIds([]);
setSelectedContextObjectIds([]);
setSelectedSectionLineIds([]);
};
const deleteSelectionChanges = () => {
// Schnittlinie(n): Entf löscht NUR ihre Linie (linePoints), die Ebene
// bleibt — ADDITIV zu den übrigen Kanälen unten (nicht mehr exklusiv:
// seit Cmd/Ctrl+A Schnittlinien zusammen mit Wänden/etc. mitselektiert,
@@ -1246,33 +1274,21 @@ export default function App() {
const colids = new Set(notLocked("columnIds", selectedColumnIds));
const rfids = new Set(notLocked("roofIds", selectedRoofIds));
const ctxids = new Set(selectedContextObjectIds);
setProject((p) => ({
...p,
drawings2d: p.drawings2d.filter((d) => !dids.has(d.id)),
walls: p.walls.filter((w) => !wids.has(w.id)),
ceilings: (p.ceilings ?? []).filter((c) => !cids.has(c.id)),
roofs: (p.roofs ?? []).filter((r) => !rfids.has(r.id)),
stairs: (p.stairs ?? []).filter((s) => !stids.has(s.id)),
rooms: (p.rooms ?? []).filter((r) => !rmids.has(r.id)),
extrudedSolids: (p.extrudedSolids ?? []).filter((s) => !exids.has(s.id)),
columns: (p.columns ?? []).filter((c) => !colids.has(c.id)),
// Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt.
openings: (p.openings ?? []).filter(
(o) => !oids.has(o.id) && !wids.has(o.hostWallId),
),
context: (p.context ?? []).filter((o) => !ctxids.has(o.id)),
}));
setSelectedDrawingIds([]);
setSelectedWallIds([]);
setSelectedCeilingIds([]);
setSelectedOpeningIds([]);
setSelectedStairIds([]);
setSelectedRoomIds([]);
setSelectedExtrudedSolidIds([]);
setSelectedColumnIds([]);
setSelectedRoofIds([]);
setSelectedContextObjectIds([]);
setSelectedSectionLineIds([]);
setProject(
opsMutation((p) => [
...removeItems(p, "drawings2d", dids),
...removeItems(p, "walls", wids),
...removeItems(p, "ceilings", cids),
...removeItems(p, "roofs", rfids),
...removeItems(p, "stairs", stids),
...removeItems(p, "rooms", rmids),
...removeItems(p, "extrudedSolids", exids),
...removeItems(p, "columns", colids),
// Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt.
...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId)),
...removeItems(p, "context", ctxids),
]),
);
};
// Tastatur im Auswahl-Werkzeug: Ctrl/Cmd+A = alles wählen, Entf/Backspace =
@@ -1823,6 +1839,7 @@ export default function App() {
moveRoomBy,
moveCeilingBy,
moveElementByOf,
groupChanges,
});
// Nummern-Shortcuts für Zeichenwerkzeuge (Vectorworks-Stil): 1 Text, 2 Linie,
+10 -9
View File
@@ -42,11 +42,12 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
@@ -202,8 +203,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft {
return { preview: [{ kind: "line", a, b }], vertices: [a] };
}
function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): Project {
if (r < EPS) return p;
function appendArc(center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -211,7 +212,7 @@ function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "arc", center, r, a0, a1 },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (method: ArcMethod): [CommandState, CommandResult] => [
@@ -268,7 +269,7 @@ export const arcCommand: Command = {
if (!arc) return [s, { draft: null }];
return [
idle("ser")[0],
{ draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
}
if (input.kind !== "point") return [s, { draft: null }];
@@ -291,7 +292,7 @@ export const arcCommand: Command = {
const { center, r, a0 } = s;
return [
idle("center")[0],
{ draft: null, done: true, commit: (p) => appendArc(p, center, r, a0, a1, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendArc(center, r, a0, a1, ctx)) },
];
}
@@ -311,7 +312,7 @@ export const arcCommand: Command = {
if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten
return [
idle("three")[0],
{ draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
}
@@ -331,7 +332,7 @@ export const arcCommand: Command = {
if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten
return [
idle("ser")[0],
{ draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) },
];
}
@@ -350,7 +351,7 @@ export const arcCommand: Command = {
if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten
return [
idle("sed")[0],
{ draft: null, done: true, commit: (p) => appendArc(p, sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendArc(sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx)) },
];
},
+2 -2
View File
@@ -23,7 +23,7 @@
// wie move/copy). Leere Auswahl → No-op.
import {
commitTransform,
transformMutation,
hasTransformSelection,
toTransformSel,
transformPreview,
@@ -200,7 +200,7 @@ export const arrayCommand: Command = {
const pts = kind === "polar" ? polarPts(base, segAngleDeg(base, target)) : [base, target];
return [
idle(kind)[0],
{ draft: null, done: true, commit: (p) => commitTransform(p, toTransformSel(sel), op, pts, "array", lastCount) },
{ draft: null, done: true, commit: transformMutation(toTransformSel(sel), op, pts, "array", lastCount) },
];
},
+6 -5
View File
@@ -17,10 +17,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
interface BezierStart extends CommandState {
phase: "start";
@@ -58,8 +59,8 @@ function bezierDraft(pts: Vec2[], rubber: Vec2[]): ToolDraft {
return { preview, vertices: pts.length > 0 ? [pts[0]] : [] };
}
function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project {
if (pts.length < 4) return p;
function appendBezier(pts: Vec2[], ctx: CommandContext): CoreOp[] {
if (pts.length < 4) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -67,7 +68,7 @@ function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "bezier", pts },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -76,7 +77,7 @@ const idle = (): [CommandState, CommandResult] => [
];
const finish = (pts: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as BezierStart,
{ draft: null, done: true, commit: (p) => appendBezier(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendBezier(pts, ctx)) },
];
export const bezierCommand: Command = {
+6 -7
View File
@@ -22,9 +22,10 @@ import type {
CommandContext,
CommandResult,
CommandState,
Project,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
@@ -51,14 +52,12 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } {
return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) };
}
function appendInstance(
p: Project,
blockDefId: string,
function appendInstance(blockDefId: string,
at: Vec2,
rotation: number,
scale: number,
ctx: CommandContext,
): Project {
): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -66,7 +65,7 @@ function appendInstance(
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "block", blockDefId, at, rotation, scale },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
/** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */
@@ -117,7 +116,7 @@ export const blockCommand: Command = {
const { rotation, scale } = rotationAndScaleFrom(at, pt);
return [
idle()[0],
{ draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, rotation, scale, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendInstance(blockDefId, at, rotation, scale, ctx)) },
];
},
+8 -8
View File
@@ -26,10 +26,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -115,9 +116,9 @@ function ceilingDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
}
/** Hängt eine Decke ans Projekt (immutabel). Entartete Umrisse werden verworfen. */
function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project {
function appendCeiling(pts: Vec2[], ctx: CommandContext): CoreOp[] {
const outline = normalizeOutline(pts);
if (!outline || ceilingArea(outline) < 1e-4) return p;
if (!outline || ceilingArea(outline) < 1e-4) return [];
const ceiling: Ceiling = {
id: uniqueId("C"),
type: "ceiling",
@@ -126,8 +127,7 @@ function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project {
outline,
wallTypeId: activeTypeId(ctx),
};
const ceilings = p.ceilings ? [...p.ceilings, ceiling] : [ceiling];
return { ...p, ceilings };
return addItems("ceilings", [ceiling]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -175,7 +175,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
];
}
return [s, { draft: ceilingDraft(s.points, s.cursor) }];
@@ -197,7 +197,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
];
}
// Null-Strecke (Klick auf denselben Punkt) ignorieren.
@@ -224,7 +224,7 @@ export const ceilingCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null } as CeilIdle,
{ draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) },
];
}
return idle();
+9 -7
View File
@@ -52,6 +52,8 @@ import type {
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
@@ -265,8 +267,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft {
return { preview: [{ kind: "line", a, b }], vertices: [a] };
}
function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): Project {
if (r < EPS) return p;
function appendCircle(center: Vec2, r: number, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -274,7 +276,7 @@ function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext):
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "circle", center, r },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (method: CircleMethod): [CommandState, CommandResult] => [
@@ -335,7 +337,7 @@ export const circleCommand: Command = {
if (input.kind === "number") r = input.value;
else r = dist(s.center, input.point);
const center = s.center;
return [idle("center")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }];
return [idle("center")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
}
if (s.method === "ttr") {
@@ -346,7 +348,7 @@ export const circleCommand: Command = {
const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null;
// Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten.
if (!center) return [s, { draft: null }];
return [idle("ttr")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }];
return [idle("ttr")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
}
if (input.kind !== "point") return [s, { draft: null }];
const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point);
@@ -387,7 +389,7 @@ export const circleCommand: Command = {
}
const center = mid(s.a, pt);
const r = dist(s.a, pt) / 2;
return [idle("twoPoint")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }];
return [idle("twoPoint")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }];
}
// threePoint
@@ -405,7 +407,7 @@ export const circleCommand: Command = {
if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten
return [
idle("threePoint")[0],
{ draft: null, done: true, commit: (p) => appendCircle(p, circ.center, circ.r, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendCircle(circ.center, circ.r, ctx)) },
];
},
+6 -7
View File
@@ -22,9 +22,10 @@ import type {
CommandResult,
CommandState,
CmdOption,
Project,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Ebene (Kategorie) für Stützen: „50" Tragwerk (Fallback: aktive). */
const COLUMN_CATEGORY = "50";
@@ -48,11 +49,9 @@ function currentProfile(): ColumnProfile {
}
/** Fügt die Stütze immutabel an `project.columns` an. */
function appendColumn(
p: Project,
position: Vec2,
function appendColumn(position: Vec2,
ctx: CommandContext,
): Project {
): CoreOp[] {
const height =
ctx.level.floorHeight != null && ctx.level.floorHeight > 0
? ctx.level.floorHeight
@@ -67,7 +66,7 @@ function appendColumn(
rotation: 0,
height,
};
return { ...p, columns: [...(p.columns ?? []), column] };
return addItems("columns", [column]);
}
interface ColState extends CommandState {
@@ -135,7 +134,7 @@ export const columnCommand: Command = {
if (input.kind === "point") {
return [
{ phase: "done", lastPoint: null } as ColState,
{ draft: null, done: true, commit: (p) => appendColumn(p, input.point, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendColumn(input.point, ctx)) },
];
}
return [s, { draft: null }];
+3 -3
View File
@@ -5,11 +5,11 @@
// → weitere Zielpunkte = weitere Kopien (Basispunkt bleibt), bis Esc/Enter.
//
// Die Auswahl kommt vorab über ctx.selection. Leere Auswahl → No-op + Hinweis.
// Der Commit nutzt `commitTransform` (op:"move", mode:"copy") — eine Kopie der
// Der Commit nutzt `transformMutation` (op:"move", mode:"copy") — eine Kopie der
// Auswahl an die Endlage, Original unverändert; neue IDs via uniqueId (dort).
import {
commitTransform,
transformMutation,
hasTransformSelection,
toTransformSel,
transformPreview,
@@ -136,7 +136,7 @@ export const copyCommand: Command = {
next,
{
draft: copyDraft(ctx.project, sel, base, pt),
commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "copy", 1),
commit: transformMutation(toTransformSel(sel), "move", [base, pt], "copy", 1),
},
];
},
+5 -4
View File
@@ -14,10 +14,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (drawing2d.ts)
const DEFAULT_LABEL = "A";
@@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft {
return { preview, vertices: [at] };
}
function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project {
function appendDetailRef(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -47,7 +48,7 @@ function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "detailref", at, label: DEFAULT_LABEL },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -68,7 +69,7 @@ export const detailrefCommand: Command = {
if (input.kind !== "point") return [s, { draft: null }];
return [
{ phase: "point", lastPoint: null } as DetailRefIdle,
{ draft: null, done: true, commit: (p) => appendDetailRef(p, input.point, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendDetailRef(input.point, ctx)) },
];
},
+7 -10
View File
@@ -36,6 +36,8 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation, patchItem } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
@@ -151,16 +153,11 @@ function offsetDraft(pts: Vec2[], offset: number, at: Vec2 | null): ToolDraft {
}
/** Committet eine Kette: neu anhängen (editId null) ODER dasselbe Element ersetzen. */
function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): Project {
function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): CoreOp[] {
const cleaned = pts.filter((pt, i) => i === 0 || dist(pts[i - 1], pt) >= EPS);
if (cleaned.length < 2) return p; // zu wenig gültige Punkte → nichts committen/ändern
if (cleaned.length < 2) return []; // zu wenig gültige Punkte → nichts committen/ändern
if (editId) {
return {
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === editId ? { ...d, geom: { shape: "dimension", pts: cleaned, offset } } : d,
),
};
return patchItem(p, "drawings2d", editId, (d): Drawing2D => ({ ...d, geom: { shape: "dimension", pts: cleaned, offset } }));
}
const d: Drawing2D = {
id: uniqueId("dr2d"),
@@ -169,7 +166,7 @@ function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | n
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "dimension", pts: cleaned, offset },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -237,7 +234,7 @@ export const dimensionCommand: Command = {
const editId = s.editId;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: (p) => commitChain(p, pts, offset, editId, ctx) },
{ draft: null, done: true, commit: opsMutation((p) => commitChain(p, pts, offset, editId, ctx)) },
];
},
+8 -9
View File
@@ -30,11 +30,12 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
@@ -138,15 +139,13 @@ function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDra
// ── Commit ───────────────────────────────────────────────────────────────────
function appendEllipse(
p: Project,
center: Vec2,
function appendEllipse(center: Vec2,
rx: number,
ry: number,
rotation: number,
ctx: CommandContext,
): Project {
if (rx < EPS || ry < EPS) return p;
): CoreOp[] {
if (rx < EPS || ry < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -154,7 +153,7 @@ function appendEllipse(
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "ellipse", center, rx, ry, rotation },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (method: EllipseMethod): [CommandState, CommandResult] => [
@@ -201,7 +200,7 @@ export const ellipseCommand: Command = {
return [ns, { draft: boxDraft(pt, pt) }];
}
const { center, rx, ry } = ellipseFromCorners(s.p0, pt);
return [idle("box")[0], { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, 0, ctx) }];
return [idle("box")[0], { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, 0, ctx)) }];
}
// axis
@@ -221,7 +220,7 @@ export const ellipseCommand: Command = {
const rotation = angleOf(center, major);
return [
idle("axis")[0],
{ draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, rotation, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, rotation, ctx)) },
];
},
+5 -7
View File
@@ -25,6 +25,8 @@ import type {
Project,
Vec2,
} from "../types";
import { addItems, opsMutation, removeItems } from "../../core";
import type { CoreOp } from "../../core";
const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Profil-Wahl
@@ -113,7 +115,7 @@ function appendExtrudedSolid(
taper: number,
sourceId: string,
ctx: CommandContext,
): Project {
): CoreOp[] {
const solid: ExtrudedSolid = {
id: uniqueId("extrude"),
type: "extrudedSolid",
@@ -123,11 +125,7 @@ function appendExtrudedSolid(
circle: profile.circle,
...(taper > 0 ? { taper } : {}),
};
return {
...p,
drawings2d: p.drawings2d.filter((d) => d.id !== sourceId),
extrudedSolids: [...(p.extrudedSolids ?? []), solid],
};
return [...removeItems(p, "drawings2d", [sourceId]), ...addItems("extrudedSolids", [solid])];
}
// ── Zustand ───────────────────────────────────────────────────────────────────
@@ -177,7 +175,7 @@ const commitTaper = (
ctx: CommandContext,
): [CommandState, CommandResult] => [
{ phase: "done", lastPoint: null } as ExDone,
{ draft: null, done: true, commit: (p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx) },
{ draft: null, done: true, commit: opsMutation((p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx)) },
];
export const extrudeCommand: Command = {
+5 -4
View File
@@ -14,11 +14,12 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
type KoteKind = "okFertig" | "ukFertig" | "okRoh" | "ukRoh";
const KIND_ORDER: KoteKind[] = ["okFertig", "ukFertig", "okRoh", "ukRoh"];
@@ -62,7 +63,7 @@ function valueDraft(at: Vec2, kind: KoteKind): ToolDraft {
return { preview, vertices: [at] };
}
function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): Project {
function appendKote(at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -70,7 +71,7 @@ function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: Co
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "kote", at, value, kind, rotation: 0 },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -101,7 +102,7 @@ export const koteCommand: Command = {
const { at, kind } = s;
return [
{ phase: "point", lastPoint: null },
{ draft: null, done: true, commit: (p) => appendKote(p, at, input.value, kind, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendKote(at, input.value, kind, ctx)) },
];
},
+6 -7
View File
@@ -22,11 +22,12 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const DEFAULT_TEXT_HEIGHT_M = 0.25;
const MAX_BENDS = 4;
@@ -53,14 +54,12 @@ interface LeaderAnchor extends CommandState {
}
type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor;
function appendLeaderText(
p: Project,
id: string,
function appendLeaderText(id: string,
at: Vec2,
target: Vec2,
bends: Vec2[],
ctx: CommandContext,
): Project {
): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
@@ -76,7 +75,7 @@ function appendLeaderText(
...(bends.length > 0 ? { leaderBendPoints: bends } : {}),
},
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -143,7 +142,7 @@ export const leaderCommand: Command = {
{
draft: null,
done: true,
commit: (p) => appendLeaderText(p, id, pt, target, bends, ctx),
commit: opsMutation(() => appendLeaderText(id, pt, target, bends, ctx)),
focusDrawingId: id,
},
];
+5 -3
View File
@@ -36,6 +36,8 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -81,7 +83,7 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
}
/** Hängt eine 2D-Linie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */
function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: CommandContext) {
function appendLine(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -89,7 +91,7 @@ function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: Comman
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "line", a, b },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
export const lineCommand: Command = {
@@ -117,7 +119,7 @@ export const lineCommand: Command = {
}
const a = s.a;
const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt };
return [next, { draft: lineDraft(pt, pt), commit: (p) => appendLine(p, a, pt, ctx) }];
return [next, { draft: lineDraft(pt, pt), commit: opsMutation(() => appendLine(a, pt, ctx)) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
+3 -3
View File
@@ -7,12 +7,12 @@
// wie Move/Copy). Ist sie leer, ist nichts zu spiegeln: kurzer No-op mit Hinweis
// („Nichts gewählt") und Beenden.
//
// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"mirror",
// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"mirror",
// mode:"copy") — er spiegelt Wände UND alle 2D-Formen immutabel an der Achse und
// hängt das Spiegelbild als KOPIE an (das Original bleibt stehen). Das ist das
// klassische Mirror „Kopie spiegeln" (Rhino/Vectorworks-Default).
import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform";
import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform";
import { transformPreview } from "../../tools/transform";
import type {
Command,
@@ -132,7 +132,7 @@ export const mirrorCommand: Command = {
{
draft: null,
done: true,
commit: (p) => commitTransform(p, toTransformSel(sel), "mirror", [a, pt], "copy", 1),
commit: transformMutation(toTransformSel(sel), "mirror", [a, pt], "copy", 1),
},
];
},
+3 -3
View File
@@ -9,11 +9,11 @@
// einen zweiten, divergierenden Pick-Pfad für die Objektwahl aufzumachen; die
// Selektion läuft schon sauber über die Plan-Ansicht/Store).
//
// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"move",
// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"move",
// mode:"move") statt eine zweite Verschiebe-Logik zu duplizieren — er bewegt
// Wände UND alle 2D-Formen immutabel an die Endlage.
import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform";
import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform";
import { transformPreview } from "../../tools/transform";
import type {
Command,
@@ -145,7 +145,7 @@ export const moveCommand: Command = {
{
draft: null,
done: true,
commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "move", 1),
commit: transformMutation(toTransformSel(sel), "move", [base, pt], "move", 1),
},
];
},
+7 -6
View File
@@ -27,10 +27,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -76,8 +77,8 @@ function multilinePairs(a: Vec2, b: Vec2, spacing: number, sign: number, count:
return out;
}
function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): Project {
if (segLen(a, b) < EPS) return p;
function appendMultiline(a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): CoreOp[] {
if (segLen(a, b) < EPS) return [];
const pairs = multilinePairs(a, b, spacing, sign, count);
const copies: Drawing2D[] = pairs.map(([pa, pb]) => ({
id: uniqueId("dr2d"),
@@ -86,7 +87,7 @@ function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: nu
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "line", a: pa, b: pb },
}));
return { ...p, drawings2d: [...p.drawings2d, ...copies] };
return addItems("drawings2d", copies);
}
const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.multiline.count" };
@@ -169,7 +170,7 @@ export const multilineCommand: Command = {
const { a, b } = s;
return [
idle()[0],
{ draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) },
];
}
if (input.kind === "point") {
@@ -177,7 +178,7 @@ export const multilineCommand: Command = {
const { a, b } = s;
return [
idle()[0],
{ draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) },
];
}
return [s, { draft: null }];
+7 -5
View File
@@ -29,6 +29,8 @@ import type {
Project,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl
@@ -183,11 +185,11 @@ function offsetDraftShapes(curve: Curve, d: number): DraftShape[] {
return [{ kind: "poly", pts: tess, closed: curve.closed }];
}
function appendOffset(p: Project, src: Drawing2D, d: number): Project {
function appendOffset(src: Drawing2D, d: number): CoreOp[] {
const geom = offsetGeom(src, d);
if (!geom) return p;
if (!geom) return [];
const copy: Drawing2D = { ...src, id: uniqueId("dr2d"), geom };
return { ...p, drawings2d: [...p.drawings2d, copy] };
return addItems("drawings2d", [copy]);
}
// ── Zustand ───────────────────────────────────────────────────────────────────
@@ -316,7 +318,7 @@ function offsetSideInput(
const d = sign * mag;
return [
{ phase: "done", lastPoint: null } as OffDone,
{ draft: null, done: true, commit: (p) => appendOffset(p, src, d) },
{ draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) },
];
}
@@ -327,7 +329,7 @@ function offsetSideInput(
const d = sign * lastDistance;
return [
{ phase: "done", lastPoint: null } as OffDone,
{ draft: null, done: true, commit: (p) => appendOffset(p, src, d) },
{ draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) },
];
}
+6 -6
View File
@@ -22,10 +22,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Ebene (Kategorie) für Öffnungen: „21" Türen/Fenster (Fallback: aktive). */
const OPENING_CATEGORY = "21";
@@ -183,7 +184,7 @@ function posDraft(s: OpPos): ToolDraft {
}
/** Hängt eine Öffnung ans Projekt (immutabel). */
function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project {
function appendOpening(s: OpPos, ctx: CommandContext): CoreOp[] {
const len = Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y);
const width = Math.max(0.1, Math.min(s.width, len));
const position = Math.max(0, Math.min(s.posAlong, Math.max(0, len - width)));
@@ -208,8 +209,7 @@ function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project {
? { hinge: s.hinge, swing: s.side, openingDir: s.dir, swingAngle: s.swingAngle }
: {}),
};
const openings = p.openings ? [...p.openings, opening] : [opening];
return { ...p, openings };
return addItems("openings", [opening]);
}
const idle = (from?: OpState): [CommandState, CommandResult] => [
@@ -307,7 +307,7 @@ export const openingCommand: Command = {
const ns: OpPos = { ...s, posAlong: proj.t, cursor: pt };
return [
idle(s)[0],
{ draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) },
];
},
@@ -325,7 +325,7 @@ export const openingCommand: Command = {
const ns = s;
return [
idle(s)[0],
{ draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) },
];
}
return idle(s);
+5 -4
View File
@@ -11,10 +11,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (drawing2d.ts)
const PREVIEW_CROSS = 0.12;
@@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft {
return { preview, vertices: [at] };
}
function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project {
function appendPointMarker(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -47,7 +48,7 @@ function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "pointmarker", at },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -68,7 +69,7 @@ export const pointmarkerCommand: Command = {
if (input.kind !== "point") return [s, { draft: null }];
return [
{ phase: "point", lastPoint: null } as PointMarkerIdle,
{ draft: null, done: true, commit: (p) => appendPointMarker(p, input.point, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendPointMarker(input.point, ctx)) },
];
},
+10 -9
View File
@@ -35,11 +35,12 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const MIN_SIDES = 3;
@@ -148,8 +149,8 @@ function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) };
}
function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): Project {
if (r < EPS) return p;
function appendPolygon(center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): CoreOp[] {
if (r < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -157,11 +158,11 @@ function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ct
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project {
if (dist(a, b) < EPS) return p;
function appendPolygonFromEdge(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
if (dist(a, b) < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -169,7 +170,7 @@ function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -247,7 +248,7 @@ export const polygonCommand: Command = {
}
const a = s.a;
const b = input.point;
return [idle()[0], { draft: null, done: true, commit: (p) => appendPolygonFromEdge(p, a, b, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendPolygonFromEdge(a, b, ctx)) }];
}
// phase "radius"
@@ -266,7 +267,7 @@ export const polygonCommand: Command = {
const center = s.center;
return [
idle()[0],
{ draft: null, done: true, commit: (p) => appendPolygon(p, center, r, dir, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendPolygon(center, r, dir, ctx)) },
];
},
+8 -9
View File
@@ -29,10 +29,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -200,13 +201,11 @@ function polyDraft(
}
/** Hängt eine 2D-Polylinie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */
function appendPolyline(
p: Project,
pts: Vec2[],
function appendPolyline(pts: Vec2[],
bulges: number[],
closed: boolean,
ctx: CommandContext,
): Project {
): CoreOp[] {
// `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner
// Geradenzug bleibt damit bitgleich zu vorher (additives Feld).
const hasArc = bulges.some((b) => Math.abs(b) > EPS);
@@ -219,7 +218,7 @@ function appendPolyline(
? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) }
: { shape: "polyline", pts, closed },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
/** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */
@@ -312,7 +311,7 @@ export const polylineCommand: Command = {
const bl = [...s.bulges, closingBulge(s)];
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) },
];
}
return [
@@ -371,7 +370,7 @@ export const polylineCommand: Command = {
const bl = [...s.bulges, newBulge];
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) },
];
}
const points = [...s.points, pt];
@@ -411,7 +410,7 @@ export const polylineCommand: Command = {
const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges;
return [
{ phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle,
{ draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, close, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, close, ctx)) },
];
}
return idle(s.closed, s.arc, s.tangent);
+5 -4
View File
@@ -14,10 +14,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -67,7 +68,7 @@ function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project {
function appendRay(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -75,7 +76,7 @@ function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "ray", a, b },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
export const rayCommand: Command = {
@@ -100,7 +101,7 @@ export const rayCommand: Command = {
const a = s.a;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: (p) => appendRay(p, a, pt, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRay(a, pt, ctx)) },
];
},
+18 -17
View File
@@ -41,11 +41,12 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import type { TranslationKey } from "../../i18n";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
@@ -310,8 +311,8 @@ function riseDraft(a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft {
// ── Commit ───────────────────────────────────────────────────────────────────
/** Achsparalleles Rechteck als `shape:"rect"` (geschlossen behandelt). */
function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Project {
if (max.x - min.x < EPS || max.y - min.y < EPS) return p; // Null-Rechteck
function appendRect(min: Vec2, max: Vec2, ctx: CommandContext): CoreOp[] {
if (max.x - min.x < EPS || max.y - min.y < EPS) return []; // Null-Rechteck
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -319,7 +320,7 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "rect", min, max },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
/**
@@ -327,11 +328,11 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj
* — `shape:"rect"` kann nur achsparallel, deshalb hier ein Ring aus vier Ecken.
* Downstream (Füllung/Offset) behandelt einen geschlossenen Polygonzug als Ring.
*/
function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project {
function appendRotated(pts: Vec2[], ctx: CommandContext): CoreOp[] {
// Fläche prüfen: entartete Rechtecke verwerfen.
const w = segLen(pts[0], pts[1]);
const h = segLen(pts[1], pts[2]);
if (w < EPS || h < EPS) return p;
if (w < EPS || h < EPS) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -339,7 +340,7 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts, closed: true },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
/**
@@ -350,9 +351,9 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project {
* passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten
* Rechteck).
*/
function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Project {
function appendRectRounded(corners: Vec2[], ctx: CommandContext): CoreOp[] {
const rr = roundedRectPts(corners, lastRadius);
if (!rr) return p;
if (!rr) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -360,7 +361,7 @@ function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Pr
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (method: RectMethod): [CommandState, CommandResult] => [
@@ -436,14 +437,14 @@ export const rectCommand: Command = {
{
draft: null,
done: true,
commit: (p) => {
commit: opsMutation(() => {
const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt);
if (lastRadius >= EPS) {
const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return appendRectRounded(p, corners, ctx);
return appendRectRounded(corners, ctx);
}
return appendRect(p, g.min, g.max, ctx);
},
return appendRect(g.min, g.max, ctx);
}),
},
];
}
@@ -456,10 +457,10 @@ export const rectCommand: Command = {
{
draft: null,
done: true,
commit: (p) => {
commit: opsMutation(() => {
const corners = rotatedCorners(a, b, pt);
return lastRadius >= EPS ? appendRectRounded(p, corners, ctx) : appendRotated(p, corners, ctx);
},
return lastRadius >= EPS ? appendRectRounded(corners, ctx) : appendRotated(corners, ctx);
}),
},
];
},
+8 -7
View File
@@ -19,10 +19,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug
@@ -62,9 +63,9 @@ function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: CommandContext): Project {
function appendRevcloud(points: Vec2[], closed: boolean, ctx: CommandContext): CoreOp[] {
const expanded = revisionCloudPts(points, closed, lastArcSize);
if (!expanded) return p;
if (!expanded) return [];
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -72,7 +73,7 @@ function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: Comman
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -105,7 +106,7 @@ export const revcloudCommand: Command = {
}
if (input.id === "close" && s.phase === "next" && s.points.length >= 3) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }];
}
return [s, { draft: null }];
}
@@ -123,7 +124,7 @@ export const revcloudCommand: Command = {
// Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring).
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }];
}
const points = [...s.points, pt];
const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
@@ -142,7 +143,7 @@ export const revcloudCommand: Command = {
const s = state as RevcloudState;
if (s.phase === "next" && s.points.length >= 2) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, false, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, false, ctx)) }];
}
return idle();
},
+6 -6
View File
@@ -20,10 +20,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Ebene (Kategorie) für Dächer („31 Dächer"). */
const ROOF_CATEGORY = "31";
@@ -93,10 +94,10 @@ function roofDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
}
/** Hängt ein Dach ans Projekt (immutabel). Entartete Rechtecke werden verworfen. */
function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): Project {
function appendRoof(a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): CoreOp[] {
const w = Math.abs(b.x - a.x);
const d = Math.abs(b.y - a.y);
if (w < 0.1 || d < 0.1) return p;
if (w < 0.1 || d < 0.1) return [];
const roof: Roof = {
id: uniqueId("RF"),
type: "roof",
@@ -111,8 +112,7 @@ function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: Command
ridgeAxis: w >= d ? "x" : "y",
thickness: 0.2,
};
const roofs = p.roofs ? [...p.roofs, roof] : [roof];
return { ...p, roofs };
return addItems("roofs", [roof]);
}
const idle = (shape: RoofShape = "sattel"): [CommandState, CommandResult] => [
@@ -157,7 +157,7 @@ export const roofCommand: Command = {
const shape = s.shape;
return [
{ phase: "start", shape, lastPoint: null } as RoofIdle,
{ draft: null, done: true, commit: (p) => appendRoof(p, a, b, shape, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRoof(a, b, shape, ctx)) },
];
},
+9 -9
View File
@@ -31,10 +31,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -134,11 +135,10 @@ function defaultRoomName(ctx: CommandContext): string {
}
/** Hängt einen Raum ans Projekt (immutabel); entartete Umrisse werden verworfen. */
function appendRoom(p: Project, boundary: Vec2[], ctx: CommandContext): Project {
if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return p;
function appendRoom(boundary: Vec2[], ctx: CommandContext): CoreOp[] {
if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return [];
const room = buildRoom(ctx, boundary);
const rooms = p.rooms ? [...p.rooms, room] : [room];
return { ...p, rooms };
return addItems("rooms", [room]);
}
// ── Zustand ──────────────────────────────────────────────────────────────────
@@ -254,7 +254,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
];
}
return [s, { draft: s.phase === "draw" ? manualDraft(s.points, s.cursor) : null }];
@@ -275,7 +275,7 @@ export const roomCommand: Command = {
if (boundary && boundary.length >= 3) {
return [
{ phase: "start", lastPoint: null, mode: "inside" } as RoomIdle,
{ draft: null, done: true, commit: (p) => appendRoom(p, boundary, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRoom(boundary, ctx)) },
];
}
// Kein umschlossener Bereich getroffen → im Werkzeug bleiben (kein Commit).
@@ -298,7 +298,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
];
}
const last = s.points[s.points.length - 1];
@@ -329,7 +329,7 @@ export const roomCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, mode: s.mode } as RoomIdle,
{ draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) },
];
}
return idle(s.mode);
+4 -5
View File
@@ -11,11 +11,11 @@
//
// Die Auswahl kommt vorab über `ctx.selection` (erst selektieren, dann Befehl —
// wie Move/Copy/Mirror). Gedreht wird über den bestehenden, getesteten
// `commitTransform` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es
// `transformMutation` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es
// entsteht keine Kopie.
import {
commitTransform,
transformMutation,
hasTransformSelection,
toTransformSel,
transformPreview,
@@ -125,7 +125,7 @@ export const rotateCommand: Command = {
{
draft: null,
done: true,
commit: (p) => commitTransform(p, toTransformSel(sel), "rotate", pts, "move", 1),
commit: transformMutation(toTransformSel(sel), "rotate", pts, "move", 1),
},
];
}
@@ -166,8 +166,7 @@ export const rotateCommand: Command = {
{
draft: null,
done: true,
commit: (p) =>
commitTransform(p, toTransformSel(sel), "rotate", [center, ref, pt], "move", 1),
commit: transformMutation(toTransformSel(sel), "rotate", [center, ref, pt], "move", 1),
},
];
},
+3 -3
View File
@@ -15,7 +15,7 @@
// desselben Typs verändert — bewusste Grenze, s. PENDENZEN.md.
import {
commitTransform,
transformMutation,
hasTransformSelection,
toTransformSel,
transformPreview,
@@ -110,7 +110,7 @@ export const scaleCommand: Command = {
{
draft: null,
done: true,
commit: (p) => commitTransform(p, toTransformSel(sel), "scale", pts, "move", 1),
commit: transformMutation(toTransformSel(sel), "scale", pts, "move", 1),
},
];
}
@@ -145,7 +145,7 @@ export const scaleCommand: Command = {
{
draft: null,
done: true,
commit: (p) => commitTransform(p, toTransformSel(sel), "scale", [base, ref, pt], "move", 1),
commit: transformMutation(toTransformSel(sel), "scale", [base, ref, pt], "move", 1),
},
];
},
+5 -4
View File
@@ -13,10 +13,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50];
let lastLength = 1;
@@ -59,7 +60,7 @@ function pointDraft(at: Vec2): ToolDraft {
};
}
function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project {
function appendScalebar(at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -67,7 +68,7 @@ function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project {
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -96,7 +97,7 @@ export const scalebarCommand: Command = {
return [s, { draft: null }];
}
if (input.kind !== "point") return [s, { draft: null }];
return [idle()[0], { draft: null, done: true, commit: (p) => appendScalebar(p, input.point, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendScalebar(input.point, ctx)) }];
},
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }],
+7 -6
View File
@@ -25,10 +25,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug
@@ -80,7 +81,7 @@ function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode:
return draft;
}
function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): Project {
function appendSpline(pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -88,7 +89,7 @@ function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode,
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "spline", pts, closed, mode },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [
@@ -143,7 +144,7 @@ export const splineCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) },
];
}
return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }];
@@ -168,7 +169,7 @@ export const splineCommand: Command = {
const pts = s.points;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) },
];
}
const points = [...s.points, pt];
@@ -197,7 +198,7 @@ export const splineCommand: Command = {
const close = s.closed && pts.length >= 3;
return [
{ phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle,
{ draft: null, done: true, commit: (p) => appendSpline(p, pts, close, s.curveMode, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendSpline(pts, close, s.curveMode, ctx)) },
];
}
return idle(s.closed, s.curveMode);
+6 -6
View File
@@ -30,10 +30,11 @@ import type {
CommandState,
CmdOption,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Ebene (Kategorie) für Treppen: „40" Treppen (Fallback: aktive). */
const STAIR_CATEGORY = "40";
@@ -241,7 +242,7 @@ function runDraft(s: StairRun, ctx: CommandContext): ToolDraft {
}
/** Hängt eine Treppe ans Projekt (immutabel) und aktualisiert die Defaults. */
function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project {
function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] {
const stair = buildStair(s, ctx);
// Zuletzt genutzte Einstellungen für die nächste Treppe merken.
stairDefaults.shape = s.shape;
@@ -252,8 +253,7 @@ function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project {
stairDefaults.auftritt = s.auftritt;
stairDefaults.steps = s.steps;
stairDefaults.rise = s.rise;
const stairs = p.stairs ? [...p.stairs, stair] : [stair];
return { ...p, stairs };
return addItems("stairs", [stair]);
}
const idle = (from?: StairCmdState): [CommandState, CommandResult] => [
@@ -348,7 +348,7 @@ export const stairCommand: Command = {
const ns: StairRun = { ...s, cursor: pt };
return [
idle(s)[0],
{ draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) },
];
},
@@ -365,7 +365,7 @@ export const stairCommand: Command = {
const ns = s;
return [
idle(s)[0],
{ draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) },
];
}
return idle(s);
+6 -4
View File
@@ -10,7 +10,9 @@
import type { Drawing2D } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type { Command, CommandContext, CommandResult, CommandState, Project, Vec2 } from "../types";
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Schrifthöhe eines frei platzierten Texts in Modell-Metern. */
const DEFAULT_TEXT_HEIGHT_M = 0.25;
@@ -20,7 +22,7 @@ interface TextIdle extends CommandState {
}
type TextState = TextIdle;
function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext): Project {
function appendEmptyText(id: string, at: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
@@ -28,7 +30,7 @@ function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext):
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0 },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -54,7 +56,7 @@ export const textCommand: Command = {
{
draft: null,
done: true,
commit: (p) => appendEmptyText(p, id, at, ctx),
commit: opsMutation(() => appendEmptyText(id, at, ctx)),
focusDrawingId: id,
},
];
+5 -4
View File
@@ -27,9 +27,10 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
/** Default-Schrifthöhe einer Textspalte in Modell-Metern (= Baseline-Versatz vom Rahmen-Top). */
const DEFAULT_TEXT_HEIGHT_M = 0.25;
@@ -84,7 +85,7 @@ function frameDraft(a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: V
};
}
function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx: CommandContext): Project {
function appendEmptyTextbox(id: string, at: Vec2, width: number, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
@@ -92,7 +93,7 @@ function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, width },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -123,7 +124,7 @@ export const textboxCommand: Command = {
{
draft: null,
done: true,
commit: (p) => appendEmptyTextbox(p, id, at, width, ctx),
commit: opsMutation(() => appendEmptyTextbox(id, at, width, ctx)),
focusDrawingId: id,
focusMinHeightM: heightM,
},
+5 -4
View File
@@ -15,10 +15,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -59,7 +60,7 @@ function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandContext): Project {
function appendEmptyTextPath(id: string, pts: Vec2[], ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id,
type: "drawing2d",
@@ -67,7 +68,7 @@ function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandCo
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -77,7 +78,7 @@ const idle = (): [CommandState, CommandResult] => [
function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult {
const id = uniqueId("dr2d");
return { draft: null, done: true, commit: (p) => appendEmptyTextPath(p, id, pts, ctx), focusDrawingId: id };
return { draft: null, done: true, commit: opsMutation(() => appendEmptyTextPath(id, pts, ctx)), focusDrawingId: id };
}
export const textpathCommand: Command = {
+12 -10
View File
@@ -31,6 +31,8 @@ import type {
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -109,7 +111,7 @@ function wallTypeForThickness(
p: Project,
base: WallType,
thickness: number,
): { project: Project; wallTypeId: string } {
): { ops: CoreOp[]; wallTypeId: string } {
const componentId = base.layers[0].componentId;
const near = (a: number, b: number) => Math.abs(a - b) < 1e-4;
const existing = p.wallTypes.find(
@@ -118,13 +120,13 @@ function wallTypeForThickness(
t.layers[0].componentId === componentId &&
near(t.layers[0].thickness, thickness),
);
if (existing) return { project: p, wallTypeId: existing.id };
if (existing) return { ops: [], wallTypeId: existing.id };
const nt: WallType = {
id: uniqueId("WT"),
name: `${base.name} ${(thickness * 100).toFixed(0)} cm`,
layers: [{ componentId, thickness }],
};
return { project: { ...p, wallTypes: [...p.wallTypes, nt] }, wallTypeId: nt.id };
return { ops: addItems("wallTypes", [nt]), wallTypeId: nt.id };
}
interface WallIdle extends CommandState {
@@ -179,12 +181,12 @@ function appendWalls(
pts: Vec2[],
ctx: CommandContext,
thickOverride: number | null,
): Project {
): CoreOp[] {
const height =
ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : DEFAULT_HEIGHT;
// Dicke-Übersteuerung (nur einschichtig): passenden Wandtyp finden/erzeugen,
// damit Plan/3D — die die Dicke aus dem Wandtyp lesen — korrekt darstellen.
let project = p;
let typeOps: CoreOp[] = [];
let wallTypeId = activeWallTypeId(ctx);
const base = activeWallType(ctx);
if (
@@ -194,8 +196,8 @@ function appendWalls(
thickOverride >= MIN_THICKNESS &&
Math.abs(thickOverride - wallTypeThickness(base)) > 1e-4
) {
const r = wallTypeForThickness(project, base, thickOverride);
project = r.project;
const r = wallTypeForThickness(p, base, thickOverride);
typeOps = r.ops;
wallTypeId = r.wallTypeId;
}
const newWalls: Wall[] = [];
@@ -214,8 +216,8 @@ function appendWalls(
height,
});
}
if (newWalls.length === 0) return p;
return { ...project, walls: [...project.walls, ...newWalls] };
if (newWalls.length === 0) return [];
return [...typeOps, ...addItems("walls", newWalls)];
}
const idle = (
@@ -299,7 +301,7 @@ export const wallCommand: Command = {
const to = s.thickOverride;
return [
{ phase: "start", lastPoint: null, thickOverride: to, single: s.single } as WallIdle,
{ draft: null, done: true, commit: (p) => appendWalls(p, pts, ctx, to) },
{ draft: null, done: true, commit: opsMutation((p) => appendWalls(p, pts, ctx, to)) },
];
}
return idle(s.thickOverride, s.single);
+6 -5
View File
@@ -29,10 +29,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug
@@ -59,7 +60,7 @@ function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project {
function appendWipeout(points: Vec2[], ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -69,7 +70,7 @@ function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project
background: MASK_COLOR,
color: MASK_COLOR,
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
const idle = (): [CommandState, CommandResult] => [
@@ -100,7 +101,7 @@ export const wipeoutCommand: Command = {
// Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet).
if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }];
}
const points = [...s.points, pt];
const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
@@ -120,7 +121,7 @@ export const wipeoutCommand: Command = {
const s = state as WipeoutState;
if (s.phase === "next" && s.points.length >= 3) {
const pts = s.points;
return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }];
return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }];
}
return idle();
},
+5 -4
View File
@@ -14,10 +14,11 @@ import type {
CommandResult,
CommandState,
DraftShape,
Project,
ToolDraft,
Vec2,
} from "../types";
import { addItems, opsMutation } from "../../core";
import type { CoreOp } from "../../core";
const EPS = 1e-6;
const DEG = Math.PI / 180;
@@ -66,7 +67,7 @@ function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft {
return draft;
}
function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project {
function appendXline(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] {
const d: Drawing2D = {
id: uniqueId("dr2d"),
type: "drawing2d",
@@ -74,7 +75,7 @@ function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project
categoryCode: ctx.defaultCategoryCode,
geom: { shape: "xline", a, b },
};
return { ...p, drawings2d: [...p.drawings2d, d] };
return addItems("drawings2d", [d]);
}
export const xlineCommand: Command = {
@@ -99,7 +100,7 @@ export const xlineCommand: Command = {
const a = s.a;
return [
{ phase: "start", lastPoint: null },
{ draft: null, done: true, commit: (p) => appendXline(p, a, pt, ctx) },
{ draft: null, done: true, commit: opsMutation(() => appendXline(a, pt, ctx)) },
];
},
+57
View File
@@ -0,0 +1,57 @@
// [K4] S3 Messung: typische Hochfrequenz-Aktionen auf einem grossen Projekt (3000 Wände) über den
// Store — Griff ziehen (100 Schritte, ein Undo-Schritt), Auswahl verschieben (300 Wände, 20-mal),
// Eigenschaft tippen (100 Zeichen, ein Undo-Schritt). Werte gehen nach stderr (TODO [K4]); die
// Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis.
import { describe, expect, it } from "vitest";
import { getState } from "./appStore";
import { sampleProject } from "../model/sampleProject";
import type { Project, Wall } from "../model/types";
const st = () => getState();
function bigProject(n: number): Project {
const base = sampleProject.walls;
const walls: Wall[] = Array.from({ length: n }, (_, i) => ({
...base[i % base.length],
id: `w${i}`,
start: { x: i, y: 0 },
end: { x: i + 1, y: 0 },
}));
return { ...structuredClone(sampleProject), walls };
}
describe("Messung Store-Aktionen, 3000 Wände", () => {
it("Griff ziehen, Auswahl verschieben, Eigenschaft tippen", () => {
st().setProject(bigProject(3000));
st().clearHistory();
const depth0 = st().undoDepth;
// Griff ziehen: 100 Mausschritte, ein Undo-Schritt.
let t = performance.now();
for (let i = 0; i < 100; i++) st().moveGripOf(null, "w1500", 0, { x: 1500 + i * 0.01, y: 0.5 });
const gripMs = (performance.now() - t) / 100;
expect(st().project.walls[1500].start).toEqual({ x: 1500 + 99 * 0.01, y: 0.5 });
expect(st().undoDepth).toBe(depth0 + 1);
// Auswahl verschieben: 300 Wände, 20 Verschiebungen.
const ids = Array.from({ length: 300 }, (_, i) => `w${i * 10}`);
t = performance.now();
for (let i = 0; i < 20; i++) {
st().commitTransformOn({ wallIds: ids, drawingId: null }, "move", [{ x: 0, y: 0 }, { x: 0, y: 0.1 }], "move", 1);
}
const moveMs = (performance.now() - t) / 20;
expect(st().project.walls[10].start.y).toBeCloseTo(2, 9);
expect(st().project.walls[11].start.y).toBe(0);
// Eigenschaft tippen: 100 Tastenschritte mit coalesceKey.
t = performance.now();
for (let i = 0; i < 100; i++) st().updateWall("w42", { height: 2.5 + i / 1000 }, "typing:w42");
const typeMs = (performance.now() - t) / 100;
expect(st().project.walls[42].height).toBeCloseTo(2.599, 9);
process.stderr.write(
`3000 Wände (Store): Griff ziehen ${gripMs.toFixed(2)} ms/Schritt, Auswahl verschieben (300) ${moveMs.toFixed(2)} ms, Eigenschaft tippen ${typeMs.toFixed(2)} ms\n`,
);
expect(gripMs + moveMs + typeMs).toBeLessThan(200);
});
});
+177
View File
@@ -0,0 +1,177 @@
// [K4] S3 zweite Etappe: Store-Aktionen erzeugen Ops direkt (`applyChange`, `opsMutation`) statt
// Projekt → Projekt + `diffToOps`. Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung),
// Leseansicht und Kern-Dokument bleiben gleich — auch über Zufallsfolgen der umgestellten
// Aktionen mit Undo bis zum Anfang und Redo bis zum Ende.
import { beforeEach, describe, expect, it } from "vitest";
import { getState, setState } from "./appStore";
import { storeDocument } from "./historySlice";
import { sampleProject } from "../model/sampleProject";
import type { Drawing2D, Project, Vec2 } from "../model/types";
import { applyOps } from "../core/ops";
import { opsMutation, patchItem, removeItems } from "../core/opsBuild";
const st = () => getState();
function rng(seed: number) {
let x = seed >>> 0;
return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
}
function drawings(r: () => number): Drawing2D[] {
const v = (): Vec2 => ({ x: Math.round(r() * 100) / 10, y: Math.round(r() * 100) / 10 });
const base = { type: "drawing2d" as const, levelId: "eg", categoryCode: "20" };
const geoms = [
{ shape: "line", a: v(), b: v() },
{ shape: "polyline", pts: [v(), v(), v(), v()], closed: true, bulge: [0, 0.3, 0, 0] },
{ shape: "polyline", pts: [v(), v(), v(), v()], closed: false },
{ shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } },
{ shape: "circle", center: v(), r: 1.5 },
{ shape: "arc", center: v(), r: 1, a0: 0.2, a1: 2 },
{ shape: "text", at: v(), text: "A", height: 0.3, angle: 0 },
{ shape: "dimension", pts: [v(), v(), v()], offset: 0.5 },
] as Drawing2D["geom"][];
return geoms.map((geom, i) => ({ ...base, id: `d${i}`, geom }) as Drawing2D);
}
/** Kern-Dokument == TS-Leseansicht (JSON). */
function expectMirror(): void {
const p = st().project;
expect(JSON.parse(storeDocument(p).json())).toEqual(JSON.parse(JSON.stringify(p)));
}
beforeEach(() => {
st().setProject(structuredClone(sampleProject));
st().clearHistory();
});
describe("applyChange", () => {
it("Ops gehen ohne Differenz an den Kern: ein Undo-Schritt, Protokoll = genau diese Ops", () => {
const before = st().project;
const w = before.walls[0];
const ops = patchItem(before, "walls", w.id, { height: 3.3 });
st().applyChange(ops);
expect(st().project.walls[0].height).toBe(3.3);
// Unveränderte Elemente und Listen behalten ihre Identität.
expect(st().project.walls[1]).toBe(before.walls[1]);
expect(st().project.drawingLevels).toBe(before.drawingLevels);
expect(st().recentOps().at(-1)).toEqual(ops);
expect(st().undoDepth).toBe(1);
st().undo();
expect(st().project.walls[0].height).toBe(w.height);
expectMirror();
});
it("leere Ops: kein Schritt; NaN: abgelehnt, Projekt unverändert", () => {
const before = st().project;
st().applyChange([]);
st().applyChange((p) => patchItem(p, "walls", "gibt-es-nicht", { height: 1 }));
expect(st().project).toBe(before);
expect(st().undoDepth).toBe(0);
st().applyChange((p) => patchItem(p, "walls", p.walls[0].id, { height: NaN }));
expect(st().project).toBe(before);
expect(st().undoDepth).toBe(0);
});
it("coalesceKey: Serie = ein Schritt; setProject(opsMutation) nimmt die Ops direkt", () => {
const id = st().project.walls[0].id;
for (let i = 0; i < 50; i++) st().applyChange((p) => patchItem(p, "walls", id, { height: 2 + i / 100 }), "drag");
expect(st().undoDepth).toBe(1);
const m = opsMutation((p) => removeItems(p, "walls", [id]));
st().setProject(m);
expect(st().recentOps().at(-1)).toEqual([{ kind: "remove", collection: "walls", ids: [id] }]);
expect(st().undoDepth).toBe(2);
st().undo();
st().undo();
expect(st().project.walls[0].height).toBe(sampleProject.walls[0].height);
expectMirror();
});
it("groupChanges: mehrere Aktionen = ein Undo-Schritt", () => {
const p0 = st().project;
st().groupChanges(() => {
st().patchLevel(p0.drawingLevels[0].id, { linePoints: undefined, name: "X" });
st().setProject(opsMutation((p) => removeItems(p, "walls", [p.walls[0].id, p.walls[1].id])));
});
expect(st().undoDepth).toBe(1);
st().undo();
expect(st().project).toEqual(p0);
});
});
describe("groupChanges mit Schlüssel", () => {
it("Griff-Zug mit mitgeführten Ecken: alle Mausschritte = ein Undo-Schritt", () => {
const p0 = st().project;
const [a, b] = p0.walls;
for (let i = 0; i < 30; i++) {
st().groupChanges(() => {
st().moveElementByOf(null, a.id, { x: 0.01, y: 0 });
st().moveGripOf(null, b.id, 0, { x: b.start.x + (i + 1) * 0.01, y: b.start.y });
}, `bodyDrag::${a.id}`);
}
expect(st().undoDepth).toBe(1);
st().undo();
expect(st().project).toEqual(p0);
expectMirror();
});
});
describe("Zufallsfolgen der umgestellten Aktionen", () => {
it("Leseansicht = Kern, jede Aktion = applyOps(vorher, ihre Ops), Undo/Redo exakt", () => {
for (let seed = 1; seed <= 12; seed++) {
const r = rng(seed);
const start: Project = { ...structuredClone(sampleProject), drawings2d: drawings(r) };
setState({ project: start });
st().clearHistory();
const v = (): Vec2 => ({ x: r() * 10, y: r() * 10 });
let committed = 0;
for (let k = 0; k < 60; k++) {
const s = st();
const p = s.project;
const wid = p.walls[Math.floor(r() * p.walls.length)]?.id ?? "x";
const did = p.drawings2d[Math.floor(r() * p.drawings2d.length)]?.id ?? "x";
const lid = p.drawingLevels[Math.floor(r() * p.drawingLevels.length)]?.id ?? "x";
const cid = p.ceilings?.[0]?.id ?? "x";
const rmid = p.rooms?.[0]?.id ?? "x";
const idx = Math.floor(r() * 4);
const n = Math.floor(r() * 14);
const depth = s.undoDepth;
try {
switch (n) {
case 0: s.moveGripOf(null, wid, idx % 2, v()); break;
case 1: s.moveGripOf(did, null, idx % 2, v()); break;
case 2: s.moveElementByOf(did, null, v()); break;
case 3: s.moveEdgeOf(null, wid, 0, 1, v()); break;
case 4: s.updateWall(wid, { height: 2 + r() }); break;
case 5: s.setElementColor("drawing2d", did, "#abcdef"); break;
case 6: s.commitTransformOn({ wallIds: [wid], drawingId: did }, idx % 2 ? "move" : "rotate", [v(), v(), v()], idx < 2 ? "move" : "copy", 1); break;
case 7: s.moveCeilingBy(cid, v()); break;
case 8: s.moveRoomGrip(rmid, idx, v()); break;
case 9: s.toggleLevelVisible(lid); break;
case 10: s.patchLevel(lid, { floorHeight: 2.5 + r() }); break;
case 11: s.setWallThickness(wid, 0.1 + r() * 0.3); break;
case 12: s.resizeElement("drawing2d", did, 1 + r(), 1 + r(), { fx: 0, fy: 0 }); break;
case 13: s.setProject(opsMutation((q) => removeItems(q, "drawings2d", [did]))); break;
}
} catch {
continue; // ungültige Griff-Indizes (z. B. Kante einer kurzen Polylinie) — wie bisher
}
if (st().project !== p) {
committed++;
// Ein Schritt mehr — oder gleich viele, wenn dieselbe Griff-Serie verschmolzen wurde.
expect(st().undoDepth - depth).toBeGreaterThanOrEqual(0);
expect(st().undoDepth - depth).toBeLessThanOrEqual(1);
expect(st().project).toEqual(applyOps(p, st().recentOps().at(-1)!));
}
}
expect(committed).toBeGreaterThan(30);
expectMirror();
const end = JSON.stringify(st().project);
while (st().canUndo) st().undo();
expect(JSON.stringify(st().project)).toBe(JSON.stringify(start));
expectMirror();
while (st().canRedo) st().redo();
expect(JSON.stringify(st().project)).toBe(end);
expectMirror();
}
});
});
+29
View File
@@ -7,6 +7,7 @@
import { describe, it, expect } from "vitest";
import {
activeGroupOps,
addNewElementsToActiveGroup,
applyGroupDimming,
applyGroupDimmingToPlan,
@@ -21,6 +22,9 @@ import {
import type { Primitive } from "../plan/generatePlan/shared";
import { materializeUnderlay, type Plan } from "../plan/generatePlan";
import type { Drawing2D, Group, Project } from "../model/types";
import { applyOps } from "../core/ops";
import type { CoreOp } from "../core/ops";
import { addItems, replaceItem } from "../core/opsBuild";
const EMPTY_MEM = {
wallIds: [] as string[],
@@ -261,6 +265,31 @@ describe("addNewElementsToActiveGroup", () => {
});
});
describe("activeGroupOps ([K4] S3: Ops statt Differenz)", () => {
const mk = (id: string): Group => ({ id, wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] });
const line = (id: string) =>
({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number];
const wall = (id: string) => ({ id, start: { x: 0, y: 0 }, end: { x: 1, y: 0 } }) as unknown as Project["walls"][number];
it("gleiches Ergebnis wie addNewElementsToActiveGroup, Zufall", () => {
let x = 11;
const r = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
for (let n = 0; n < 200; n++) {
const before: Project = { ...project([mk("g1"), mk("g2")]), drawings2d: [line("d0")], walls: [wall("w0")] };
const ops: CoreOp[] = [];
const k = Math.floor(r() * 4);
if (k >= 1) ops.push(...addItems("drawings2d", [line(`a${n}`), line(`b${n}`)], r() < 0.5 ? 0 : undefined));
if (k >= 2) ops.push(...addItems("walls", [wall(`w${n}x`)]));
if (k >= 3) ops.push(replaceItem("drawings2d", { ...line("d0"), color: "#f00" }));
const path = r() < 0.2 ? [] : r() < 0.5 ? ["g1"] : ["g2", "g1", "gx"];
const after = applyOps(before, ops);
const legacy = addNewElementsToActiveGroup(before, after, path);
const viaOps = applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]);
expect(viaOps).toEqual(legacy);
}
});
});
describe("ungroup", () => {
it("löst genau EIN Level auf; Untergruppen bleiben als eigene Gruppen bestehen", () => {
const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
+54
View File
@@ -9,6 +9,10 @@ import type { Drawing2D, Group, Project } from "../model/types";
import type { Plan, UnderlayGroup } from "../core";
import { uniqueId } from "../tools/types";
import type { Primitive } from "../core";
import { applyOps } from "../core";
import type { CoreOp } from "../core";
import { itemsOf, patchItem } from "../core";
import type { EntityCollection } from "../core";
/** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */
export interface GroupMembership {
@@ -292,6 +296,56 @@ export function addNewElementsToActiveGroup(
};
}
/** Liste je Mitgliedsart. */
const COLLECTION_OF: Record<MemberKind, EntityCollection> = {
wallIds: "walls",
drawingIds: "drawings2d",
ceilingIds: "ceilings",
roomIds: "rooms",
stairIds: "stairs",
columnIds: "columns",
roofIds: "roofs",
openingIds: "openings",
};
/**
* Wie {@link addNewElementsToActiveGroup}, für eine Änderung als Ops ([K4] S3): die zusätzlichen
* Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen — ohne Differenz
* über alle Listen. Leer ohne aktive Gruppe oder ohne neue Elemente.
*/
export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] {
if (groupPath.length === 0) return [];
const addedIds = new Set<string>();
const touched = new Set<string>();
for (const op of ops) {
if (op.kind !== "add") continue;
touched.add(op.collection);
for (const e of op.items) addedIds.add(e.id);
}
if (addedIds.size === 0) return [];
const after = applyOps(before, ops);
const activeId = groupPath[groupPath.length - 1];
const g = (after.groups ?? []).find((x) => x.id === activeId);
if (!g) return [];
const added = { ...EMPTY_MEMBERSHIP };
for (const k of KEYS) {
const coll = COLLECTION_OF[k];
if (!touched.has(coll)) continue;
// Reihenfolge wie in der Liste (wie `newIds`); vorher vorhandene ids sind nie neu.
const existed = new Set<string>();
for (const e of itemsOf(before, coll)) {
const id = (e as { id: string }).id;
if (addedIds.has(id)) existed.add(id);
}
added[k] = itemsOf(after, coll)
.map((e) => (e as { id: string }).id)
.filter((id) => addedIds.has(id) && !existed.has(id));
}
if (KEYS.every((k) => added[k].length === 0)) return [];
const merged: Group = { ...g, ...mergeMembership(g, added) };
return patchItem(after, "groups", activeId, () => merged);
}
/**
* Erzeugt eine neue Gruppe aus einer Mengen-Auswahl (+ optional bereits
* gewählte Gruppen, die dabei als Untergruppen verschachtelt werden — „zwei
+222 -355
View File
File diff suppressed because it is too large. Load diff
+20 -7
View File
@@ -92,6 +92,11 @@ export function useGripEditing(opts: {
moveRoomBy: (id: string, delta: Vec2) => void;
moveCeilingBy: (id: string, delta: Vec2) => void;
moveElementByOf: (drawingId: string | null, wallId: string | null, delta: Vec2) => void;
/**
* Fasst mehrere Änderungen zu EINEM Undo-Schritt zusammen ([K4] S3, Store `groupChanges`); mit
* Schlüssel schliessen die Mausschritte desselben Zugs an denselben Schritt an.
*/
groupChanges?: (fn: () => void, coalesceKey?: string) => void;
}) {
const {
project,
@@ -129,6 +134,7 @@ export function useGripEditing(opts: {
moveCeilingBy,
moveElementByOf,
} = opts;
const groupChanges = opts.groupChanges ?? ((fn: () => void) => fn());
// Bewegpunkt (Move-Handle) einer Treppe: liegt auf der Treppe (Mitte des
// ersten Laufs bei gerade/L, Zentrum bei Wendel) und verschiebt beim Ziehen
@@ -1000,7 +1006,8 @@ export function useGripEditing(opts: {
};
/** Ausstehenden Zug jetzt in das Projekt schreiben (EINE Mutation). */
const commitPendingGrip = () => {
const commitPendingGrip = () => groupChanges(commitPendingGripChanges);
const commitPendingGripChanges = () => {
const ph = pendingSheetHeightRef.current;
pendingSheetHeightRef.current = null;
if (ph) {
@@ -1053,7 +1060,8 @@ export function useGripEditing(opts: {
};
/** Aufgeschobenes Körper-Verschieben jetzt ins Projekt schreiben. */
const commitPendingBody = () => {
const commitPendingBody = () => groupChanges(commitPendingBodyChanges);
const commitPendingBodyChanges = () => {
const pwm = pendingWallMoveRef.current;
pendingWallMoveRef.current = null;
sheetDuRef.current = null;
@@ -1436,16 +1444,21 @@ export function useGripEditing(opts: {
setDraft({ preview: bodyPreviewShapes(), vertices: [], snap: null });
return;
}
moveElementByOf(moveDrawingId, moveWallId, delta);
// Beim ersten Move-Event die Koinzidenz-Gruppe einmalig bestimmen (Snapshot
// VOR der ersten Mutation der Siblings). Danach inkrementell mitführen.
if (moveCoincidentRef.current === null) {
moveCoincidentRef.current = findMoveCoincident2D(moveDrawingId, moveWallId);
}
for (const c of moveCoincidentRef.current) {
c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y };
moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator);
}
const coincident = moveCoincidentRef.current;
// Element + mitgeführte Ecken: je Mausschritt eine Gruppe, die Schritte desselben Zugs
// schliessen an denselben Undo-Schritt an.
groupChanges(() => {
moveElementByOf(moveDrawingId, moveWallId, delta);
for (const c of coincident) {
c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y };
moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator);
}
}, `bodyDrag:${moveDrawingId ?? ""}:${moveWallId ?? ""}`);
},
// Kanten-Griff ziehen. Zwei Verhalten (Zielpunkt jeweils ABSOLUT relativ
// zum ORIGINALEN Anker `edge.mid`, angewandt über applyEdgeToward — s. dort):
+13 -16
View File
@@ -5,6 +5,7 @@
//
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { opsMutation, patchItem, removeItems } from "../core";
import type { Project, Vec2 } from "../model/types";
import type { CategoryDisplayResolver } from "../core";
import type { DisplayResolver } from "../viewport/Viewport3D";
@@ -168,14 +169,11 @@ export function useMouseSelectionHandlers(opts: {
const id = editTextId;
if (!id) return;
setProject(
(p) => ({
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === id && d.geom.shape === "text"
? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } }
: d,
opsMutation((p) =>
patchItem(p, "drawings2d", id, (d) =>
d.geom.shape === "text" ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } : d,
),
}),
),
`commitTextEdit:${id}`,
);
};
@@ -186,15 +184,14 @@ export function useMouseSelectionHandlers(opts: {
const closeTextEdit = () => {
const id = editTextId;
if (id) {
setProject((p) => {
const d = p.drawings2d.find((x) => x.id === id);
// `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) —
// reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde.
if (d && d.geom.shape === "text" && d.geom.text.trim() === "") {
return { ...p, drawings2d: p.drawings2d.filter((x) => x.id !== id) };
}
return p;
});
setProject(
opsMutation((p) => {
const d = p.drawings2d.find((x) => x.id === id);
// `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) —
// reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde.
return d && d.geom.shape === "text" && d.geom.text.trim() === "" ? removeItems(p, "drawings2d", [id]) : [];
}),
);
}
setEditTextId(null);
setEditTextMinHeightM(null);
+59 -68
View File
@@ -8,6 +8,7 @@
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { applyFillMode } from "./fillMode";
import { opsMutation, patchItem } from "../core";
import { useMemo, type RefObject } from "react";
import type { DrawingLevel, Layout, Project } from "../model/types";
import { resolvePenColor } from "../model/penSets";
@@ -474,21 +475,19 @@ export function usePanelHostBase(opts: {
},
onSetSelectionFillMode: (mode) => {
if (selection?.kind !== "drawing2d") return;
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => (d.id === selection.id ? applyFillMode(d, p.hatches, mode) : d)),
}));
const id = selection.id;
setProject(opsMutation((p) => patchItem(p, "drawings2d", id, (d) => applyFillMode(d, p.hatches, mode))));
},
onSetSelectionFillOpacity: (opacity) => {
if (selection?.kind === "drawing2d")
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => {
if (d.id !== selection.id) return d;
const { fillOpacity: _old, ...rest } = d;
return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) };
}),
}));
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", selection.id, (d) => {
const { fillOpacity: _old, ...rest } = d;
return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) };
}),
),
);
},
onSetSelectionOpacity: (opacity) => {
// Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der
@@ -497,15 +496,13 @@ export function usePanelHostBase(opts: {
// Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches
// Feld gesetzt wird, entscheidet die Form.
if (selection?.kind === "drawing2d")
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => {
if (d.id !== selection.id) return d;
return d.geom.shape === "image"
? { ...d, geom: { ...d.geom, opacity } }
: { ...d, opacity };
}),
}));
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", selection.id, (d) =>
d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } : { ...d, opacity },
),
),
);
else if (selection?.kind === "layoutAnnotation" && activeLayout)
patchOpenLayout(activeLayout.id, (l) =>
patchAnnotationInLayout(l, selection.id, { opacity }),
@@ -571,44 +568,39 @@ export function usePanelHostBase(opts: {
},
onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex),
onSetDashScale: (drawingId, scale) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => (d.id === drawingId ? { ...d, dashScale: scale } : d)),
})),
setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))),
onSetDetailRefLabel: (drawingId, label) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === drawingId && d.geom.shape === "detailref"
? { ...d, geom: { ...d.geom, label } }
: d,
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) =>
d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, label } } : d,
),
),
})),
),
onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => {
if (d.id !== drawingId || d.geom.shape !== "detailref") return d;
const geom = { ...d.geom };
if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId;
else delete geom.sheetLayoutId;
return { ...d, geom };
}),
})),
onSetDetailRefSheetLabel: (drawingId, sheetLabel) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === drawingId && d.geom.shape === "detailref"
? { ...d, geom: { ...d.geom, sheetLabel } }
: d,
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) => {
if (d.geom.shape !== "detailref") return d;
const geom = { ...d.geom };
if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId;
else delete geom.sheetLayoutId;
return { ...d, geom };
}),
),
})),
),
onSetDetailRefSheetLabel: (drawingId, sheetLabel) =>
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) =>
d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, sheetLabel } } : d,
),
),
),
onSetHatchPlacement: (drawingId, patch) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) => {
if (d.id !== drawingId) return d;
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) => {
const next = { ...d };
// `null` = zurück auf die Ressource (Feld entfernen).
if ("angleDeg" in patch)
@@ -618,24 +610,23 @@ export function usePanelHostBase(opts: {
if ("origin" in patch)
patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin);
return next;
}),
})),
}),
),
),
onSetEndMarks: (drawingId, patch) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === drawingId ? { ...d, endMarks: { ...d.endMarks, ...patch } } : d,
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })),
),
})),
),
onSetDimensionStyle: (drawingId, patch) =>
setProject((p) => ({
...p,
drawings2d: p.drawings2d.map((d) =>
d.id === drawingId && d.geom.shape === "dimension"
? { ...d, geom: { ...d.geom, ...patch } }
: d,
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) =>
d.geom.shape === "dimension" ? { ...d, geom: { ...d.geom, ...patch } } : d,
),
),
})),
),
onSetSelectionBackgroundPen: (penId) => {
if (!selection) return;
const background = penId ? resolvePenColor(project, penId) : undefined;
+71 -37
View File
@@ -7,7 +7,7 @@
// P distribute — Original bleibt + N Kopien gleichmäßig zwischen Original und Ziel.
//
// Bezeichner englisch, UI-Text via t() (CONVENTIONS.md). Reine Funktionen + Geometrie;
// die App hält den State und wendet `commitTransform` immutabel an.
// die App hält den State und wendet die Ops aus `transformOps` an ([K4] S3).
import { transformSolid } from "../core";
import type {
@@ -32,6 +32,10 @@ import { drawingPreviewShapes } from "./drawingPreview";
import { mvGeom, reversesOrientation, scaleFactor, scaleGeom } from "../core";
import { uniqueId } from "./types";
import type { CommandSelection } from "../commands/types";
import { applyOps } from "../core";
import type { CoreOp } from "../core";
import { addItems, opsMutation, patchItems } from "../core";
import type { ProjectMutation } from "../core";
export type TransformOp = "move" | "rotate" | "mirror" | "scale";
export type CopyMode = "move" | "copy" | "array" | "distribute"; // U / I / O / P
@@ -497,17 +501,20 @@ export function rotateGizmoShapes(center: Vec2, refPoint: Vec2, cursor: Vec2): D
// ── Commit ───────────────────────────────────────────────────────────────────
/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien). */
export function commitTransform(
/**
* Die Transformation als Ops ([K4] S3): `replace` je bewegtem Original (nur bei „move"), `add` der
* Kopien je Liste. Liest nur die gewählten Elemente — keine Projekt-Differenz über alle Wände.
*/
export function transformOps(
project: Project,
sel: TransformSelection,
op: TransformOp,
pts: Vec2[],
mode: CopyMode,
count: number,
): Project {
): CoreOp[] {
const items = gatherItems(project, sel, op);
if (items.length === 0) return project;
if (items.length === 0) return [];
const wallIds = new Set(sel.wallIds);
// Bei einer Skalierung müssen auch Grössenfelder (Radius/Schrifthöhe/…)
// mitziehen — dafür `scaleGeom` statt `mvGeom` (s. dort); analog für
@@ -517,18 +524,11 @@ export function commitTransform(
const stairAt = (s: Stair, fn: (p: Vec2) => Vec2, t: number): Stair =>
mvStair(s, fn, op === "scale" ? scaleFactor(pts, t) : 1);
let walls = project.walls;
let drawings2d = project.drawings2d;
let extrudedSolids = project.extrudedSolids ?? [];
let columns = project.columns ?? [];
let ceilings = project.ceilings ?? [];
let roofs = project.roofs ?? [];
let stairs = project.stairs ?? [];
let rooms = project.rooms ?? [];
const ceilingIds = new Set(sel.ceilingIds ?? []);
const roofIds = new Set(sel.roofIds ?? []);
const stairIds = new Set(sel.stairIds ?? []);
const roomIds = new Set(sel.roomIds ?? []);
const ops: CoreOp[] = [];
// U (move): Original an die Endlage (t=1) transformieren. Objekt-Sperre
// (`locked`) überall mitgeprüft — dieselbe Semantik wie `gatherItems`
@@ -537,13 +537,20 @@ export function commitTransform(
// genau diese Art von Doppel-Pflege).
if (movesOriginal(mode)) {
const fn = transformFn(op, pts, 1);
walls = walls.map((w) =>
wallIds.has(w.id) && !w.locked ? { ...w, start: fn(w.start), end: fn(w.end) } : w,
ops.push(
...patchItems(project, "walls", (w) => wallIds.has(w.id) && !w.locked, (w) => ({
...w,
start: fn(w.start),
end: fn(w.end),
})),
);
const moveDrawIds = drawingIdSet(sel);
if (moveDrawIds.size > 0) {
drawings2d = drawings2d.map((d) =>
moveDrawIds.has(d.id) && !d.locked ? { ...d, geom: geomAt(d.geom, fn, 1) } : d,
ops.push(
...patchItems(project, "drawings2d", (d) => moveDrawIds.has(d.id) && !d.locked, (d) => ({
...d,
geom: geomAt(d.geom, fn, 1),
})),
);
}
if (sel.extrudedSolidId) {
@@ -552,19 +559,21 @@ export function commitTransform(
// nutzt) müssen mitziehen — sonst weicht das 3D-Volumen sichtbar von
// der Grundriss-Kontur ab (nur `center` mitzuführen genügt nicht).
const f1 = op === "scale" ? scaleFactor(pts, 1) : 1;
extrudedSolids = extrudedSolids.map((s) => (s.id === sel.extrudedSolidId ? transformSolid(s, fn, f1) : s));
const solidId = sel.extrudedSolidId;
ops.push(...patchItems(project, "extrudedSolids", (s) => s.id === solidId, (s) => transformSolid(s, fn, f1)));
}
if (sel.columnId) {
columns = columns.map((c) => (c.id === sel.columnId && !c.locked ? mvColumn(c, fn) : c));
const columnId = sel.columnId;
ops.push(...patchItems(project, "columns", (c) => c.id === columnId && !c.locked, (c) => mvColumn(c, fn)));
}
if (ceilingIds.size > 0)
ceilings = ceilings.map((c) => (ceilingIds.has(c.id) && !c.locked ? mvCeiling(c, fn) : c));
if (roofIds.size > 0 && roofTransformAllowed(op)) {
roofs = roofs.map((r) => (roofIds.has(r.id) && !r.locked ? mvRoof(r, fn) : r));
}
ops.push(...patchItems(project, "ceilings", (c) => ceilingIds.has(c.id) && !c.locked, (c) => mvCeiling(c, fn)));
if (roofIds.size > 0 && roofTransformAllowed(op))
ops.push(...patchItems(project, "roofs", (r) => roofIds.has(r.id) && !r.locked, (r) => mvRoof(r, fn)));
if (stairIds.size > 0)
stairs = stairs.map((s) => (stairIds.has(s.id) && !s.locked ? stairAt(s, fn, 1) : s));
if (roomIds.size > 0) rooms = rooms.map((r) => (roomIds.has(r.id) && !r.locked ? mvRoom(r, fn) : r));
ops.push(...patchItems(project, "stairs", (s) => stairIds.has(s.id) && !s.locked, (s) => stairAt(s, fn, 1)));
if (roomIds.size > 0)
ops.push(...patchItems(project, "rooms", (r) => roomIds.has(r.id) && !r.locked, (r) => mvRoom(r, fn)));
}
// Kopien anhängen (I/O/P bzw. mirror copy).
@@ -614,16 +623,41 @@ export function commitTransform(
}
}
}
return {
...project,
walls: newWalls.length ? [...walls, ...newWalls] : walls,
drawings2d: newDrawings.length ? [...drawings2d, ...newDrawings] : drawings2d,
extrudedSolids: newSolids.length ? [...extrudedSolids, ...newSolids] : extrudedSolids,
columns: newColumns.length ? [...columns, ...newColumns] : columns,
ceilings: newCeilings.length ? [...ceilings, ...newCeilings] : ceilings,
roofs: newRoofs.length ? [...roofs, ...newRoofs] : roofs,
stairs: newStairs.length ? [...stairs, ...newStairs] : stairs,
rooms: newRooms.length ? [...rooms, ...newRooms] : rooms,
};
ops.push(
...addItems("walls", newWalls),
...addItems("drawings2d", newDrawings),
...addItems("extrudedSolids", newSolids),
...addItems("columns", newColumns),
...addItems("ceilings", newCeilings),
...addItems("roofs", newRoofs),
...addItems("stairs", newStairs),
...addItems("rooms", newRooms),
);
return ops;
}
/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien), über {@link transformOps}. */
export function commitTransform(
project: Project,
sel: TransformSelection,
op: TransformOp,
pts: Vec2[],
mode: CopyMode,
count: number,
): Project {
return applyOps(project, transformOps(project, sel, op, pts, mode, count));
}
/**
* Wie {@link commitTransform}, als Projekt → Projekt-Funktion mit mitgeführten Ops (`opsMutation`) —
* für `CommandResult.commit`: `setProject` übergibt die Ops ohne Projekt-Differenz an den Kern.
*/
export function transformMutation(
sel: TransformSelection,
op: TransformOp,
pts: Vec2[],
mode: CopyMode,
count: number,
): ProjectMutation {
return opsMutation((p) => transformOps(p, sel, op, pts, mode, count));
}